import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { Building2, Loader2, Plus, UserPlus, Users2 } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@/shared/common/ui/card";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from "@/shared/common/ui/alert-dialog";
import { Badge } from "@/shared/common/ui/badge";
import { AdvancedTable } from "@/shared/common/ui/table/AdvancedTable";
import { useLocalizedName } from "@/shared/common/localizedName";
import { OrganizationDto } from "@/shared/dto/organization/organizationDto";
import {
  OrgAdminUser,
  useOrgAdmins,
} from "@/super-admin/hooks/useOrgAdmins";
import { OrgPicker } from "./OrgPicker";
import {
  AdminRoleInfo,
  getOrgAdminsColumnDefn,
} from "./OrgAdminsColumnDefn";
import AdminFormModal, { AdminFormValues } from "./AdminFormModal";
import AssignExistingAdminModal from "./AssignExistingAdminModal";

interface RemoveTarget {
  admin: OrgAdminUser;
  roleInfo: AdminRoleInfo;
}

export default function OrgAdminsPage() {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();

  const [selectedOrg, setSelectedOrg] = useState<OrganizationDto | null>(null);
  const [pageIndex, setPageIndex] = useState(0);
  const [pageSize, setPageSize] = useState(10);

  // modals & confirms
  const [formOpen, setFormOpen] = useState(false);
  const [editAdmin, setEditAdmin] = useState<OrgAdminUser | null>(null);
  const [assignOpen, setAssignOpen] = useState(false);
  const [removeTarget, setRemoveTarget] = useState<RemoveTarget | null>(null);
  const [toggleTarget, setToggleTarget] = useState<OrgAdminUser | null>(null);

  const {
    adminsResponse,
    isLoading,
    isError,
    refetch,
    addAdmin,
    isAdding,
    assignAdmin,
    isAssigning,
    removeAdmin,
    isRemoving,
    resendInvite,
    toggleActive,
    isToggling,
    updateAdminProfile,
    isUpdatingProfile,
    formError,
    assignError,
    removeError,
    toggleError,
    clearErrors,
  } = useOrgAdmins(selectedOrg?.id, {
    take: pageSize,
    skip: pageIndex * pageSize,
  });

  useEffect(() => {
    setPageIndex(0);
  }, [selectedOrg?.id, pageSize]);

  const admins = adminsResponse?.items ?? [];
  const adminCount = adminsResponse?.count ?? 0;
  const existingAdminIds = useMemo(
    () => admins.map((admin) => admin.id),
    [admins],
  );

  const handleFormSubmit = (values: AdminFormValues) => {
    if (!selectedOrg) return;
    const person = {
      name: values.name,
      username: values.username,
      email: values.email,
      phoneNumber: values.phoneNumber,
    };
    if (editAdmin) {
      updateAdminProfile(
        { id: editAdmin.id, payload: person },
        {
          onSuccess: () => {
            setFormOpen(false);
            setEditAdmin(null);
          },
        },
      );
    } else {
      addAdmin(
        {
          organizationId: values.organizationId,
          unitId: values.unitId || undefined,
          ...person,
        },
        { onSuccess: () => setFormOpen(false) },
      );
    }
  };

  const handleAssign = (
    userId: string,
    organizationId: string,
    unitId?: string,
  ) => {
    assignAdmin(
      { organizationId, userId, unitId },
      { onSuccess: () => setAssignOpen(false) },
    );
  };

  const handleRemoveConfirm = () => {
    if (!removeTarget || !selectedOrg) return;
    const { admin, roleInfo } = removeTarget;
    removeAdmin(
      // unit-admin-only rows go through the unit endpoint; everything else
      // defaults to org removal so a role anomaly never sends unitId: undefined
      !roleInfo.isOrgAdmin && roleInfo.unitId
        ? { userId: admin.id, unitId: roleInfo.unitId }
        : { userId: admin.id, organizationId: selectedOrg.id },
      { onSuccess: () => setRemoveTarget(null) },
    );
  };

  const handleResend = (admin: OrgAdminUser) => {
    if (!admin.email || !admin.phoneNumber) {
      toast.error(t("orgAdmins.toasts.missingContact"));
      return;
    }
    const toastId = toast.loading(t("orgAdmins.toasts.resending"));
    resendInvite(
      { email: admin.email, phoneNumber: admin.phoneNumber },
      { onSettled: () => toast.dismiss(toastId) },
    );
  };

  const handleToggleConfirm = () => {
    if (!toggleTarget) return;
    toggleActive(
      { id: toggleTarget.id, activate: !toggleTarget.isActive },
      { onSuccess: () => setToggleTarget(null) },
    );
  };

  const columns = useMemo(
    () =>
      getOrgAdminsColumnDefn({
        selectedOrgId: selectedOrg?.id ?? "",
        localizedName: localizedName as (name?: {
          am?: string;
          en?: string;
        }) => string,
        onEdit: (admin) => {
          setEditAdmin(admin);
          setFormOpen(true);
        },
        onResend: handleResend,
        onToggleActive: setToggleTarget,
        onRemove: (admin, roleInfo) => setRemoveTarget({ admin, roleInfo }),
      }),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [selectedOrg?.id],
  );

  return (
    <div className="p-6 space-y-6">
      <Card className="shadow-none border-none bg-transparent px-0">
        <CardHeader className="px-0 space-y-1">
          <CardTitle className="text-2xl font-bold text-slate-800 dark:text-slate-100">
            {t("orgAdmins.title")}
          </CardTitle>
          <p className="text-sm text-muted-foreground">
            {t("orgAdmins.subtitle")}
          </p>
        </CardHeader>
        <CardContent className="px-0 space-y-4">
          {/* Org selector + summary */}
          <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <OrgPicker value={selectedOrg} onChange={setSelectedOrg} />
            {selectedOrg && (
              <div className="flex flex-wrap items-center gap-2">
                <Badge
                  variant="outline"
                  className="gap-1 border-indigo-300 bg-indigo-50 text-indigo-700 dark:border-indigo-800 dark:bg-indigo-950 dark:text-indigo-300"
                >
                  <Users2 className="h-3.5 w-3.5" />
                  {t("orgAdmins.adminsCount", { count: adminCount })}
                </Badge>
                {selectedOrg.activeEmployeeCount !== undefined && (
                  <Badge variant="outline" className="gap-1">
                    {t("orgAdmins.activeEmployees", {
                      count: selectedOrg.activeEmployeeCount,
                    })}
                  </Badge>
                )}
                <Badge
                  variant="outline"
                  className={
                    selectedOrg.status === "Active"
                      ? "border-emerald-300 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950 dark:text-emerald-300"
                      : "border-amber-300 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-300"
                  }
                >
                  {selectedOrg.status}
                </Badge>
              </div>
            )}
          </div>

          {!selectedOrg ? (
            <div className="flex h-64 flex-col items-center justify-center gap-3 rounded-lg border border-dashed border-gray-300 dark:border-gray-700">
              <Building2 className="h-10 w-10 text-muted-foreground" />
              <p className="font-medium text-slate-700 dark:text-slate-200">
                {t("orgAdmins.selectOrgPrompt")}
              </p>
              <p className="text-sm text-muted-foreground">
                {t("orgAdmins.selectOrgPromptHint")}
              </p>
            </div>
          ) : (
            <>
              {isError && (
                <div className="flex items-center justify-between gap-3 rounded-md border border-red-300 bg-red-50 px-4 py-3 text-sm text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-300">
                  {t("orgAdmins.loadError")}
                  <Button variant="outline" size="sm" onClick={() => refetch()}>
                    {t("common.retry")}
                  </Button>
                </div>
              )}
              {!isLoading && !isError && adminCount === 0 && (
                <div className="rounded-md border border-amber-300 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:border-amber-800 dark:bg-amber-950 dark:text-amber-300">
                  {t("orgAdmins.noAdminsHint", {
                    name: localizedName(selectedOrg.name),
                  })}
                </div>
              )}
              <AdvancedTable
                columns={columns}
                data={admins}
                tableName={t("orgAdmins.tableName")}
                toolBarPosition="right"
                itemCount={adminCount}
                pageIndex={pageIndex}
                pageSize={pageSize}
                onPageChange={setPageIndex}
                onPageSizeChange={setPageSize}
                nextFunction={() => setPageIndex(pageIndex + 1)}
                prevFunction={() => setPageIndex(Math.max(pageIndex - 1, 0))}
                refresh={refetch}
                isLoading={isLoading}
                extraToolbar={
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      onClick={() => setAssignOpen(true)}
                    >
                      <UserPlus className="mr-2 h-4 w-4" />
                      {t("orgAdmins.assignExisting")}
                    </Button>
                    <Button
                      onClick={() => {
                        setEditAdmin(null);
                        setFormOpen(true);
                      }}
                    >
                      <Plus className="mr-2 h-4 w-4" />
                      {t("orgAdmins.addAdmin")}
                    </Button>
                  </div>
                }
              />
            </>
          )}
        </CardContent>
      </Card>

      {/* Add / Edit modal */}
      <AdminFormModal
        isOpen={formOpen}
        onClose={() => {
          setFormOpen(false);
          setEditAdmin(null);
          clearErrors();
        }}
        admin={editAdmin}
        organizationId={selectedOrg?.id}
        apiError={formError}
        onSubmit={handleFormSubmit}
        isSubmitting={isAdding || isUpdatingProfile}
      />

      {/* Assign existing employee modal */}
      {selectedOrg && (
        <AssignExistingAdminModal
          isOpen={assignOpen}
          onClose={() => {
            setAssignOpen(false);
            clearErrors();
          }}
          organizationId={selectedOrg.id}
          existingAdminIds={existingAdminIds}
          apiError={assignError}
          onAssign={handleAssign}
          isAssigning={isAssigning}
        />
      )}

      {/* Remove admin confirm */}
      <AlertDialog
        open={!!removeTarget}
        onOpenChange={(open) => {
          if (!open) {
            setRemoveTarget(null);
            clearErrors();
          }
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-lg font-bold text-red-600">
              {t("orgAdmins.confirmRemove.title")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("orgAdmins.confirmRemove.description", {
                name:
                  localizedName(removeTarget?.admin.name) ||
                  removeTarget?.admin.email,
                org: localizedName(selectedOrg?.name),
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          {removeError && (
            <div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-300">
              {removeError}
            </div>
          )}
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isRemoving}>
              {t("common.cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              disabled={isRemoving}
              onClick={handleRemoveConfirm}
              className="bg-red-600 hover:bg-red-700 text-white"
            >
              {isRemoving
                ? t("orgAdmins.confirmRemove.removing")
                : t("orgAdmins.actions.remove")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>

      {/* Activate / Deactivate confirm */}
      <AlertDialog
        open={!!toggleTarget}
        onOpenChange={(open) => {
          if (!open) {
            setToggleTarget(null);
            clearErrors();
          }
        }}
      >
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle className="text-lg font-bold">
              {toggleTarget?.isActive
                ? t("orgAdmins.confirmToggle.deactivateTitle")
                : t("orgAdmins.confirmToggle.activateTitle")}
            </AlertDialogTitle>
            <AlertDialogDescription>
              {t("orgAdmins.confirmToggle.description", {
                name:
                  localizedName(toggleTarget?.name) || toggleTarget?.email,
              })}
            </AlertDialogDescription>
          </AlertDialogHeader>
          {toggleError && (
            <div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-800 dark:border-red-800 dark:bg-red-950 dark:text-red-300">
              {toggleError}
            </div>
          )}
          <AlertDialogFooter>
            <AlertDialogCancel disabled={isToggling}>
              {t("common.cancel")}
            </AlertDialogCancel>
            <AlertDialogAction
              disabled={isToggling}
              onClick={handleToggleConfirm}
              className={
                toggleTarget?.isActive
                  ? "bg-amber-600 hover:bg-amber-700 text-white"
                  : "bg-emerald-600 hover:bg-emerald-700 text-white"
              }
            >
              {isToggling && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
              {toggleTarget?.isActive
                ? t("orgAdmins.actions.deactivate")
                : t("orgAdmins.actions.activate")}
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </div>
  );
}
