import { UploadOutlined } from "@ant-design/icons";
import {
  Button,
  Form,
  Image,
  Input,
  message,
  Modal,
  Select,
  Upload,
} from "antd";
import TextArea from "antd/es/input/TextArea";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import axiosInstance, { baseURL } from "../../api/axios";
import { deviceStatusOptions } from "../../config/DeviceStatusConfig";
import { selectUserId } from "../../features/auth/authSlice";

export default function DeviceDetailModal({
  visiable,
  mode = "create",
  device,
  onclose,
  onSuccess,
}) {
  const [form] = Form.useForm();
  const [imageFile, setImageFile] = useState(null);
  const [initialValues, setInitialValues] = useState({});
  const [fileList, setFileList] = useState();
  const userId = useSelector(selectUserId);
  useEffect(() => {
    if (visiable) {
      setFileList([]);
      if (mode === "edit") {
        const values = {
          name: device.name,
          location: device.location,
          usageRequirement: device.usageRequirement,
          status: device.status,
        };
        form.setFieldsValue(values);
        setInitialValues(values);
      } else {
        const values = {
          name: undefined,
          location: undefined,
          usageRequirement: undefined,
          status: undefined,
        };
        form.setFieldsValue(values);
        setInitialValues(values);
      }
    }
  }, [visiable, mode, device, form]);

  const handleOk = async () => {
    const values = await form.validateFields();
    const data = {};
    Object.keys(initialValues).forEach((key) => {
      if (values[key] !== initialValues[key]) {
        data[key] = values[key];
      }
    });

    if (Object.keys(data).length > 0) {
      if (mode === "edit") {
        await axiosInstance.put(`/device/${device.deviceId}`, data);
        message.success("编辑成功");
      } else {
        device = await axiosInstance.post(`/device/${userId}`, data);

        message.success("添加成功");
      }
    }

    if (imageFile) {
      const formData = new FormData();
      formData.append("image", imageFile);
      await axiosInstance.post(`device/${device.id}/image`, formData, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      });
    }
    onSuccess();
    onclose();
  };

  return (
    <Modal
      title={mode === "edit" ? "编辑设备" : "添加设备"}
      open={visiable}
      onCancel={() => {
        onclose();
      }}
      onOk={handleOk}
      okText="保存"
    >
      <Form form={form} layout="vertical" initialValues={initialValues}>
        <Form.Item name="name" label="设备名称" rules={[{ required: true }]}>
          <Input />
        </Form.Item>
        <Form.Item name="location" label="位置">
          <Input />
        </Form.Item>
        <Form.Item name="usageRequirement" label="使用要求">
          <TextArea />
        </Form.Item>
        <Form.Item
          name="status"
          label="设备状态"
          rules={[{ required: true, message: "请选择设备状态" }]}
        >
          <Select options={deviceStatusOptions} placeholder="请选择设备状态" />
        </Form.Item>

        <Form.Item label="设备图片">
          {device?.imagePath && (
            <Image src={`${baseURL}/${device.imagePath}`} className="mt-2" />
          )}
          <br />
          <Upload
            fileList={fileList}
            beforeUpload={(file) => {
              setImageFile(file);
              return false; // 阻止自动上传
            }}
            showUploadList={{ showRemoveIcon: true }}
            onChange={({ fileList }) => setFileList(fileList)}
            maxCount={1}
          >
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
}
