import { useEffect, useMemo, useState } from "react";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { t } from "i18next";
import { ArchivedUserColumnDefn } from "@/user-management/components/content/ArchivedUserColumnDefn";
import {
  fetchValidOrganization,
  ValidOrganizationDto,
} from "@/record-management/services/api/organizationService";
import { useLocalizedName } from "@/shared/common/localizedName";
import {
  SimpleTreeSelect,
  TreeViewItemO,
} from "@/shared/common/form/fields/FormFields";
import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import { useArchivedUsers } from "@/super-admin/hooks/useArchivedUsers";

const SuperAdminArchiveUsersPage = () => {
  const [pageIndex, setPageIndex] = useState(0);
  const pageSize = 10;
  const localizedName = useLocalizedName();
  const { t } = useTranslation();

  const {
    data: exteranlOrgsResponse,
    isLoading: loadingExternalOrgs,
    error: externalOrgsError,
  } = useQuery({
    queryKey: ["organizations"], // include param
    queryFn: fetchValidOrganization,
    staleTime: 5 * 60 * 1000,
  });

  // State for selected unit (single selection)
  const [selectedUnitId, setSelectedUnitId] = useState<string | null>(null);

  // Handle unit selection and ensure dropdown closes
  const handleUnitSelection = (unitId: string | null) => {
    setSelectedUnitId(unitId);
  };

  const treeOrganizationsOptions: TreeViewItemO[] = useMemo(() => {
    return (
      exteranlOrgsResponse?.items.map((org: ValidOrganizationDto) => ({
        id: org.id,
        name: org.name, // converts {en,am} => string
        hierarchyType: "organization",
        value: org.units.length === 1 ? org.units[0].id : "",
        children:
          Array.isArray(org.units) && org.units.length > 0
            ? org.units.map((unit) => ({
                id: unit.id,
                name: unit.name, // string
                hierarchyType: "unit",
                value: unit.id,
                children: [],
              }))
            : [],
      })) || []
    );
  }, [exteranlOrgsResponse, localizedName]);

  // After defining treeOrganizationsOptions
  useEffect(() => {
    if (!selectedUnitId && exteranlOrgsResponse?.items) {
      const firstValidUnit = exteranlOrgsResponse.items
        .flatMap((org) => org.units)
        .find((unit) => unit.id);

      if (firstValidUnit) {
        setSelectedUnitId(firstValidUnit.id);
      }
    }
  }, [exteranlOrgsResponse, selectedUnitId]);

  // Save
  useEffect(() => {
    if (selectedUnitId)
      sessionStorage.setItem("selectedArchiveUnitId", selectedUnitId);
  }, [selectedUnitId]);

  // Load on mount
  useEffect(() => {
    const saved = sessionStorage.getItem("selectedArchiveUnitId");
    if (saved) setSelectedUnitId(saved);
  }, []);

  const { data: archivedUsersData, refetch } = useArchivedUsers(
    selectedUnitId ?? ""
  );

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

  if (loadingExternalOrgs) {
    return <div className="text-gray-900 dark:text-gray-100">{t("loading")}</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-row justify-between items-center px-0">
          <CardTitle className="text-xl font-semibold">
            {t("setting.archivedUsers")}
          </CardTitle>
        </CardHeader>

        {/* Unit Selector */}
        <div className="mb-4">
          <SimpleTreeSelect
            label={t("selectUnit")}
            options={treeOrganizationsOptions}
            value={selectedUnitId}
            onChange={handleUnitSelection}
            collapsible
          />
        </div>

        {/* Archived Users Table */}
        <CardContent className="px-0">
          <AdvancedTable
            columns={ArchivedUserColumnDefn}
            data={archivedUsersData?.items || []}
            tableName="Archived Users"
            toolBarPosition="right"
            itemCount={archivedUsersData?.count || 0}
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={() => handlePageChange(pageIndex + 1)}
            prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
            refresh={refetch}
          />
        </CardContent>
      </Card>
    </div>
  );
};

export default SuperAdminArchiveUsersPage;
