"use client";
import { usePermission } from "@/utils/auth/permission";
import { cellIndex } from "@/utils/lib/helpers";
import { keepPreviousData, useQuery } from "@tanstack/react-query";
import axios from "axios";
import { Alert, Spinner } from "flowbite-react";
import Link from "next/link";
import { FC, useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import ActionButton from "../action-button";
import DeleteRecord from "../common/delete-record";
import CustomPagination from "../common/pagination";
import DataTable from "../dataTable/data-table-fb";
import { TSstaffSchema } from "../forms/schema/staff";
import { BiMoney, BiMoneyWithdraw } from "react-icons/bi";

type props = {
  initStaffs: TSstaffSchema;
  initPagination: any;
};

const StaffList: FC<props> = ({ initStaffs, initPagination }) => {
  const [currentPage, setCurrentPage] = useState(1);
  const [pagination, setPagination] = useState<any>(initPagination);

  const onPageChange = (page: number) => setCurrentPage(page);
  const getStaffs = async () => {
    const {
      data: { data },
      data: {
        data: { pagination },
      },
    } = await axios.get(`/api/staffs?page=${currentPage}`);
    setPagination(pagination);
    return data?.data;
  };
  const {
    data: staffs,
    isLoading,
    isError,
    error = {} as any,
  } = useQuery({
    queryKey: ["staffs", { currentPage }],
    placeholderData: keepPreviousData,
    queryFn: () => getStaffs(),
    retry: 0,
    initialData: initStaffs,
  });

  const columns = [
    {
      header: "SL",
      cell: ({ row }: any) => (
        <div className="font-bold">{cellIndex(row.index, pagination)}</div>
      ),
    },
    {
      header: "Name",
      accessorKey: "name",
    },
    {
      header: "Role",
      accessorKey: "role",
      cell: ({ row }: any) => {
        const staff = row.original;
        const roles = staff?.roles?.map((role: any) => role?.name);
        return (
          <>
            <p>{roles?.toString()}</p>
          </>
        );
      },
    },
    {
      header: "designation",
      accessorKey: "designation",
    },
    {
      header: "phone",
      accessorKey: "phone",
    },
    {
      header: "email",
      accessorKey: "email",
    },
    {
      header: "join date",
      accessorKey: "join_date",
    },
    {
      header: "status",
      accessorKey: "status",
    },
    {
      header: "Actions",
      id: "testing",
      cell: ({ row }: any) => {
        const staff = row.original;
        const staff_id: string = String(staff.id);
        return (
          <>
            <div className=" flex">
              <div className="mr-2">
                {usePermission("staffs.edit") && (
                  <Link href={`staffs/edit/${staff_id}`}>
                    <ActionButton type="edit" />
                  </Link>
                )}
              </div>
              {usePermission("staffs.show") && (
                <Link href={`/staffs/view/${staff_id}`}>
                  <ActionButton className="ml-1" type="view" />
                </Link>
              )}
              {usePermission("staffs.delete") && (
                <DeleteRecord
                  url={`/api/staffs/${staff_id}`}
                  name="Staff"
                  keys="staffs"
                />
              )}
            </div>
          </>
        );
      },
    },
  ];

  return (
    <>
      {isLoading && (
        <div className="text-center">
          <Spinner
            aria-label="Center-aligned spinner example"
            className="mt-20"
            size="xl"
          />
        </div>
      )}
      {isError && (
        <Alert color="failure" icon={HiInformationCircle}>
          <span className="font-medium">Info alert!</span>
          {error?.response?.data?.error?.message}
        </Alert>
      )}
      {staffs !== undefined && (
        <div className="user-list pb-20 shadow-md">
          <div className="border-b overflow-x-auto">
            <DataTable data={staffs} columns={columns} />
          </div>
          <CustomPagination
            pagination={pagination}
            currentPage={currentPage}
            onPageChange={onPageChange}
          />
        </div>
      )}
    </>
  );
};
export default StaffList;
