import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Loader2, Plus, ShieldCheck } from "lucide-react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";

import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/shared/common/ui/table";
import { useLocalizedName } from "@/shared/common/localizedName";
import { AssignedAdminsDto } from "@/shared/dto/organization/orgAdminsDto";
import { AssignAdminDialog } from "@/super-admin/components/organizationAdmins/AssignAdminDialog";
import { AdminRemoveConfirm } from "@/super-admin/components/organizationAdmins/RemoveAdminConfirm";
import { fetchUnitAdminById } from "@/super-admin/services/api/organizationAdminService";
import { removeUnitAdminRole } from "@/super-admin/services/api/userRoleService";

interface ManageUnitAdminDialogProps {
  isOpen: boolean;
  onClose: () => void;
  organizationId: string;
  unitId: string;
}

const normalizeAdmins = (data: unknown): AssignedAdminsDto[] => {
  if (Array.isArray(data)) return data as AssignedAdminsDto[];

  if (
    data &&
    typeof data === "object" &&
    "items" in data &&
    Array.isArray((data as { items?: unknown[] }).items)
  ) {
    return (data as { items: AssignedAdminsDto[] }).items;
  }

  return [];
};

export function ManageUnitAdminDialog({
  isOpen,
  onClose,
  organizationId,
  unitId,
}: ManageUnitAdminDialogProps) {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const queryClient = useQueryClient();
  const [isAssignDialogOpen, setIsAssignDialogOpen] = useState(false);
  const [removingUserId, setRemovingUserId] = useState<string | null>(null);

  const {
    data: admins = [],
    isLoading,
    isError,
    refetch,
  } = useQuery({
    queryKey: ["unitAdmins", unitId],
    queryFn: async () => {
      const response = await fetchUnitAdminById(unitId, {
        take: 300,
        skip: 0,
      });
      return normalizeAdmins(response.data);
    },
    enabled: isOpen && !!unitId,
    staleTime: 0,
  });

  const handleRemove = async (userId: string) => {
    setRemovingUserId(userId);

    try {
      await removeUnitAdminRole({ unitId, userId });
      await queryClient.invalidateQueries({
        queryKey: ["unitAdmins", unitId],
      });
      toast.success(
        t(
          "organization.unitAdminRemovedSuccess",
          "Unit admin removed successfully",
        ),
      );
    } catch (error: any) {
      toast.error(
        t("organization.unitAdminRemoveFailed", "Failed to remove unit admin"),
        {
          description: error?.response?.data?.message,
        },
      );
    } finally {
      setRemovingUserId(null);
    }
  };

  const handleAssigned = async () => {
    setIsAssignDialogOpen(false);
    await queryClient.invalidateQueries({
      queryKey: ["unitAdmins", unitId],
    });
  };

  return (
    <>
      <Dialog
        open={isOpen}
        onOpenChange={(open) => {
          if (!open && !isAssignDialogOpen) onClose();
        }}
      >
        <DialogContent className="sm:max-w-[850px]">
          <DialogHeader>
            <DialogTitle>
              {t("contentManagement.manageUnitAdmin", "Manage Unit Admin")}
            </DialogTitle>
            <DialogDescription>
              {t(
                "organization.manageUnitAdminInstructions",
                "View, add, or remove administrators assigned to this unit.",
              )}
            </DialogDescription>
          </DialogHeader>

          <div className="space-y-4">
            <div className="flex items-center justify-between">
              <div>
                <h3 className="font-medium">
                  {t("organization.currentUnitAdmins", "Current unit admins")}
                </h3>
                <p className="text-sm text-muted-foreground">
                  {t(
                    "organization.currentUnitAdminsDescription",
                    "Users who can administer this unit.",
                  )}
                </p>
              </div>
              <Button onClick={() => setIsAssignDialogOpen(true)}>
                <Plus className="mr-2 h-4 w-4" />
                {t("organization.addAdmin", "Add admin")}
              </Button>
            </div>

            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("organization.name", "Name")}</TableHead>
                    <TableHead>{t("common.email", "Email")}</TableHead>
                    <TableHead>{t("common.status", "Status")}</TableHead>
                    <TableHead className="text-right">
                      {t("common.actions", "Actions")}
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {isLoading ? (
                    <TableRow>
                      <TableCell colSpan={4} className="h-32 text-center">
                        <Loader2 className="mx-auto h-6 w-6 animate-spin text-primary" />
                      </TableCell>
                    </TableRow>
                  ) : isError ? (
                    <TableRow>
                      <TableCell colSpan={4} className="h-32 text-center">
                        <div className="space-y-3">
                          <p className="text-sm text-destructive">
                            {t(
                              "organization.errorLoadingAdmins",
                              "Failed to load admins.",
                            )}
                          </p>
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={() => refetch()}
                          >
                            {t("organization.retry", "Retry")}
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : admins.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={4} className="h-32 text-center">
                        <ShieldCheck className="mx-auto mb-2 h-7 w-7 text-muted-foreground" />
                        <p className="text-sm text-muted-foreground">
                          {t(
                            "organization.noUnitAdminsAssigned",
                            "No admins are assigned to this unit.",
                          )}
                        </p>
                      </TableCell>
                    </TableRow>
                  ) : (
                    admins.map((admin) => (
                      <TableRow key={admin.id}>
                        <TableCell className="font-medium">
                          {localizedName(admin.name) || admin.username}
                        </TableCell>
                        <TableCell>{admin.email || "—"}</TableCell>
                        <TableCell className="capitalize">
                          {admin.status || "—"}
                        </TableCell>
                        <TableCell className="text-right">
                          <AdminRemoveConfirm
                            onConfirm={() => handleRemove(admin.id)}
                            loading={removingUserId === admin.id}
                          />
                        </TableCell>
                      </TableRow>
                    ))
                  )}
                </TableBody>
              </Table>
            </div>
          </div>

          <DialogFooter>
            <Button type="button" variant="outline" onClick={onClose}>
              {t("common.close", "Close")}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {isAssignDialogOpen && (
        <AssignAdminDialog
          isOpen={isAssignDialogOpen}
          onClose={() => setIsAssignDialogOpen(false)}
          onSuccess={handleAssigned}
          organizationId={organizationId}
          unitId={unitId}
        />
      )}
    </>
  );
}
