import { useEffect, useState } from "react";
import Taro, { useRouter } from '@tarojs/taro';
import { View, Text } from '@tarojs/components';
import {
  NavBar,
  Form,
  Input,
  Button,
  DatePicker,
  Picker,
  TextArea,
  Cell,
  Switch,
  Toast
} from '@nutui/nutui-react-taro';
import { ArrowDown } from '@nutui/icons-react-taro';
import './sign.scss';

// 签约表单数据类型
interface SignFormData {
  customerId: string;
  contractType: string;
  contractAmount: string;
  contractDate: string;
  startDate: string;
  endDate: string;
  paymentMethod: string;
  paymentCycle: string[];
  specialTerms: string;
  isUrgent: boolean;
  contactPerson: string;
  contactPhone: string;
  signLocation: string;
  remarks: string;
}

const CustomerSign = () => {
  const router = useRouter();
  const [statusBarHeight, setStatusBarHeight] = useState<number>(0);
  const [formData, setFormData] = useState<SignFormData>({
    customerId: '',
    contractType: '',
    contractAmount: '',
    contractDate: '',
    startDate: '',
    endDate: '',
    paymentMethod: '',
    paymentCycle: [],
    specialTerms: '',
    isUrgent: false,
    contactPerson: '',
    contactPhone: '',
    signLocation: '',
    remarks: ''
  });
  const [loading, setLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMsg, setToastMsg] = useState('');

  // 合同类型选项
  const contractTypes = [
    { text: '服务合同', value: 'service' },
    { text: '销售合同', value: 'sales' },
    { text: '代理合同', value: 'agency' },
    { text: '合作协议', value: 'cooperation' }
  ];

  // 付款方式选项
  const paymentMethods = [
    { text: '一次性付款', value: 'onetime' },
    { text: '分期付款', value: 'installment' },
    { text: '月付', value: 'monthly' },
    { text: '季付', value: 'quarterly' },
    { text: '年付', value: 'yearly' }
  ];

  // 付款周期选项
  const paymentCycles = [
    { text: '签约后立即付款', value: 'immediate' },
    { text: '签约后7天内', value: '7days' },
    { text: '签约后15天内', value: '15days' },
    { text: '签约后30天内', value: '30days' },
    { text: '按月付款', value: 'monthly' }
  ];

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

  const handleInputChange = (field: keyof SignFormData, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }));
  };

  const validateForm = (): boolean => {
    if (!formData.contractType) {
      showToastMsg('请选择合同类型');
      return false;
    }
    if (!formData.contractAmount) {
      showToastMsg('请输入合同金额');
      return false;
    }
    if (!formData.contractDate) {
      showToastMsg('请选择签约日期');
      return false;
    }
    if (!formData.startDate) {
      showToastMsg('请选择合同开始日期');
      return false;
    }
    if (!formData.endDate) {
      showToastMsg('请选择合同结束日期');
      return false;
    }
    if (!formData.paymentMethod) {
      showToastMsg('请选择付款方式');
      return false;
    }
    if (!formData.contactPerson) {
      showToastMsg('请输入联系人姓名');
      return false;
    }
    if (!formData.contactPhone) {
      showToastMsg('请输入联系电话');
      return false;
    }
    if (!formData.signLocation) {
      showToastMsg('请输入签约地点');
      return false;
    }
    return true;
  };

  const handleSubmit = async () => {
    if (!validateForm()) return;

    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1500));

      showToastMsg('签约成功！');

      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        Taro.navigateBack();
      }, 2000);
    } catch (error) {
      showToastMsg('签约失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const formatDate = (date: Date): string => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

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

    // 获取客户ID
    const { customerId } = router.params;
    if (customerId) {
      setFormData(prev => ({ ...prev, customerId }));
    }
  }, []);

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

      {/* 导航栏 */}
      <NavBar
        style={{
          marginTop: `${statusBarHeight}px`,
          backgroundColor: 'transparent',
          color: '#ffffff'
        }}
        onBackClick={() => Taro.navigateBack()}
      >
        <Text style={{ color: '#ffffff', fontSize: '18px', fontWeight: 'bold' }}>
          客户签约
        </Text>
      </NavBar>

      {/* 表单内容 */}
      <View className="form-container">
        <Form>
          {/* 基本信息 */}
          <View className="form-section">
            <View className="section-title">基本信息</View>

            <Form.Item label="合同类型" required>
              <Picker
                options={contractTypes}
                value={formData.contractType}
                onConfirm={(options) => handleInputChange('contractType', options[0]?.value)}
              >
                <Cell
                  className="picker-cell"
                  title={contractTypes.find(item => item.value === formData.contractType)?.text || '请选择合同类型'}
                  extra={<ArrowDown />}
                />
              </Picker>
            </Form.Item>

            <Form.Item label="合同金额" required>
              <Input
                placeholder="请输入合同金额"
                type="digit"
                value={formData.contractAmount}
                onChange={(value) => handleInputChange('contractAmount', value)}
              />
            </Form.Item>

            <Form.Item label="签约日期" required>
              <DatePicker
                value={formData.contractDate ? new Date(formData.contractDate) : new Date()}
                onConfirm={(options, value) => handleInputChange('contractDate', formatDate(value))}
              >
                <Cell
                  className="picker-cell"
                  title={formData.contractDate || '请选择签约日期'}
                  extra={<ArrowDown />}
                />
              </DatePicker>
            </Form.Item>
          </View>

          {/* 合同期限 */}
          <View className="form-section">
            <View className="section-title">合同期限</View>

            <Form.Item label="开始日期" required>
              <DatePicker
                value={formData.startDate ? new Date(formData.startDate) : new Date()}
                onConfirm={(options, value) => handleInputChange('startDate', formatDate(value))}
              >
                <Cell
                  className="picker-cell"
                  title={formData.startDate || '请选择开始日期'}
                  extra={<ArrowDown />}
                />
              </DatePicker>
            </Form.Item>

            <Form.Item label="结束日期" required>
              <DatePicker
                value={formData.endDate ? new Date(formData.endDate) : new Date()}
                onConfirm={(options, value) => handleInputChange('endDate', formatDate(value))}
              >
                <Cell
                  className="picker-cell"
                  title={formData.endDate || '请选择结束日期'}
                  extra={<ArrowDown />}
                />
              </DatePicker>
            </Form.Item>
          </View>

          {/* 付款信息 */}
          <View className="form-section">
            <View className="section-title">付款信息</View>

            <Form.Item label="付款方式" required>
              <Picker
                options={paymentMethods}
                value={formData.paymentMethod}
                onConfirm={(options) => handleInputChange('paymentMethod', options[0]?.value)}
              >
                <Cell
                  className="picker-cell"
                  title={paymentMethods.find(item => item.value === formData.paymentMethod)?.text || '请选择付款方式'}
                  extra={<ArrowDown />}
                />
              </Picker>
            </Form.Item>

            <Form.Item label="付款周期">
              <Picker
                options={paymentCycles}
                value={formData.paymentCycle}
                onConfirm={(options) => handleInputChange('paymentCycle', options[0]?.value)}
              >
                <Cell
                  className="picker-cell"
                  title={paymentCycles.find(item => item.value === formData.paymentCycle)?.text || '请选择付款周期'}
                  extra={<ArrowDown />}
                />
              </Picker>
            </Form.Item>
          </View>

          {/* 联系信息 */}
          <View className="form-section">
            <View className="section-title">联系信息</View>

            <Form.Item label="联系人" required>
              <Input
                placeholder="请输入联系人姓名"
                value={formData.contactPerson}
                onChange={(value) => handleInputChange('contactPerson', value)}
              />
            </Form.Item>

            <Form.Item label="联系电话" required>
              <Input
                placeholder="请输入联系电话"
                type="tel"
                value={formData.contactPhone}
                onChange={(value) => handleInputChange('contactPhone', value)}
              />
            </Form.Item>

            <Form.Item label="签约地点" required>
              <Input
                placeholder="请输入签约地点"
                value={formData.signLocation}
                onChange={(value) => handleInputChange('signLocation', value)}
              />
            </Form.Item>
          </View>

          {/* 其他信息 */}
          <View className="form-section">
            <View className="section-title">其他信息</View>

            <Form.Item label="特殊条款">
              <TextArea
                placeholder="请输入特殊条款（可选）"
                value={formData.specialTerms}
                onChange={(value) => handleInputChange('specialTerms', value)}
                rows={3}
              />
            </Form.Item>

            <Form.Item label="紧急处理">
              <Switch
                checked={formData.isUrgent}
                onChange={(value) => handleInputChange('isUrgent', value)}
              />
            </Form.Item>

            <Form.Item label="备注">
              <TextArea
                placeholder="请输入备注信息（可选）"
                value={formData.remarks}
                onChange={(value) => handleInputChange('remarks', value)}
                rows={3}
              />
            </Form.Item>
          </View>
        </Form>
      </View>

      {/* 底部提交按钮 */}
      <View className="fixed-bottom">
        <Button
          className="submit-btn"
          loading={loading}
          onClick={handleSubmit}
        >
          {loading ? '提交中...' : '确认签约'}
        </Button>
      </View>

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

export default CustomerSign;
