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 { LeaveCancellation, soriAPIClient } from '../../lib/sori';
import { ApproveLeaveCancellationForm } from './ApproveLeaveCancellationForm';
import { CreateLeaveCancellationForm } from './CreateLeaveCancellationForm';
export const LeaveCancellationScene: FC = () => {
  const [createOpen, setCreateOpen] = useState(false);
  const [approveOpen, setApproveOpen] = useState(false);

  const [leaveCancellations, setLeaveCancellations] = useState<
    LeaveCancellation[]
  >([]);
  const [selectedLeaveCancellation, setSelectedLeaveCancellation] =
    useState<LeaveCancellation | null>(null);
  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 20;

  const paginatedstaffs = leaveCancellations.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize,
  );
  const loadLeaveCancellations = async () => {
    const leaveCancellationsResult =
      await soriAPIClient.leaveCancellations.actions.getLeaveCancellations();

    const leaveCancellations = leaveCancellationsResult.unwrap();

    setLeaveCancellations(leaveCancellations);
  };
  useEffect(() => {
    loadLeaveCancellations();
  }, []);

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

  return (
    <>
      <Dialog open={createOpen} onRequestClose={() => setCreateOpen(false)}>
        <CreateLeaveCancellationForm
          onClose={() => {
            setCreateOpen(false);
            loadLeaveCancellations();
          }}
          open={createOpen}
        />
      </Dialog>
      <Dialog open={approveOpen} onRequestClose={() => setApproveOpen(false)}>
        {selectedLeaveCancellation && (
          <ApproveLeaveCancellationForm
            leaveCancellation={selectedLeaveCancellation}
            onClose={() => {
              setApproveOpen(false);
              setSelectedLeaveCancellation(null);
              loadLeaveCancellations(); // refresh list after delete
            }}
          />
        )}
      </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>Leave Cancellation Management</span>
            <Button
              className="bg-blue-6 text-white"
              onClick={() => {
                setCreateOpen(true);
              }}
            >
              + Create Leave Cancellation
            </Button>
          </div>
        </div>
        <Stack className="relative h-full w-full overflow-hidden">
          <LeaveAppTable
            leaveCancellations={paginatedstaffs}
            onApproveClick={(leaveCancellation) => {
              setSelectedLeaveCancellation(leaveCancellation);
              setApproveOpen(true);
            }}
          />

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

const LeaveAppTable: FC<{
  leaveCancellations: LeaveCancellation[];
  onApproveClick: (leaveCancellation: LeaveCancellation) => void;
}> = ({ leaveCancellations, onApproveClick }) => {
  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">Leave Type</th>
            <th className="border-b px-4 py-2">From Date</th>
            <th className="border-b px-4 py-2">To Date</th>
            <th className="border-b px-4 py-2">Duration (Days)</th>
            <th className="border-b px-4 py-2">Full/Half</th>
            <th className="border-b px-4 py-2">Last Updated</th>
            <th className="border-b px-4 py-2">Status</th>
            <th className="border-b px-4 py-2"></th>
            <th className="border-b px-4 py-2"></th>
          </tr>
        </thead>
        <tbody>
          {leaveCancellations.map((leaveCancellation) => (
            <LeaveAppTr
              key={leaveCancellation._id.toString()}
              LeaveCancellation={leaveCancellation}
              onApproveClick={onApproveClick}
            />
          ))}
        </tbody>
      </table>
    </ScrollArea>
  );
};

const LeaveAppTr: FC<{
  LeaveCancellation: LeaveCancellation;
  onApproveClick: (leaveCancellation: LeaveCancellation) => void;
}> = ({ LeaveCancellation, onApproveClick }) => {
  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)`;
  };

  const workDayType = LeaveCancellation.leaves[0].workDay.type;
  let leaveDuration = 0;

  if (workDayType === 'full') {
    leaveDuration = LeaveCancellation.leaves.length;
  } else {
    leaveDuration = 0.5;
  }

  return (
    <tr
      key={LeaveCancellation._id.toString()}
      className="text-center text-gray-600"
    >
      <td className="border-b px-4 py-2">
        {LeaveCancellation.leaves[0].type[0].toUpperCase() +
          LeaveCancellation.leaves[0].type.slice(1)}
      </td>
      <td className="border-b px-4 py-2">
        {LeaveCancellation.leaves[0].workDay.date}
      </td>
      <td className="border-b px-4 py-2">
        {
          LeaveCancellation.leaves[LeaveCancellation.leaves.length - 1].workDay
            .date
        }
      </td>
      <td className="border-b px-4 py-2">{leaveDuration}</td>
      <td className="border-b px-4 py-2">
        {LeaveCancellation.leaves[0].workDay.type}
      </td>
      <td className="border-b px-4 py-2">{`${getLastUpdatedTime(LeaveCancellation.updatedAt)}`}</td>
      <td className="border-b px-4 py-2">{LeaveCancellation.status}</td>
      <td className="border-b px-4 py-2">
        <Button
          className="mx-auto border-gray-300 rounded-lg bg-transparent"
          //onClick={() => onDeleteClick(LeaveCancellation)}
        >
          Edit
        </Button>
      </td>
      <td className="border-b px-4 py-2">
        <Button
          className="mx-auto border-gray-300 rounded-lg bg-transparent"
          onClick={() => onApproveClick(LeaveCancellation)}
        >
          Approve
        </Button>
      </td>
    </tr>
  );
};
