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 { useMigratedData } from "@/super-admin/hooks/useMigratedData";
import { MigratedDataColumnDefn } from "./MigratedDataColumnDefn";
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 { useNavigate } from "react-router-dom";

export default function MigratedDataManagement() {
  const [pageIndex, setPageIndex] = useState(0);
  const pageSize = 10;
  const localizedName = useLocalizedName();
  const { t } = useTranslation();
  const navigate = useNavigate();

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

  const [selectedUnitId, setSelectedUnitId] = useState<string | null>(null);

  const treeOrganizationsOptions: TreeViewItemO[] = useMemo(() => {
    return (
      exteranlOrgsResponse?.items.map((org: ValidOrganizationDto) => ({
        id: org.id,
        name: org.name,
        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,
                hierarchyType: "unit",
                value: unit.id,
                children: [],
              }))
            : [],
      })) || []
    );
  }, [exteranlOrgsResponse, localizedName]);

  useEffect(() => {
    if (!selectedUnitId) {
      const firstValidUnit = exteranlOrgsResponse?.items
        ?.flatMap((org) => org.units)
        .find((u) => u.id);

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

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

  useEffect(() => {
    const saved = sessionStorage.getItem("selectedUnitId");
    if (saved) setSelectedUnitId(saved);
  }, []);

  const { data: migratedResponse, isLoading: loadingMigratedData } =
    useMigratedData(selectedUnitId ?? "", {
      skip: pageIndex * pageSize,
      take: pageSize,
      orderBy: "migratedAt:DESC",
    });

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

  if (loadingExternalOrgs || loadingMigratedData) {
    return <div>{t("common.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="px-0">
          <CardTitle className="text-xl font-semibold">
            {t("migration.migratedData")}
          </CardTitle>
          {/* Export button hidden until export API is available
          <Button onClick={exportMigrated}>
            {isExporting ? t("migration.exporting") : t("migration.exportData")}
          </Button>
          */}
        </CardHeader>

        <div className="mb-4 max-w-lg">
          <SimpleTreeSelect
            label={t("migration.selectUnit")}
            options={treeOrganizationsOptions}
            value={selectedUnitId}
            onChange={setSelectedUnitId}
            collapsible
            localizedName={localizedName}
          />
        </div>

        <CardContent className="px-0">
          <AdvancedTable
            columns={MigratedDataColumnDefn(localizedName, t, navigate)}
            data={migratedResponse?.items || []}
            tableName={t("migration.migratedData")}
            toolBarPosition="right"
            itemCount={migratedResponse?.count || 0}
            pageIndex={pageIndex}
            onPageChange={handlePageChange}
            nextFunction={() => handlePageChange(pageIndex + 1)}
            prevFunction={() => handlePageChange(Math.max(pageIndex - 1, 0))}
          />
        </CardContent>
      </Card>
    </div>
  );
}
