import { Table, Tag } from "antd";
import { useEffect, useState } from "react";
import axiosInstance from "../../api/axios";
import { useSelector } from "react-redux";
import Column from "antd/es/table/Column";
import dayjs from "dayjs";

export default function MyReservation() {
  const [reservations, setReservations] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const userId = useSelector((state) => state.auth.userId);

  const fetchData = async (pagination) => {
    const data = await axiosInstance.get(`/reservation/${userId}`, {
      params: {
        page: pagination.current,
        size: pagination.pageSize,
      },
    });
    setReservations(data.records);
    setPagination({
      ...pagination,
      total: data.total,
    });
  };

  useEffect(() => {
    fetchData(pagination);
  }, []);

  const handlePageChange = (pagination) => {
    fetchData(pagination);
  };

  return (
    <>
      <Table
        dataSource={reservations}
        pagination={pagination}
        onChange={handlePageChange}
        rowKey="reservationId"
      >
        <Column
          title="设备名称"
          key="deviceName"
          dataIndex="deviceName"
          render={(_, { deviceName }) => {
            return deviceName ? (
              deviceName
            ) : (
              <span className="text-red-600">该设备已被删除</span>
            );
          }}
        />
        <Column
          title="设备管理员"
          key="deviceAdminName"
          dataIndex="deviceAdminName"
        />
        <Column
          title="管理员联系方式"
          key="deviceAdminContact"
          dataIndex="deviceAdminContact"
        />
        <Column title="开始使用时间" key="startTime" dataIndex="startTime" />
        <Column title="结束使用时间" key="endTime" dataIndex="endTime" />
        <Column
          title="预约状态"
          key="statusLabel"
          dataIndex="statusLabel"
          render={(_, { statusLabel }) => {
            const color = statusLabel === "通过" ? "green" : "yellow";
            return (
              <Tag color={color} key="statusLabel">
                {statusLabel}
              </Tag>
            );
          }}
        />
        <Column
          title="预约提交时间"
          key="createdTime"
          dataIndex="createdTime"
          render={(_, { createdTime }) => {
            return dayjs(createdTime).format("YYYY-MM-DD HH:mm");
          }}
        />
      </Table>
    </>
  );
}
