import { type FC } from "react";
import Table from "@/components/Table";
import Filters from "@/components/Filters";
import { Add } from "iconsax-react";
import Button from "@/components/Button";
import { Link } from "react-router-dom";
import { Pages } from "@/config/Pages";
import {
  useDeleteUserGroup,
  useGetUserGroups,
} from "./hooks/useUserGroupData";
import { useUserGroupFilters } from "./hooks/useUserGroupFilters";
import { getUserGroupTableColumns } from "./components/UserGroupTableColumns";
import { useUserGroupFiltersFields } from "./components/UserGroupFiltersFields";

const UserGroupsList: FC = () => {
  const {
    filters,
    currentPage,
    apiParams,
    handleFiltersChange,
    handlePageChange,
    limit,
  } = useUserGroupFilters();

  const { data: groupsData, isLoading } = useGetUserGroups(apiParams);
  const { mutate: deleteUserGroup, isPending: isDeleting } =
    useDeleteUserGroup();

  const groups = groupsData?.data || [];
  const columns = getUserGroupTableColumns({
    onDelete: (id: string) => deleteUserGroup(id),
    isDeleting,
  });
  const filterFields = useUserGroupFiltersFields();
  const totalPages = Math.ceil(groups.length / limit) || 1;

  return (
    <div className="mt-5">
      <div className="flex justify-between items-center">
        <h1 className="text-lg font-light">گروه‌های مشتری</h1>
        <Link to={Pages.customers.groupsAdd}>
          <Button className="w-fit px-6">
            <div className="flex gap-2 items-center">
              <Add color="#fff" size={20} />
              <span>افزودن گروه</span>
            </div>
          </Button>
        </Link>
      </div>

      <div className="mt-8">
        <Filters
          fields={filterFields}
          onChange={handleFiltersChange}
          initialValues={filters}
          searchField="search"
        />
      </div>

      <Table
        columns={columns}
        data={groups}
        isloading={isLoading}
        pagination={{
          currentPage,
          totalPages,
          onPageChange: handlePageChange,
        }}
      />
    </div>
  );
};

export default UserGroupsList;
