import { useMemo, useState, useEffect } from "react"; import { useTranslation } from "react-i18next"; import { ArchiveRestore, Building2, UserSquare2, Trash2, Search, Filter } 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 { useUnit } from "@/user-management/hooks/useUnit"; import { useArchivedPositions, useArchivedUnits, useArchiveActions, } from "@/user-management/hooks/useArchived"; import { UnitDto } from "@/user-management/dto/unit/unitDto"; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/shared/common/ui/alert-dialog"; import { toast } from "sonner"; import { deleteUnit } from "@/user-management/services/api/unitService"; import { useQueryClient } from "@tanstack/react-query"; import { useMyAdminOrganizations } from "@/user-management/hooks/useOrgAdminOrganizations"; import { Badge } from "@/shared/common/ui/badge"; import { Skeleton } from "@/shared/common/ui/skeleton"; type Tab = "units" | "positions"; const ArchivedUnitsPositionsPage = () => { const { t } = useTranslation(); const localizedName = useLocalizedName(); const queryClient = useQueryClient(); const { getAccessibleList } = useUnit(); const { organizations: myAdminOrganizations } = useMyAdminOrganizations(); const [activeTab, setActiveTab] = useState("units"); const [selectedOrgId, setSelectedOrgId] = useState(""); const [selectedUnitId, setSelectedUnitId] = useState(""); const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false); const [unitToDelete, setUnitToDelete] = useState<{ id: string; name: string } | null>(null); const [isDeleting, setIsDeleting] = useState(false); const { data: unitsResponse, isLoading: isLoadingUnits } = getAccessibleList( selectedOrgId || "", { take: 300, skip: 0 }, !!selectedOrgId ); const unitList: UnitDto[] = selectedOrgId ? (unitsResponse?.data?.items ?? []) : []; const { data: archivedUnitsData, refetch: refetchArchivedUnits, isLoading: isLoadingArchivedUnits } = useArchivedUnits(selectedOrgId || undefined); const { data: archivedPositionsData, refetch: refetchArchivedPositions, isLoading: isLoadingArchivedPositions } = useArchivedPositions(selectedUnitId || undefined); const { restoreUnit, isRestoringUnit, restorePosition, isRestoringPosition } = useArchiveActions(); useEffect(() => { if (activeTab === "units" && !selectedOrgId && myAdminOrganizations.length > 0) { setSelectedOrgId(myAdminOrganizations[0].id); } }, [activeTab, myAdminOrganizations.length]); useEffect(() => { if (activeTab === "positions" && !selectedUnitId && unitList.length > 0) { setSelectedUnitId(unitList[0].id); } }, [activeTab, unitList.length]); const handlePermanentDelete = async () => { if (!unitToDelete) return; setIsDeleting(true); try { await deleteUnit(unitToDelete.id); toast.success(t("archive.unitDeletedPermanently", "Unit permanently deleted")); setDeleteConfirmOpen(false); setUnitToDelete(null); queryClient.invalidateQueries({ queryKey: ["archived-units"] }); refetchArchivedUnits(); } catch (error: any) { if (error?.response?.status === 400 && error?.response?.data?.message) { const errorMessage = error?.response?.data?.message; if (errorMessage.includes("Referenced Entity") || errorMessage.includes("referenced")) { toast.error( t("archive.cannotDeleteUnitWithPositions", "Cannot delete unit with related positions"), { description: t("archive.deletePositionsFirst", "Please delete or reassign all positions first."), duration: 5000 } ); } else { toast.error(t("archive.deleteUnitFailed", "Failed to delete unit")); } } else { toast.error(t("archive.deleteUnitFailed", "Failed to delete unit")); } } finally { setIsDeleting(false); } }; const archivedUnits: any[] = useMemo( () => archivedUnitsData?.items ?? archivedUnitsData ?? [], [archivedUnitsData], ); const archivedPositions: any[] = useMemo( () => archivedPositionsData?.items ?? archivedPositionsData ?? [], [archivedPositionsData], ); const unitColumns = [ { id: "name", header: t("organization.name", "Name"), cell: ({ row }: any) => (
{localizedName(row.original?.name) || "—"}
{t("archive.archivedAt", "Archived")}: {new Date(row.original?.archivedAt).toLocaleDateString()}
), }, { id: "key", header: t("organization.key", "Key"), cell: ({ row }: any) => ( {row.original?.key || "—"} ), }, { id: "status", header: t("common.status", "Status"), cell: ({ row }: any) => ( {t("archive.archived", "Archived")} ), }, { id: "actions", header: t("userIncomingretun.Actions", "Actions"), cell: ({ row }: any) => (
), }, ]; const positionColumns = [ { id: "name", header: t("organization.name", "Name"), cell: ({ row }: any) => (
{localizedName(row.original?.name) || "—"}
{t("archive.archivedAt", "Archived")}: {new Date(row.original?.archivedAt).toLocaleDateString()}
), }, { id: "key", header: t("organization.key", "Key"), cell: ({ row }: any) => ( {row.original?.key || "—"} ), }, { id: "status", header: t("common.status", "Status"), cell: ({ row }: any) => ( {t("archive.archived", "Archived")} ), }, { id: "actions", header: t("userIncomingretun.Actions", "Actions"), cell: ({ row }: any) => (
), }, ]; const isLoading = activeTab === "units" ? isLoadingArchivedUnits : isLoadingArchivedPositions; return (
{/* Header */}

{t("archive.archivedItems", "Archived Items")}

{t("archive.manageArchivedContent", "Restore or permanently delete archived content")}

{activeTab === "units" ? archivedUnits.length : archivedPositions.length} {t("common.items", "items")}
{/* Tab Buttons */}
{/* Filter Section */}
{activeTab === "units" ? ( myAdminOrganizations.length === 0 ? ( ) : ( ) ) : ( unitList.length === 0 ? (
{isLoadingUnits ? ( ) : ( t("common.noData", "No units available") )}
) : ( ) )}
{activeTab === "units" && (
{t("common.filter", "Filter")}
)}
{/* Table */}
{activeTab === "units" ? ( <> {t("archive.archivedUnits", "Archived Units")} ) : ( <> {t("archive.archivedPositions", "Archived Positions")} )}
{isLoading ? (
{[...Array(3)].map((_, i) => (
))}
) : ( <> {activeTab === "units" ? ( archivedUnits.length === 0 ? (

{t("common.noData", "No archived units")}

{t("archive.noArchivedUnits", "No archived units found for this organization")}

) : ( {}} nextFunction={() => {}} prevFunction={() => {}} refresh={refetchArchivedUnits} /> ) ) : ( archivedPositions.length === 0 ? (

{t("common.noData", "No archived positions")}

{t("archive.noArchivedPositions", "No archived positions found for this unit")}

) : ( {}} nextFunction={() => {}} prevFunction={() => {}} refresh={refetchArchivedPositions} /> ) )} )}
{/* Delete Confirmation Dialog */}
{t("archive.deletePermanentlyConfirm", "Permanently delete unit?")} {t("archive.deletePermanentlyDescription", "This will permanently delete")} "{unitToDelete?.name}" {t("archive.cannotBeUndone", "This action cannot be undone.")}
{t("common.Cancel")} {isDeleting ? ( {t("common.deleting", "Deleting...")} ) : ( t("archive.deletePermanently", "Delete Permanently") )}
); }; export default ArchivedUnitsPositionsPage;