﻿import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ArchiveRestore, Building2, Landmark } from "lucide-react";

import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import { Button } from "@/shared/common/ui/button";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import {
  useArchivedOrganizations,
  useArchivedUnits,
  useArchiveActions,
} from "@/user-management/hooks/useArchived";

type Tab = "organizations" | "units";

const SuperAdminArchivedPage = () => {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();

  const [activeTab, setActiveTab] = useState<Tab>("organizations");

  const { organizationsResponse } = useOrganizations("Org", {
    take: 300,
    skip: 0,
  });
  const organizations: any[] = organizationsResponse?.items ?? [];

  const [selectedOrgId, setSelectedOrgId] = useState<string>("");
  if (!selectedOrgId && organizations.length > 0) {
    setSelectedOrgId(organizations[0].id);
  }

  const {
    data: archivedOrgsData,
    refetch: refetchArchivedOrgs,
  } = useArchivedOrganizations();
  const { data: archivedUnitsData, refetch: refetchArchivedUnits } =
    useArchivedUnits(activeTab === "units" ? selectedOrgId || undefined : undefined);

  const archivedOrgs: any[] = useMemo(
    () => archivedOrgsData?.items ?? archivedOrgsData ?? [],
    [archivedOrgsData],
  );
  const archivedUnits: any[] = useMemo(
    () => archivedUnitsData?.items ?? archivedUnitsData ?? [],
    [archivedUnitsData],
  );

  const {
    restoreUnit,
    isRestoringUnit,
    restoreOrganization,
    isRestoringOrganization,
  } = useArchiveActions();

  const orgColumns = [
    {
      id: "name",
      header: t("organization.name", "Name"),
      cell: ({ row }: any) => localizedName(row.original?.name) || "—",
    },
    {
      id: "key",
      header: t("organization.key", "Key"),
      accessorKey: "key",
    },
    {
      id: "actions",
      header: t("userIncomingretun.Actions", "Actions"),
      cell: ({ row }: any) => (
        <Button
          size="sm"
          variant="outline"
          disabled={isRestoringOrganization}
          onClick={() => restoreOrganization(row.original.id)}
          className="flex items-center gap-2 text-primary-700 hover:bg-primary-50">
          <ArchiveRestore className="h-4 w-4" />
          {t("archive.restore", "Restore")}
        </Button>
      ),
    },
  ];

  const unitColumns = [
    {
      id: "name",
      header: t("organization.name", "Name"),
      cell: ({ row }: any) => localizedName(row.original?.name) || "—",
    },
    {
      id: "key",
      header: t("organization.key", "Key"),
      accessorKey: "key",
    },
    {
      id: "actions",
      header: t("userIncomingretun.Actions", "Actions"),
      cell: ({ row }: any) => (
        <Button
          size="sm"
          variant="outline"
          disabled={isRestoringUnit}
          onClick={() => restoreUnit(row.original.id)}
          className="flex items-center gap-2 text-primary-700 hover:bg-primary-50">
          <ArchiveRestore className="h-4 w-4" />
          {t("archive.restore", "Restore")}
        </Button>
      ),
    },
  ];

  return (
    <div className="p-6 space-y-6">
      <Card className="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("archive.archivedItems", "Archived Items")}
          </CardTitle>
        </CardHeader>

        <div className="flex gap-2 mb-4">
          <Button
            variant={activeTab === "organizations" ? "default" : "outline"}
            onClick={() => setActiveTab("organizations")}
            className="flex items-center gap-2">
            <Landmark className="h-4 w-4" />
            {t("archive.archivedOrganizations", "Archived Organizations")}
          </Button>
          <Button
            variant={activeTab === "units" ? "default" : "outline"}
            onClick={() => setActiveTab("units")}
            className="flex items-center gap-2">
            <Building2 className="h-4 w-4" />
            {t("archive.archivedUnits", "Archived Units")}
          </Button>
        </div>

        {activeTab === "units" && organizations.length > 0 && (
          <div className="mb-4 w-full sm:w-1/2">
            <label className="block text-sm font-medium text-gray-700 dark:text-gray-200">
              {t("organization.selectOrganization", "Select Organization")}
            </label>
            <Select
              value={selectedOrgId}
              onValueChange={(value) => setSelectedOrgId(value)}>
              <SelectTrigger className="mt-1 block w-full">
                <SelectValue
                  placeholder={t("organization.selectOrganization")}
                />
              </SelectTrigger>
              <SelectContent>
                {organizations.map((org: any) => (
                  <SelectItem key={org.id} value={org.id}>
                    {localizedName(org.name)}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
        )}

        <CardContent className="px-0">
          {activeTab === "organizations" ? (
            <AdvancedTable
              columns={orgColumns as any}
              data={archivedOrgs}
              tableName="ArchivedOrganizations"
              toolBarPosition="right"
              itemCount={archivedOrgs.length}
              pageIndex={0}
              onPageChange={() => {}}
              nextFunction={() => {}}
              prevFunction={() => {}}
              refresh={refetchArchivedOrgs}
            />
          ) : (
            <AdvancedTable
              columns={unitColumns as any}
              data={archivedUnits}
              tableName="ArchivedUnits"
              toolBarPosition="right"
              itemCount={archivedUnits.length}
              pageIndex={0}
              onPageChange={() => {}}
              nextFunction={() => {}}
              prevFunction={() => {}}
              refresh={refetchArchivedUnits}
            />
          )}
        </CardContent>
      </Card>
    </div>
  );
};

export default SuperAdminArchivedPage;
