"use client";

import { FiPlus } from "react-icons/fi";

import { DataTable } from "../../../components/table/DataTable";
import { HeadingToolbar } from "../../../components/table/toolbars/HeadingToolbar";
import { useAppPagination } from "../../../hooks/useAppPagination";
import { useModal } from "../../../lib/modal-system/ModalContext";
import { packageColumns } from "../../../components/table/features/packages/columns/packageColumns";
import Button from "../../../components/ui/Button";
import useFetchPackages, {
  Package,
} from "../../../hooks/features/admin/packages/useFetchPackages";
import usePackageCreate from "../../../hooks/features/admin/packages/create/usePackageCreate";
import usePackageEdit from "../../../hooks/features/admin/packages/usePackageEdit";
import SomethingWentWrong from "../../../components/SomethingWentWrong";

export default function AdminPackagesPage() {
  const pagination = useAppPagination();
  const { openModal } = useModal();

  const { data, loading, error, isError } = useFetchPackages(pagination);
  const { handlePackageCreate, loading: createLoading } = usePackageCreate();
  const { handlePackageEdit, loading: editLoading } = usePackageEdit();

  const fetchedPackages = data?.packages ?? [];
  const paginationData = data?.pagination ?? null;

  const handleCreate = () => {
    openModal("PACKAGE_FORM", {
      mode: "create",
      packageData: null,
      handleAction: async (item) => {
        await handlePackageCreate(item);
      },
    });
  };

  const handleEdit = (item: Package) => {
    openModal("PACKAGE_FORM", {
      mode: "edit",
      packageData: item,
      handleAction: async (data) => {
        await handlePackageEdit({ id: item.uuid, data });
      },
    });
  };

  const handleDelete = async (item: Package) => {
    openModal("PACKAGE_DELETE", { item });
  };

  const columns = packageColumns({
    onEdit: handleEdit,
    onDelete: handleDelete,
  });

  return (
    <section className="w-full p-4 pt-6 2xl:pt-8 2xl:p-8">
      {isError ? (
        <SomethingWentWrong
          variant="section"
          title="Unable to load packages"
          description="Package management is temporarily unavailable. Please try again."
          onRetry={() => pagination.patch({})}
          buttonText=""
        />
      ) : (
        <DataTable<Package>
          data={fetchedPackages}
          columns={columns}
          loading={loading}
          appearance="default"
          size="md"
          getRowId={(item) => String(item.uuid)}
          toolbar={
            <div className="flex w-full items-center justify-between gap-4">
              <HeadingToolbar title="Packages" />
            </div>
          }
          filters={
            <>
              <Button
                variant="white"
                type="button"
                icon={<FiPlus size={18} />}
                onClick={handleCreate}
                buttonClassName="shadow-none!"
                BtnInnerclassName="text-link!"
              >
                Create
              </Button>
            </>
          }
          classNames={{
            root: "",
            toolbar: "flex items-center gap-3",
            filters: "flex items-center gap-2",
            table: "min-w-full",
            tableThead: "bg-slate-100 border-t-2 border-slate-400  relative",
            tableTheadRow: "whitespace-nowrap",
            tableTheadCell:
              "px-3 py-2 2xl:p-3 text-left font-body text-sm 2xl:text-base font-medium text-heading relative",
            tableTbody: "border-t border-slate-300/50 relative",
            tableTbodyRow: `
              hover:bg-link-1/10 transition-colors
              [&>td]:border-b [&>td]:border-gray-200
            `,
            tableTbodyCell:
              "py-2 px-3 font-body text-[13px] 2xl:text-sm text-table-text relative",
            pagination: "",
          }}
          pagination={{
            controller: pagination,
            pageCount: paginationData?.totalPages ?? 1,
            totalItems: paginationData?.total ?? 0,
          }}
        />
      )}
    </section>
  );
}
