import { ScrollArea } from '@mantine/core';
import { FC, useEffect, useState } from 'react';
import { Button, Stack } from '../../components';
import { Dialog } from '../../components/Dialog';
import { Pagination } from '../../components/Pagination';
import { soriAPIClient, Staff } from '../../lib/sori';
import { CreateStaffForm } from './CreateStaffForm';
export const StaffScene: FC = () => {
  const [createOpen, setCreateOpen] = useState(false);

  const [staffs, setStaffs] = useState<Staff[]>([]);
  const [selectedStaff, setSelectedStaff] = useState<Staff | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 20;

  const paginatedstaffs = staffs.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize,
  );
  const loadStaffs = async () => {
    const staffsResult = await soriAPIClient.staffs.actions.getStaffs();

    const staffs = staffsResult.unwrap();

    setStaffs(staffs);
  };
  useEffect(() => {
    loadStaffs();
  }, []);

  // const onSubmit = (project: Partial<Project>) => {
  //   setProjects([...projects, project as Project]);
  //   setOpen(false);
  // };

  return (
    <>
      <Dialog open={createOpen} onRequestClose={() => setCreateOpen(false)}>
        <CreateStaffForm
          onClose={() => {
            setCreateOpen(false);
            loadStaffs();
          }}
          open={createOpen}
        />
      </Dialog>
      <Stack className="border-black-2 relative mx-auto mt-20px h-[90%] w-[90%] overflow-hidden border rounded-lg shadow-[0_2px_5px_2px_rgba(0,0,0,0.1)] xl:px-20">
        <div className="h-20 min-h-12 flex flex-col justify-center gap-1 px-8 text-lg text-xl text-black/90 font-bold font-medium dark:text-white/90">
          <div className="flex items-center justify-between">
            <span>Staff Management</span>
            <Button
              className="bg-blue-6 text-white"
              onClick={() => {
                setCreateOpen(true);
              }}
            >
              + Create Staff
            </Button>
          </div>
        </div>
        <Stack className="relative h-full w-full overflow-hidden">
          <StaffTable
            staffs={paginatedstaffs}
            onDeleteClick={(staff) => {
              setSelectedStaff(staff);
            }}
          />

          <Pagination
            count={staffs.length}
            pageSize={pageSize}
            siblingCount={1}
            currentPage={currentPage}
            onPageChange={setCurrentPage}
          />
        </Stack>
      </Stack>
    </>
  );
};

const StaffTable: FC<{
  staffs: Staff[];
  onDeleteClick: (staff: Staff) => void;
}> = ({ staffs, onDeleteClick }) => {
  return (
    <ScrollArea className="mb-1 h-full w-full overflow-hidden border border-gray-300 rounded-lg shadow-[2px_2px_5px_2px_rgba(0,0,0,0.1)]">
      <table className="min-w-full">
        <thead>
          <tr className="text-gray-700">
            <th className="border-b px-4 py-2">Staff ID</th>
            <th className="border-b px-4 py-2">Name (EN)</th>
            <th className="border-b px-4 py-2">Name (ZH)</th>
            <th className="border-b px-4 py-2">Role</th>
            <th className="border-b px-4 py-2">Last Updated</th>
            <th className="border-b px-4 py-2">Action</th>
          </tr>
        </thead>
        <tbody>
          {staffs.map((staff) => (
            <StaffTr
              key={staff.hkId}
              Staff={staff}
              onDeleteClick={onDeleteClick}
            />
          ))}
        </tbody>
      </table>
    </ScrollArea>
  );
};

const StaffTr: FC<{
  Staff: Staff;
  onDeleteClick: (staff: Staff) => void;
}> = ({ Staff, onDeleteClick }) => {
  const getLastUpdatedTime = (updatedAt: Date) => {
    const lastUpdated = new Date(updatedAt);
    const today = new Date();
    const diffMs = lastUpdated.getTime() - today.getTime();
    const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
    if (-diffDays >= 30) {
      return `> ${Math.trunc(-diffDays / 30)} 個月`;
    }
    return `${-diffDays} day(s)`;
  };

  return (
    <tr key={Staff.hkId} className="text-center text-gray-600">
      <td className="border-b px-4 py-2">{Staff.hkId}</td>
      <td className="border-b px-4 py-2">{Staff.nameEN}</td>
      <td className="border-b px-4 py-2">{Staff.nameZH}</td>
      <td className="border-b px-4 py-2">{Staff.role.toUpperCase()}</td>

      {/* <td className="border-b px-4 py-2">
        <SSCBattery ssc={Staff} />
      </td> */}
      <td className="border-b px-4 py-2">{`${getLastUpdatedTime(Staff.updatedAt)}`}</td>
      <td className="border-b px-4 py-2">
        <Button
          className="mx-auto border-gray-300 rounded-lg bg-transparent"
          onClick={() => onDeleteClick(Staff)}
        >
          Edit
        </Button>
      </td>
    </tr>
  );
};
