import { ScrollArea } from '@mantine/core';
import { ObjectId } from 'bson';
import { FC, useEffect, useState } from 'react';
import { Stack } from '../../components';
import { Pagination } from '../../components/Pagination';
import { LeaveTransaction, soriAPIClient } from '../../lib/sori';
export const LeaveTransactionScene: FC = () => {
  const [leaveTransactions, setLeaveTransactions] = useState<
    LeaveTransaction[]
  >([]);

  const [currentPage, setCurrentPage] = useState(1);
  const pageSize = 20;

  const paginatedstaffs = leaveTransactions.slice(
    (currentPage - 1) * pageSize,
    currentPage * pageSize,
  );

  const [staffMap, setStaffMap] = useState<Record<string, string>>({});
  const loadLeaveTransactions = async () => {
    const leaveApplicationsResult =
      await soriAPIClient.leaveTransactions.actions.getLeaveTransactions();

    const leaveTransactions = leaveApplicationsResult.unwrap();

    const staffIds = [
      ...new Set(leaveTransactions.map((t) => t.grantedTo.toString())),
    ];
    const staffEntries = await Promise.all(
      staffIds.map(async (id) => {
        const staffResult = await soriAPIClient.staffs.actions.getStaff(
          new ObjectId(id),
        );
        const staff = staffResult.unwrap();
        return [id, staff.nameEN] as const;
      }),
    );
    setStaffMap(Object.fromEntries(staffEntries));
    setLeaveTransactions(leaveTransactions);
  };
  useEffect(() => {
    loadLeaveTransactions();
  }, []);

  return (
    <>
      <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 Transactions</span>
          </div>
        </div>
        <Stack className="relative h-full w-full overflow-hidden">
          <LeaveAppTable
            leaveTransactions={paginatedstaffs}
            staffMap={staffMap}
          />

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

const LeaveAppTable: FC<{
  leaveTransactions: LeaveTransaction[];
  staffMap: Record<string, string>;
}> = ({ leaveTransactions, staffMap }) => {
  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">Amount</th>
            <th className="border-b px-4 py-2">Balance</th>
            <th className="border-b px-4 py-2">User</th>
            <th className="border-b px-4 py-2">Created At</th>
          </tr>
        </thead>
        <tbody>
          {leaveTransactions.map((leaveTransaction) => (
            <LeaveAppTr
              key={leaveTransaction._id.toString()}
              LeaveTransaction={leaveTransaction}
              staffMap={staffMap}
            />
          ))}
        </tbody>
      </table>
    </ScrollArea>
  );
};

const LeaveAppTr: FC<{
  LeaveTransaction: LeaveTransaction;
  staffMap: Record<string, string>;
}> = ({ LeaveTransaction, staffMap }) => {
  return (
    <tr
      key={LeaveTransaction._id.toString()}
      className="text-center text-gray-600"
    >
      <td className="border-b px-4 py-2">{LeaveTransaction.leaveType}</td>
      <td className="border-b px-4 py-2">{LeaveTransaction.amount}</td>
      <td className="border-b px-4 py-2">{LeaveTransaction.balance}</td>
      <td className="border-b px-4 py-2">
        {staffMap[LeaveTransaction.grantedTo.toString()] ?? 'Loading...'}
      </td>
      <td className="border-b px-4 py-2">
        {LeaveTransaction.createdAt.toDateString()}
      </td>
    </tr>
  );
};
