import React, { useState, useEffect } from "react";
import {
   Modal,
   Form,
   Input,
   InputNumber,
   Checkbox,
   Slider,
   Select,
   Button,
   Space,
   message,
   Popconfirm,
   Upload,
} from "antd";
import { DeleteOutlined, UploadOutlined } from "@ant-design/icons";

const { Option } = Select;

const TemplateModal = ({
   visible,
   mode, // 'add' | 'edit'
   templateData,
   onOk,
   onCancel,
   onDelete,
   tempListData,
}) => {
   const [form] = Form.useForm();
   const [isBaseline, setIsBaseline] = useState(false);
   const [isPerspectiveCorrection, setIsPerspectiveCorrection] =
      useState(false);
   const [binaryThreshold, setBinaryThreshold] = useState(100);
   const [gaussianBlur, setGaussianBlur] = useState(1);
   const [physicalRadius, setPhysicalRadius] = useState(40.0);
   const [gradientThresholdValue, setGradientThresholdValue] = useState(100);
   const [anchorThresholdValue, setAnchorThresholdValue] = useState(80);
   const [fileList, setFileList] = useState([]);
   const [imageUrl, setImageUrl] = useState("");
   const [previewVisible, setPreviewVisible] = useState(false);
   const [previewImage, setPreviewImage] = useState("");

   // 当模态框打开时，设置表单初始值
   useEffect(() => {
      if (visible) {
         if (mode === "edit" && templateData) {
            // 编辑模式：填充现有数据
            form.setFieldsValue({
               name: templateData.name,
               gaussianBlur: templateData.gaussianBlur || 1,
               physicalRadius: templateData.physicalRadius || 40.0,
               gradientThresholdValue: templateData.gradientThresholdValue,
               anchorThresholdValue: templateData.anchorThresholdValue,
            });
            setIsBaseline(templateData.isBaseline || false);
            setIsPerspectiveCorrection(
               templateData.isPerspectiveCorrection || false
            );
            setBinaryThreshold(templateData.binaryThreshold || 100);
            setGaussianBlur(templateData.gaussianBlur || 1);
            setPhysicalRadius(templateData.physicalRadius || 40.0);
            setGradientThresholdValue(templateData.gradientThresholdValue);
            setAnchorThresholdValue(templateData.anchorThresholdValue);

            // 设置图片数据
            if (templateData.imageUrl) {
               setImageUrl(templateData.imageUrl);
               setFileList([
                  {
                     uid: "-1",
                     name: templateData.name + ".jpg",
                     status: "done",
                     url: templateData.imageUrl,
                  },
               ]);
            } else {
               setImageUrl("");
               setFileList([]);
            }
         } else {
            // 新增模式：设置默认值
            form.resetFields();
            setIsBaseline(false);
            setIsPerspectiveCorrection(false);
            setBinaryThreshold(100);
            setGaussianBlur(1);
            setPhysicalRadius(40.0);
            setGradientThresholdValue(100);
            setAnchorThresholdValue(80);
            setImageUrl("");
            setFileList([]);
         }
      }
   }, [visible, mode, templateData, form]);

   // 图片上传处理
   const handleUploadChange = ({ fileList: newFileList }) => {
      setFileList(newFileList);

      // 如果文件列表为空（删除图片），清空imageUrl
      if (newFileList.length === 0) {
         setImageUrl("");
      }
   };

   const beforeUpload = (file) => {
      const isJpgOrPng =
         file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
         message.error("只能上传 JPG/PNG 格式的图片!");
         return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isLt2M) {
         message.error("图片大小不能超过 1MB!");
         return false;
      }

      // 读取文件并转换为base64
      const reader = new FileReader();
      reader.onload = (e) => {
         const base64Data = e.target.result;
         setImageUrl(base64Data);

         // 更新文件列表，添加预览URL
         setFileList([
            {
               uid: file.uid,
               name: file.name,
               status: "done",
               url: base64Data, // 使用base64数据作为预览URL
               originFileObj: file,
            },
         ]);
      };
      reader.readAsDataURL(file);

      return false; // 阻止默认上传行为
   };

   // 处理图片预览
   const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
         file.preview = await getBase64(file.originFileObj);
      }
      setPreviewImage(file.url || file.preview);
      setPreviewVisible(true);
   };

   // 将文件转换为base64用于预览
   const getBase64 = (file) =>
      new Promise((resolve, reject) => {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result);
         reader.onerror = (error) => reject(error);
      });

   const handleOk = async () => {
      try {
         const values = await form.validateFields();

         // 检查是否上传了图片
         if (!imageUrl) {
            message.error("请上传标靶图片");
            return;
         }

         // 检查模板数量限制（仅新增时）
         if (mode === "add" && tempListData.length >= 3) {
            message.error(
               "已达到标靶模板数量上限（3个）！请删除未使用的模板后再新增。"
            );
            return;
         }

         const templateInfo = {
            ...values,
            isBaseline,
            isPerspectiveCorrection,
            binaryThreshold,
            gaussianBlur,
            physicalRadius,
            gradientThresholdValue,
            anchorThresholdValue,
            imageUrl,
            key: mode === "edit" ? templateData.key : Date.now().toString(),
            id: mode === "edit" ? templateData.id : Date.now(),
         };

         onOk(templateInfo);
         message.success(mode === "add" ? "新增模板成功！" : "编辑模板成功！");
      } catch (error) {
         console.error("表单验证失败:", error);
      }
   };

   const handleDelete = () => {
      if (templateData) {
         // 检查是否为第一个模板（内置模板）
         if (templateData.key === "builtin_1") {
            message.warning("该模板为内置模板，不允许删除！");
            return;
         }
         onDelete(templateData);
         message.success("删除模板成功！");
      }
   };

   const title = mode === "add" ? "新增标靶模板" : "编辑标靶模板";

   return (
      <>
         <Modal
            title={title}
            open={visible}
            onCancel={onCancel}
            width={500}
            footer={[
               mode === "edit" && templateData?.key !== "builtin_1" && (
                  <Popconfirm
                     key="delete"
                     title={`确认删除标靶模板[${templateData?.name}]？`}
                     onConfirm={handleDelete}
                     okText="确认删除"
                     cancelText="取消"
                     okButtonProps={{ danger: true }}
                  >
                     <Button danger icon={<DeleteOutlined />}>
                        删除
                     </Button>
                  </Popconfirm>
               ),
               <Button key="ok" type="primary" onClick={handleOk}>
                  {mode === "add" ? "新增" : "确认"}
               </Button>,
            ].filter(Boolean)}
         >
            <Form
               form={form}
               layout="vertical"
               initialValues={{
                  name: "",
                  gaussianBlur: 1,
                  physicalRadius: 40.0,
                  gradientThresholdValue: 100,
                  anchorThresholdValue: 80,
               }}
            >
               <Form.Item
                  label="模板名称"
                  name="name"
                  rules={[
                     { required: true, message: "请输入模板名称" },
                     { max: 20, message: "模板名称不能超过20个字符" },
                  ]}
               >
                  <Input placeholder="请输入模板名称" />
               </Form.Item>

               <Form.Item
                  label={
                     <>
                        <span style={{ color: "red", marginRight: 4 }}>*</span>
                        标靶图片
                     </>
                  }
                  rules={[{ required: true, message: "请上传标靶图片" }]}
               >
                  <Upload
                     name="targetImage"
                     listType="picture-card"
                     fileList={fileList}
                     onChange={handleUploadChange}
                     beforeUpload={beforeUpload}
                     onPreview={handlePreview}
                     maxCount={1}
                  >
                     {fileList.length >= 1 ? null : (
                        <div>
                           <UploadOutlined />
                           <div style={{ marginTop: 8 }}>上传图片</div>
                        </div>
                     )}
                  </Upload>
                  <div
                     style={{
                        fontSize: "12px",
                        color: "#999",
                        marginTop: "4px",
                     }}
                  >
                     支持JPG、PNG格式，文件大小不超过1MB
                  </div>
               </Form.Item>

               <Form.Item label="配置参数">
                  <Space direction="vertical" style={{ width: "100%" }}>
                     <Checkbox
                        checked={isBaseline}
                        onChange={(e) => setIsBaseline(e.target.checked)}
                     >
                        设为基准点
                     </Checkbox>
                  </Space>
               </Form.Item>
               <Form.Item
                  label="标靶物理圆半径"
                  name="physicalRadius"
                  rules={[
                     { required: true, message: "请输入标靶物理圆半径" },
                     {
                        type: "number",
                        min: 0.1,
                        max: 500,
                        message: "半径必须在0.1-500mm之间",
                     },
                  ]}
               >
                  <InputNumber
                     value={physicalRadius}
                     onChange={setPhysicalRadius}
                     min={0.1}
                     max={500}
                     step={0.1}
                     precision={1}
                     addonAfter="mm"
                     style={{ width: "100%" }}
                     placeholder="请输入标靶物理圆半径"
                  />
               </Form.Item>
               <Form.Item label="梯度阈值">
                  <div style={{ padding: "0 8px" }}>
                     <Slider
                        min={0}
                        max={200}
                        value={gradientThresholdValue}
                        onChange={setGradientThresholdValue}
                        marks={{
                           0: "0",

                           100: "100",

                           200: "200",
                        }}
                     />
                     <div
                        style={{
                           textAlign: "center",
                           marginTop: "8px",
                           fontSize: "14px",
                           color: "#1890ff",
                           fontWeight: "bold",
                        }}
                     >
                        {gradientThresholdValue}
                     </div>
                  </div>
               </Form.Item>

               <Form.Item label="锚点阈值">
                  <div style={{ padding: "0 8px" }}>
                     <Slider
                        min={0}
                        max={200}
                        value={anchorThresholdValue}
                        onChange={setAnchorThresholdValue}
                        marks={{
                           0: "0",

                           80: "80",

                           200: "200",
                        }}
                     />
                     <div
                        style={{
                           textAlign: "center",
                           marginTop: "8px",
                           fontSize: "14px",
                           color: "#1890ff",
                           fontWeight: "bold",
                        }}
                     >
                        {anchorThresholdValue}
                     </div>
                  </div>
               </Form.Item>
               <Form.Item label="高斯模糊阈值" name="gaussianBlur">
                  <Select
                     value={gaussianBlur}
                     onChange={setGaussianBlur}
                     style={{ width: "100%" }}
                  >
                     <Option value={1}>1</Option>
                     <Option value={3}>3</Option>
                     <Option value={5}>5</Option>
                     <Option value={7}>7</Option>
                     <Option value={9}>9</Option>
                     <Option value={11}>11</Option>
                  </Select>
               </Form.Item>
            </Form>
         </Modal>

         {/* 图片预览Modal */}
         <Modal
            open={previewVisible}
            title="预览图片"
            footer={null}
            onCancel={() => setPreviewVisible(false)}
            width={600}
            centered
         >
            <img
               alt="预览"
               style={{
                  width: "100%",
                  maxHeight: "500px",
                  objectFit: "contain",
               }}
               src={previewImage}
            />
         </Modal>
      </>
   );
};

export default TemplateModal;
