import { useMemo, useState } from "react";
import { AdvancedTable } from "../../../shared/common/ui/table/AdvancedTable";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "../../../shared/common/ui/card";
import {
  useAllExternalUsers,
  userTypeEnum,
} from "@/super-admin/hooks/useExternalUsers";
import { ExternalUsersColumnDefn } from "./ExternalUsersColumnDefn";
import { useLocalizedName } from "@/shared/common/localizedName";
import { Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { RadioGroup, RadioGroupItem } from "@/shared/common/ui/radio-group";
import { Label } from "@/shared/common/ui/label";
import { useNavigate } from "react-router-dom";
import {
  CombinedFilterBar,
  CombinedFilterField,
} from "@/shared/components/filters/CombinedFilterBar";
import { useCombinedFilters } from "@/shared/hooks/useCombinedFilters";
import { FilterParams } from "@/shared/utils/filterParams";

export default function PendingExternalUsers() {
  const localizedName = useLocalizedName();
  const [pageIndex, setPageIndex] = useState(0);
  const pageSize = 10;
  const { t } = useTranslation();
  const navigate = useNavigate();
  const filterStore = useCombinedFilters<FilterParams>();
  const [selectedUserType, setSelectedUserType] = useState<userTypeEnum>(
    userTypeEnum.externalUsers,
  );

  const filterFields = useMemo<CombinedFilterField[]>(
    () => [
      { key: "name", label: t("profile.name", "Name"), type: "text" },
      { key: "email", label: t("profile.emailmsg", "Email"), type: "text" },
      {
        key: "username",
        label: t("profile.username", "Username"),
        type: "text",
      },
      {
        key: "phoneNumber",
        label: t("profile.phoneNumber", "Phone Number"),
        type: "text",
      },
    ],
    [t],
  );

  const { data, isLoading } = useAllExternalUsers({
    take: pageSize,
    skip: pageIndex * pageSize,
    orderBy: "updatedAt:Desc",
    userType: selectedUserType,
    ...filterStore.filters,
  });

  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };

  const handleFilterChange = () => {
    setPageIndex(0);
  };

  if (isLoading) {
    return (
      <div className="flex justify-center p-6">
        <Loader2 className="animate-spin w-6 h-6 text-gray-500 dark:text-gray-400" />
      </div>
    );
  }

  return (
    <div className="p-6 space-y-6">
      <Card className="col-span-2 shadow-none border-none bg-transparent px-0">
        <CardHeader className="flex flex-col gap-4 px-0 sm:flex-row sm:items-center sm:justify-between">
          <CardTitle className="text-xl font-semibold">All Users</CardTitle>

          <RadioGroup
            value={selectedUserType}
            onValueChange={(val: userTypeEnum) => {
              setSelectedUserType(val);
              setPageIndex(0);
            }}
            className="flex flex-wrap gap-4"
          >
            <div className="flex items-center space-x-2">
              <RadioGroupItem
                value={userTypeEnum.externalUsers}
                id="allExternal"
              />
              <Label htmlFor="allExternal">All External Users</Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value={userTypeEnum.external} id="external" />
              <Label htmlFor="external">External Organization</Label>
            </div>
            <div className="flex items-center space-x-2">
              <RadioGroupItem value={userTypeEnum.individual} id="individual" />
              <Label htmlFor="individual">Individual</Label>
            </div>
          </RadioGroup>
        </CardHeader>

        <CardContent className="space-y-4 px-0">
          <CombinedFilterBar
            fields={filterFields}
            filters={filterStore.filters}
            setFilter={filterStore.setFilter}
            setFilters={filterStore.setFilters}
            removeFilter={filterStore.removeFilter}
            removeFilters={filterStore.removeFilters}
            onFilterChange={handleFilterChange}
            className="w-full min-w-0"
          />

          <AdvancedTable
            columns={ExternalUsersColumnDefn(localizedName, navigate)}
            data={data?.items || []}
            tableName="ExternalUsers"
            toolBarPosition="right"
            itemCount={data?.count || 0}
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={() => handlePageChange(pageIndex + 1)}
            prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
            hideToolbarFilter
            disableClientFiltering
          />
        </CardContent>
      </Card>
    </div>
  );
}
