import { useEffect, useState } from 'react';
import { View, Text } from '@tarojs/components';
import '../../styles/redeem.css';
import Taro from '@tarojs/taro';
import PageShell from '../../components/PageShell';
import SubPageHeader from '../../components/SubPageHeader';
import ContactCsButton from '../../components/ContactCsButton';
import { toast } from '../../lib/api';
import { getBrandAssetsSync, loadBrandAssets } from '../../lib/brand-assets';

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

function dialPhone(phone: string) {
  const tel = phone.replace(/-/g, '');
  Taro.makePhoneCall({ phoneNumber: tel }).catch(() => toast('无法拨打电话'));
}

export default function CustomerServicePage() {
  const [brand, setBrand] = useState(() => getBrandAssetsSync());

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

  const phone = brand.customerServicePhone;
  const wecomReady = !!brand.customerServiceWecomUrl.trim() && !!brand.wecomCorpId.trim();
  const wecomUrlReady = !!brand.customerServiceWecomUrl.trim();

  const hint = isWeapp
    ? wecomReady
      ? '点击下方按钮，进入企业微信客服会话'
      : '点击下方按钮，进入在线客服会话'
    : wecomUrlReady
      ? '点击下方按钮进入企业微信客服，或拨打客服电话'
      : '请在微信小程序内打开以使用在线客服，或拨打客服电话';

  return (
    <PageShell variant="sub" className="cs-page">
      <SubPageHeader title="联系客服" />
      <View className="sub-page-body inset-page cs-body">
        <Text className="cs-brand">杜康好客客服</Text>
        <Text className="cs-hint">{hint}</Text>
        <Text className="cs-hours">工作时间：9:00 - 21:00</Text>

        {isWeapp || wecomUrlReady ? (
          <ContactCsButton className="cs-online-btn" session={{ from: 'customer-service' }} />
        ) : null}

        <View className={isWeapp || wecomUrlReady ? 'cs-phone-link' : 'cs-call-btn'} onClick={() => dialPhone(phone)}>
          <Text>
            {isWeapp || wecomUrlReady ? `或拨打客服电话 ${phone}` : '拨打客服电话'}
          </Text>
        </View>

        {!isWeapp && !wecomUrlReady ? (
          <Text className="cs-phone-display">{phone}</Text>
        ) : null}
      </View>
    </PageShell>
  );
}
