import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useAuth } from "@/shared/context/AuthContext";
import { useArchivedUsers } from "@/super-admin/hooks/useArchivedUsers";
import { ArchivedUserColumnDefn } from "@/user-management/components/content/ArchivedUserColumnDefn";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useEffect, useState } from "react";
import { useLocalizedName } from "@/shared/common/localizedName";
import { t } from "i18next";

const ArchiveUsersPage = () => {
  const { user } = useAuth();
  const { getAccessibleList } = useUnit();
  const [pageIndex, setPageIndex] = useState(0);
  const pageSize = 10;
  const localizedName = useLocalizedName();
  const organizationId =
    user?.employee && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;
  const { data: unitsResponse } = organizationId
    ? getAccessibleList(organizationId, {
        take: 300,
        skip: 0,
      })
    : { data: undefined };

  const [selectedUnitId, setSelectedUnitId] = useState<string>(
    unitsResponse?.data?.items[0]?.id || "All",
  );
  useEffect(() => {
    if (unitsResponse?.data?.items.length > 0) {
      setSelectedUnitId(unitsResponse?.data.items[0].id);
    }
  }, [unitsResponse?.data?.items]);
  const handlePageChange = (newPage: number) => {
    setPageIndex(newPage);
  };
  const { data, refetch } = useArchivedUsers(selectedUnitId, {
    take: pageSize,
    skip: pageIndex * pageSize,
  });

  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-row justify-between items-center px-0">
          <CardTitle className="text-xl font-semibold ">
            {t("setting.archivedUsers")}
          </CardTitle>
        </CardHeader>
        {unitsResponse?.data?.items?.length > 0 && (
          <div className="mb-4 w-1/2">
            <label className="block text-sm font-medium text-gray-700">
              {t("organization.selectUnit")}
            </label>
            <Select
              value={selectedUnitId}
              onValueChange={(value) => setSelectedUnitId(value)}
            >
              <SelectTrigger className="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-primary-500 focus:border-primary-500 sm:text-sm [&>span]:truncate">
                <SelectValue placeholder="Select a Unit" />
              </SelectTrigger>
              <SelectContent>
                {unitsResponse?.data.items.map((unit: UnitDto) => (
                  <SelectItem key={unit.id} value={unit.id}>
                    <span className="block truncate max-w-70">{localizedName(unit.name)}</span>
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}
        <CardContent className="px-0">
          <AdvancedTable
            columns={ArchivedUserColumnDefn}
            data={data?.items || []}
            tableName="ArchivedUsers"
            toolBarPosition="right"
            itemCount={data?.count || 0}
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={
              data?.count && data.count > (pageIndex + 1) * pageSize
                ? () => handlePageChange(pageIndex + 1)
                : () => {}
            }
            prevFunction={
              pageIndex > 0
                ? () => handlePageChange(Math.max(pageIndex - 1, 0))
                : () => {}
            }
            refresh={refetch}
          />
        </CardContent>
      </Card>
    </div>
  );
};

export default ArchiveUsersPage;
