import { useEffect, useState } from "react";
// import Taro, { useRouter } from '@tarojs/taro';
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components';
import {
  NavBar,
  Button,
  Cell,
  Tag,
  Toast
} from '@nutui/nutui-react-taro';
import {
  Phone,
  Location,
  Calendar,
  User,
  Edit,
  Share
} from '@nutui/icons-react-taro';
import './detail.scss';

// 已签约客户详情数据类型
interface CustomerDetail {
  id: string;
  companyName: string;
  contactPerson: string;
  phone: string;
  address: string;
  signDate: string;
  contractInfo: {
    contractType: string;
    contractAmount: string;
    startDate: string;
    endDate: string;
    paymentMethod: string;
    paymentCycle: string;
    status: 'active' | 'expired' | 'terminated';
  };
  businessInfo: {
    industry: string;
    scale: string;
    registeredCapital: string;
    businessScope: string;
  };
  contactHistory: Array<{
    id: string;
    date: string;
    type: string;
    content: string;
    operator: string;
  }>;
}

const CustomerDetail = () => {
  // const router = useRouter();
  const [statusBarHeight, setStatusBarHeight] = useState<number>(0);
  const [customerDetail, setCustomerDetail] = useState<CustomerDetail | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [showToast, setShowToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');

  // 模拟客户详情数据
  const mockCustomerDetail: CustomerDetail = {
    id: '1',
    companyName: '广州雅虎信息科技公司',
    contactPerson: '张经理',
    phone: '13882223433',
    address: '广西南宁市良庆区五象大道401号五象新城1号楼1226室',
    signDate: '2025-08-15 10:23:33',
    contractInfo: {
      contractType: '服务合同',
      contractAmount: '500,000',
      startDate: '2025-08-15',
      endDate: '2026-08-14',
      paymentMethod: '分期付款',
      paymentCycle: '按季度付款',
      status: 'active'
    },
    businessInfo: {
      industry: '信息技术服务',
      scale: '中型企业',
      registeredCapital: '1000万元',
      businessScope: '软件开发、技术咨询、系统集成'
    },
    contactHistory: [
      {
        id: '1',
        date: '2025-08-20',
        type: '电话沟通',
        content: '讨论项目进度，客户反馈良好',
        operator: '李销售'
      },
      {
        id: '2',
        date: '2025-08-18',
        type: '现场拜访',
        content: '实地考察客户需求，确认技术方案',
        operator: '王工程师'
      },
      {
        id: '3',
        date: '2025-08-15',
        type: '合同签署',
        content: '正式签署服务合同，项目启动',
        operator: '张经理'
      }
    ]
  };

  const showToastMsg = (msg: string) => {
    setToastMsg(msg);
    setShowToast(true);
    setTimeout(() => setShowToast(false), 2000);
  };

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return '#52c41a';
      case 'expired':
        return '#ff6b35';
      case 'terminated':
        return '#ff4d4f';
      default:
        return '#999';
    }
  };

  const getStatusText = (status: string) => {
    switch (status) {
      case 'active':
        return '履行中';
      case 'expired':
        return '已到期';
      case 'terminated':
        return '已终止';
      default:
        return '未知';
    }
  };

  const handleCall = () => {
    if (customerDetail?.phone) {
      Taro.makePhoneCall({
        phoneNumber: customerDetail.phone
      });
    }
  };

  const handleEdit = () => {
    showToastMsg('编辑功能开发中');
  };

  const handleShare = () => {
    showToastMsg('分享功能开发中');
  };

  const handleAddContact = () => {
    showToastMsg('添加联系记录功能开发中');
  };

  const handleViewContract = () => {
    showToastMsg('查看合同详情功能开发中');
  };

  const handleRenewContract = () => {
    showToastMsg('续约功能开发中');
  };

  const loadCustomerDetail = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 800));
      setCustomerDetail(mockCustomerDetail);
    } catch (error) {
      showToastMsg('加载失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    Taro.getSystemInfo({
      success: (res) => {
        setStatusBarHeight(Number(res.statusBarHeight));
      },
    });

    loadCustomerDetail();
  }, []);

  if (loading) {
    return (
      <View className="customer-detail-page">
        <View className="loading-container">
          <Text>加载中...</Text>
        </View>
      </View>
    );
  }

  if (!customerDetail) {
    return (
      <View className="customer-detail-page">
        <View className="error-container">
          <Text>客户信息加载失败</Text>
          <Button onClick={loadCustomerDetail}>重新加载</Button>
        </View>
      </View>
    );
  }

  return (
    <View className="customer-detail-page">
      {/* 头部背景 */}
      <View className="header-bg" style={{ height: '180px' }} />

      {/* 导航栏 */}
      <NavBar
        style={{
          marginTop: `${statusBarHeight}px`,
          backgroundColor: 'transparent',
          color: '#ffffff'
        }}
        onBackClick={() => Taro.navigateBack()}
        right={
          <View className="nav-actions">
            <Edit size={20} color="#ffffff" onClick={handleEdit} />
            <Share size={20} color="#ffffff" onClick={handleShare} />
          </View>
        }
      >
        <Text style={{ color: '#ffffff', fontSize: '18px', fontWeight: 'bold' }}>
          客户详情
        </Text>
      </NavBar>

      {/* 客户基本信息 */}
      <View className="detail-container">
        <View className="customer-card">
          <View className="customer-header">
            <View className="company-info">
              <Text className="company-name">{customerDetail.companyName}</Text>
              <Tag
                color={getStatusColor(customerDetail.contractInfo.status)}
                plain
              >
                {getStatusText(customerDetail.contractInfo.status)}
              </Tag>
            </View>
          </View>

          <View className="contact-info">
            <View className="contact-item">
              <User size={16} color="#666" />
              <Text className="contact-text">{customerDetail.contactPerson}</Text>
            </View>
            <View className="contact-item" onClick={handleCall}>
              <Phone size={16} color="#52c41a" />
              <Text className="contact-text phone">{customerDetail.phone}</Text>
            </View>
            <View className="contact-item">
              <Location size={16} color="#666" />
              <Text className="contact-text">{customerDetail.address}</Text>
            </View>
            <View className="contact-item">
              <Calendar size={16} color="#666" />
              <Text className="contact-text">签约时间：{customerDetail.signDate}</Text>
            </View>
          </View>
        </View>

        {/* 合同信息 */}
        <View className="info-section">
          <View className="section-header">
            <Text className="section-title">合同信息</Text>
            <Button size="small" onClick={handleViewContract}>查看合同</Button>
          </View>
          <View className="info-content">
            <Cell title="合同类型" extra={customerDetail.contractInfo.contractType} />
            <Cell title="合同金额" extra={`¥${customerDetail.contractInfo.contractAmount}`} />
            <Cell title="合同期限" extra={`${customerDetail.contractInfo.startDate} 至 ${customerDetail.contractInfo.endDate}`} />
            <Cell title="付款方式" extra={customerDetail.contractInfo.paymentMethod} />
            <Cell title="付款周期" extra={customerDetail.contractInfo.paymentCycle} />
          </View>
        </View>

        {/* 企业信息 */}
        <View className="info-section">
          <View className="section-header">
            <Text className="section-title">企业信息</Text>
          </View>
          <View className="info-content">
            <Cell title="所属行业" extra={customerDetail.businessInfo.industry} />
            <Cell title="企业规模" extra={customerDetail.businessInfo.scale} />
            <Cell title="注册资本" extra={customerDetail.businessInfo.registeredCapital} />
            <Cell title="经营范围" extra={customerDetail.businessInfo.businessScope} />
          </View>
        </View>

        {/* 联系记录 */}
        <View className="info-section">
          <View className="section-header">
            <Text className="section-title">联系记录</Text>
            <Button size="small" onClick={handleAddContact}>添加记录</Button>
          </View>
          <View className="contact-history">
            {customerDetail.contactHistory.map((record) => (
              <View key={record.id} className="history-item">
                <View className="history-header">
                  <Text className="history-type">{record.type}</Text>
                  <Text className="history-date">{record.date}</Text>
                </View>
                <Text className="history-content">{record.content}</Text>
                <Text className="history-operator">操作人：{record.operator}</Text>
              </View>
            ))}
          </View>
        </View>
      </View>

      {/* 底部操作按钮 */}
      <View className="fixed-bottom">
        <View className="action-buttons">
          <Button className="action-btn call-btn" onClick={handleCall}>
            <Phone size={16} />
            拨打电话
          </Button>
          <Button className="action-btn renew-btn" onClick={handleRenewContract}>
            续约
          </Button>
        </View>
      </View>

      {/* Toast提示 */}
      <Toast
        visible={showToast}
        content={toastMsg}
        duration={2000}
      />
    </View>
  );
};

export default CustomerDetail;
