import { useEffect, useState } from 'react';
import { Button, Text } from '@tarojs/components';
import type { ReactNode } from 'react';
import { toast } from '../lib/api';
import { getBrandAssetsSync, loadBrandAssets } from '../lib/brand-assets';
import { openWecomCustomerServiceChat } from '../lib/wecom-cs';

export type ContactCsSessionContext = {
  orderId?: string;
  orderNo?: string;
  from?: string;
};

type ContactCsButtonProps = {
  className?: string;
  children?: ReactNode;
  /** 客服会话来源上下文，便于客服后台识别 */
  session?: ContactCsSessionContext;
};

const isWeapp = process.env.TARO_ENV === 'weapp';

/** 组装 session-from（微信限制约 1000 字符；原生小程序客服兜底用） */
export function buildCsSessionFrom(session?: ContactCsSessionContext): string {
  if (!session) return 'dukang|from=mini-user';
  const parts = ['dukang'];
  if (session.from) parts.push(`from=${session.from}`);
  if (session.orderNo) parts.push(`orderNo=${session.orderNo}`);
  if (session.orderId) parts.push(`orderId=${session.orderId}`);
  return parts.join('|');
}

function canOpenWecom(url: string, corpId: string) {
  return !!url.trim() && !!corpId.trim();
}

/**
 * C 端在线客服：
 * - weapp 且已配置 CorpID + kfid：调起企业微信「微信客服」
 * - weapp 未配 CorpID：回退 open-type=contact
 * - H5：有 kfid 则打开企微客服链接
 */
export default function ContactCsButton({
  className = '',
  children = '联系在线客服',
  session,
}: ContactCsButtonProps) {
  const [cs, setCs] = useState(() => getBrandAssetsSync());

  useEffect(() => {
    void loadBrandAssets().then(setCs);
  }, []);

  const wecomChatReady = canOpenWecom(cs.customerServiceWecomUrl, cs.wecomCorpId);
  const wecomWebReady = !!cs.customerServiceWecomUrl.trim();

  if (!isWeapp && !wecomWebReady) return null;

  async function openWecom() {
    try {
      if (isWeapp && wecomChatReady) {
        await openWecomCustomerServiceChat({
          url: cs.customerServiceWecomUrl,
          corpId: cs.wecomCorpId,
          session,
        });
        return;
      }
      if (typeof window !== 'undefined' && cs.customerServiceWecomUrl) {
        window.location.href = cs.customerServiceWecomUrl;
        return;
      }
      toast('请在微信内打开后联系客服');
    } catch (e) {
      toast(e instanceof Error ? e.message : '无法打开客服');
    }
  }

  if (wecomChatReady || (!isWeapp && wecomWebReady)) {
    return (
      <Button className={className} hoverClass="none" onClick={() => void openWecom()}>
        {typeof children === 'string' ? <Text>{children}</Text> : children}
      </Button>
    );
  }

  return (
    <Button
      className={className}
      openType="contact"
      sessionFrom={buildCsSessionFrom(session)}
      hoverClass="none"
    >
      {typeof children === 'string' ? <Text>{children}</Text> : children}
    </Button>
  );
}
