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

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

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

    if (Object.keys(updates).length > 0) {
      await axiosInstance.put(`/device/${device.deviceId}`, updates);
    }

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

  return (
    <Modal
      title="编辑设备"
      open={visiable}
      onCancel={() => {
        setFileList([]);
        form.resetFields();
        onclose();
      }}
      onOk={handleEdit}
      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)}
          >
            <Button icon={<UploadOutlined />}>点击上传</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Modal>
  );
}
