import {
  DatePicker,
  Descriptions,
  Form,
  Image,
  message,
  Modal,
  Space,
} from "antd";
import dayjs from "dayjs";
import axiosInstance, { baseURL } from "../../api/axios";
import { useEffect, useState } from "react";
import isBetween from "dayjs/plugin/isBetween";
import { store } from "../../store";
import { useSelector, useStore } from "react-redux";

export default function DeviceDetailModal({ visiable, device, onclose }) {
  const [unavailableTimes, setUnavailableTims] = useState([]);
  useEffect(() => {
    const fetchUnavailableTimes = async (id) => {
      const data = await axiosInstance.get(`/device/unavailable-times/${id}`);
      setUnavailableTims(data);
    };

    if (visiable && device?.deviceId) {
      fetchUnavailableTimes(device.deviceId);
    }
  }, [visiable, device?.deviceId]);

  const { RangePicker } = DatePicker;
  const disabledDate = (current) => {
    if (!current) return false;
    const today = dayjs().startOf("day");
    const currentDay = current.startOf("day");
    if (currentDay.isBefore(today)) {
      return true;
    }
    dayjs.extend(isBetween);

    return unavailableTimes.some(({ startTime, endTime }) => {
      const start = dayjs(startTime).startOf("day");
      const end = dayjs(endTime).endOf("day");
      return currentDay.isBetween(start, end, null, "[]");
    });
  };

  const [form] = Form.useForm();
  const userId = useSelector((state) => state.auth.userId);

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

    const [startTime, endTime] = values.date;

    const payload = {
      deviceId: device.deviceId,
      userId,
      startTime: startTime.format("YYYY-MM-DD"),
      endTime: endTime.format("YYYY-MM-DD"),
    };

    await axiosInstance.post("/reservation", payload);
    message.success("预约成功");
    form.resetFields();
    onclose();
  };

  return (
    <Modal
      title="预约设备"
      open={visiable}
      onCancel={() => {
        onclose();
      }}
      onOk={handleOK}
    >
      <Space direction="vertical">
        <Descriptions column={1}>
          <Descriptions.Item label="设备名称">{device?.name}</Descriptions.Item>
          <Descriptions.Item label="使用要求">
            {device?.usageRequirement}
          </Descriptions.Item>
          <Descriptions.Item label="设备位置">
            {device?.location}
          </Descriptions.Item>
          <Descriptions.Item label="设备图片">
            <Image src={`${baseURL}/${device?.imagePath}`} />
          </Descriptions.Item>
        </Descriptions>

        <Form form={form} layout="inline" className="mt-14">
          <Form.Item
            name="date"
            label="预约日期"
            rules={[{ required: true, message: "请选择预约日期" }]}
          >
            <RangePicker disabledDate={disabledDate} />
          </Form.Item>
        </Form>
      </Space>
    </Modal>
  );
}
