import React, { useState, useEffect } from "react";
import {
   Modal,
   Form,
   Input,
   Checkbox,
   Slider,
   Select,
   Button,
   Popconfirm,
} from "antd";
import { RightOutlined, DownOutlined } from "@ant-design/icons";

const { Option } = Select;

const TargetDetailModal = ({
   visible,
   mode,
   targetData,
   onOk,
   onCancel,
   onDelete,
}) => {
   const [form] = Form.useForm();
   const [advancedConfig, setAdvancedConfig] = useState(false);

   // 高斯模糊阈值选项
   const gaussianBlurOptions = [1, 3, 5, 7, 9, 11];

   useEffect(() => {
      if (visible && targetData) {
         // 编辑模式时填充表单数据
         form.setFieldsValue({
            name: targetData.name || "",
            radius: targetData.radius || "",
            isReferencePoint: targetData.isReferencePoint || false,
            gradientThreshold: targetData.gradientThreshold,
            anchorThreshold: targetData.anchorThreshold,
            gaussianBlurThreshold: targetData.gaussianBlurThreshold || 3,
         });
         // 默认高级配置不展开
         setAdvancedConfig(false);
      } else if (visible && mode === "add") {
         // 新增模式时设置默认值
         form.setFieldsValue({
            name: "",
            radius: "",
            isReferencePoint: false,
            gradientThreshold: 100,
            anchorThreshold: 80,
            gaussianBlurThreshold: 3,
         });
         setAdvancedConfig(false);
      }
   }, [visible, targetData, mode, form]);

   const handleOk = () => {
      form
         .validateFields()
         .then((values) => {
            const targetInfo = {
               ...values,
               hasAdvancedConfig: advancedConfig,
               id: targetData?.id || Date.now().toString(),
            };
            onOk(targetInfo);
            form.resetFields();
            setAdvancedConfig(false);
         })
         .catch((info) => {
            console.log("表单验证失败:", info);
         });
   };

   const handleCancel = () => {
      form.resetFields();
      setAdvancedConfig(false);
      onCancel();
   };

   const handleDelete = () => {
      if (targetData) {
         // 传递 key 或 id 给删除函数
         const targetKey = targetData.key || targetData.id;
         onDelete(targetKey);
      }
   };

   const handleAdvancedConfigChange = () => {
      setAdvancedConfig(!advancedConfig);
   };

   return (
      <Modal
         title="详情"
         open={visible}
         onOk={handleOk}
         onCancel={handleCancel}
         width={400}
         destroyOnHidden={true}
         footer={[
            mode === "edit" && (
               <Popconfirm
                  key="delete"
                  title="确认删除选中的标靶？"
                  description="此操作将移除画面中的标靶及其历史数据，且不可恢复。"
                  onConfirm={handleDelete}
                  okText="确认删除"
                  cancelText="取消"
                  placement="topRight"
               >
                  <Button danger style={{ float: "left" }}>
                     删除标靶
                  </Button>
               </Popconfirm>
            ),
            <Button key="cancel" onClick={handleCancel}>
               取消
            </Button>,
            <Button key="ok" type="primary" onClick={handleOk}>
               确认
            </Button>,
         ]}
      >
         <Form
            form={form}
            layout="vertical"
            initialValues={{
               isReferencePoint: false,
               gradientThreshold: 100,
               anchorThreshold: 80,
               gaussianBlurThreshold: 3,
            }}
         >
            <Form.Item
               label="标靶描述"
               name="name"
               rules={[
                  { required: true, message: "请输入标靶描述" },
                  { max: 50, message: "标靶描述不能超过50个字符" },
                  { pattern: /^[^\u4e00-\u9fa5]+$/, message: "仅支持英文、数字及符号" },
               ]}
            >
               <Input placeholder="请输入标靶描述" />
            </Form.Item>

            <Form.Item
               label="标靶圆物理半径(mm)"
               name="radius"
               rules={[
                  { required: true, message: "请输入标靶圆物理半径" },
                  {
                     pattern: /^\d+(\.\d+)?$/,
                     message: "请输入有效的数字",
                  },
               ]}
            >
               <Input placeholder="请输入标靶圆物理半径" />
            </Form.Item>

            <Form.Item label="高级配置">
               <Button
                  type="text"
                  onClick={handleAdvancedConfigChange}
                  icon={advancedConfig ? <DownOutlined /> : <RightOutlined />}
                  style={{
                     padding: "0",
                     height: "auto",
                     display: "flex",
                     alignItems: "center",
                     fontSize: "14px",
                  }}
               >
                  展开高级配置选项
               </Button>
            </Form.Item>

            {advancedConfig && (
               <>
                  <Form.Item name="isReferencePoint" valuePropName="checked">
                     <Checkbox>设为基准点</Checkbox>
                  </Form.Item>

                  <Form.Item label="梯度阈值" name="gradientThreshold">
                     <Slider
                        min={0}
                        max={200}
                        marks={{
                           0: "0",
                           200: "200",
                        }}
                        tooltip={{
                           formatter: (value) => `${value}`,
                        }}
                        included={true}
                     />
                  </Form.Item>

                  <Form.Item label="锚点阈值" name="anchorThreshold">
                     <Slider
                        min={0}
                        max={200}
                        marks={{
                           0: "0",
                           200: "200",
                        }}
                        tooltip={{
                           formatter: (value) => `${value}`,
                        }}
                        included={true}
                     />
                  </Form.Item>

                  <Form.Item label="高斯模糊阈值" name="gaussianBlurThreshold">
                     <Select placeholder="请选择高斯模糊阈值">
                        {gaussianBlurOptions.map((value) => (
                           <Option key={value} value={value}>
                              {value}
                           </Option>
                        ))}
                     </Select>
                  </Form.Item>
               </>
            )}
         </Form>
      </Modal>
   );
};

export default TargetDetailModal;
