import {
  useState,
  useEffect,
  Card,
  Form,
  Input,
  Select,
  Switch,
  Button,
  Space,
  Radio,
  Checkbox,
  DatePicker,
  InputNumber,
  Divider,
  Alert,
  Tooltip,
  Modal,
  message,
  CheckCircleOutlined,
  CloseCircleOutlined,
  EditOutlined,
  SaveOutlined,
  UndoOutlined,
  ExclamationCircleOutlined,
  Option,
  TextArea,
  FC,
} from '@/imports';

interface HumanApprovalFormProps {
  taskId: string;
  aiSuggestion: any;
  onApprove: (formData: any) => void;
  onReject: (reason: string) => void;
  onModify: (modifiedData: any) => void;
  loading?: boolean;
}

export const HumanApprovalForm: FC<HumanApprovalFormProps> = ({
  taskId,
  aiSuggestion,
  onApprove,
  onReject,
  onModify,
  loading = false,
}) => {
  const [form] = Form.useForm();
  const [rejectReason, setRejectReason] = useState('');
  const [rejectModalVisible, setRejectModalVisible] = useState(false);
  const [isModified, setIsModified] = useState(false);
  const [originalSuggestion, setOriginalSuggestion] = useState(aiSuggestion);

  // 初始化表单数据
  useEffect(() => {
    form.setFieldsValue({
      ...aiSuggestion,
    });
    setOriginalSuggestion(aiSuggestion);
    setIsModified(false);
  }, [aiSuggestion, form]);

  // 检测表单修改
  const handleFormChange = () => {
    form.validateFields().then((values) => {
      const hasChanges = Object.keys(values).some((key) => {
        return JSON.stringify(values[key]) !== JSON.stringify(originalSuggestion[key]);
      });
      setIsModified(hasChanges);
    });
  };

  // 处理审批
  const handleApprove = () => {
    form.validateFields().then((values) => {
      onApprove(values);
    }).catch((error) => {
      message.error('Please fill in all required fields');
    });
  };

  // 处理拒绝
  const handleReject = () => {
    if (!rejectReason) {
      message.error('Please provide a reason for rejection');
      return;
    }
    onReject(rejectReason);
    setRejectModalVisible(false);
    setRejectReason('');
  };

  // 处理修改
  const handleModify = () => {
    form.validateFields().then((values) => {
      onModify(values);
    }).catch((error) => {
      message.error('Please fill in all required fields');
    });
  };

  // 重置表单
  const handleReset = () => {
    form.setFieldsValue(originalSuggestion);
    setIsModified(false);
  };

  return (
    <Card
      title={
        <Space size="middle">
          <span>Human Approval - Task {taskId}</span>
          {isModified && (
            <Alert
              message="Form has been modified"
              type="warning"
              showIcon
              style={{ marginLeft: 'auto' }}
            />
          )}
        </Space>
      }
    >
      <Form
        form={form}
        layout="vertical"
        onValuesChange={handleFormChange}
      >
        <Form.Item
          name="title"
          label="Suggestion Title"
          rules={[{ required: true, message: 'Please enter suggestion title' }]}
        >
          <Input placeholder="Enter suggestion title" />
        </Form.Item>

        <Form.Item
          name="description"
          label="Suggestion Description"
          rules={[{ required: true, message: 'Please enter suggestion description' }]}
        >
          <TextArea rows={4} placeholder="Enter suggestion description" />
        </Form.Item>

        {aiSuggestion.suggestedPrice && (
          <Form.Item
            name="suggestedPrice"
            label="Suggested Price"
            rules={[{ required: true, message: 'Please enter suggested price' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              prefix="$"
              min={0}
              step={0.01}
              precision={2}
            />
          </Form.Item>
        )}

        {aiSuggestion.batchSize && (
          <Form.Item
            name="batchSize"
            label="Batch Size"
            rules={[{ required: true, message: 'Please enter batch size' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              min={1}
              step={1}
            />
          </Form.Item>
        )}

        {aiSuggestion.campaignBudget && (
          <Form.Item
            name="campaignBudget"
            label="Campaign Budget"
            rules={[{ required: true, message: 'Please enter campaign budget' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              prefix="$"
              min={0}
              step={100}
            />
          </Form.Item>
        )}

        <Form.Item
          name="confidence"
          label="Confidence Level"
          rules={[{ required: true, message: 'Please select confidence level' }]}
        >
          <Select placeholder="Select confidence level">
            <Option value="low">Low (0-30%)</Option>
            <Option value="medium">Medium (31-70%)</Option>
            <Option value="high">High (71-90%)</Option>
            <Option value="very-high">Very High (91-100%)</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="priority"
          label="Priority"
          rules={[{ required: true, message: 'Please select priority' }]}
        >
          <Select placeholder="Select priority">
            <Option value="low">Low</Option>
            <Option value="medium">Medium</Option>
            <Option value="high">High</Option>
            <Option value="urgent">Urgent</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="notes"
          label="Additional Notes"
        >
          <TextArea rows={3} placeholder="Enter any additional notes" />
        </Form.Item>

        <Divider />

        <Form.Item
          name="approvalOptions"
          label="Approval Options"
          rules={[{ required: true, message: 'Please select an option' }]}
        >
          <Radio.Group>
            <Radio value="approve">Approve as is</Radio>
            <Radio value="modify">Modify and approve</Radio>
            <Radio value="reject">Reject</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="executor"
          label="Executor"
          rules={[{ required: true, message: 'Please select executor' }]}
        >
          <Select placeholder="Select executor">
            <Option value="ai">AI Automatic Execution</Option>
            <Option value="human">Human Execution</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="executionTime"
          label="Execution Time"
          rules={[{ required: true, message: 'Please select execution time' }]}
        >
          <Radio.Group>
            <Radio value="immediate">Immediate</Radio>
            <Radio value="scheduled">Scheduled</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="scheduledTime"
          label="Scheduled Time"
          dependencies={['executionTime']}
          rules={[
            {
              required: (_, values) => values.executionTime === 'scheduled',
              message: 'Please select scheduled time',
            },
          ]}
        >
          <DatePicker showTime style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item
          name="notify"
          label="Notifications"
        >
          <Checkbox.Group>
            <Space direction="vertical">
              <Checkbox value="email">Send email notification</Checkbox>
              <Checkbox value="sms">Send SMS notification</Checkbox>
              <Checkbox value="webhook">Trigger webhook</Checkbox>
            </Space>
          </Checkbox.Group>
        </Form.Item>

        <div style={{ marginTop: 24, textAlign: 'right' }}>
          <Space size="middle">
            <Button onClick={handleReset} icon={<UndoOutlined />}>
              Reset
            </Button>
            <Button
              danger
              onClick={() => setRejectModalVisible(true)}
              icon={<CloseCircleOutlined />}
            >
              Reject
            </Button>
            {isModified ? (
              <Button
                type="primary"
                onClick={handleModify}
                loading={loading}
                icon={<SaveOutlined />}
              >
                Modify and Approve
              </Button>
            ) : (
              <Button
                type="primary"
                onClick={handleApprove}
                loading={loading}
                icon={<CheckCircleOutlined />}
              >
                Approve
              </Button>
            )}
          </Space>
        </div>
      </Form>

      <Modal
        title="Reject Suggestion"
        open={rejectModalVisible}
        onOk={handleReject}
        onCancel={() => setRejectModalVisible(false)}
        okText="Reject"
        cancelText="Cancel"
      >
        <Form layout="vertical">
          <Form.Item
            label="Reason for Rejection"
            rules={[{ required: true, message: 'Please provide a reason for rejection' }]}
          >
            <TextArea
              rows={4}
              placeholder="Enter reason for rejection"
              value={rejectReason}
              onChange={(e) => setRejectReason(e.target.value)}
            />
          </Form.Item>
          <Form.Item
            label="Additional Comments"
          >
            <TextArea
              rows={2}
              placeholder="Enter any additional comments"
            />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  );
};

export default HumanApprovalForm;
