import { useEffect, useMemo, useState } from "react";
import { Check, Loader2, UserPlus } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/shared/common/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/shared/common/ui/dialog";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { ScrollArea } from "@/shared/common/ui/scroll-area";
import { Badge } from "@/shared/common/ui/badge";
import { cn } from "@/super-admin/lib/utils";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useEmployees } from "@/user-management/hooks/useEmployees";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";

interface AssignExistingAdminModalProps {
  isOpen: boolean;
  onClose: () => void;
  /** org preselected in the panel (the page's current org) */
  organizationId: string;
  /** user ids that are already admins of the page's org — shown disabled */
  existingAdminIds: string[];
  /** server-side error from the last assign attempt, shown inline */
  apiError: string | null;
  /** unitId set → grant unit-admin of that unit instead of org-admin */
  onAssign: (userId: string, organizationId: string, unitId?: string) => void;
  isAssigning: boolean;
}

/**
 * Promote an existing employee to admin. Three panels like the old
 * AssignAdminDialog: pick an org (page org preselected), pick a unit (or
 * none → org admin), then pick a user — unit selection also filters the
 * employee list to that unit.
 */
export default function AssignExistingAdminModal({
  isOpen,
  onClose,
  organizationId,
  existingAdminIds,
  apiError,
  onAssign,
  isAssigning,
}: AssignExistingAdminModalProps) {
  const { t } = useTranslation();
  const localizedName = useLocalizedName();
  const [selectedUserId, setSelectedUserId] = useState("");
  const [search, setSearch] = useState("");
  const [orgId, setOrgId] = useState(organizationId);
  // "" → org admin (all org users listed); set → unit admin of that unit
  const [unitId, setUnitId] = useState("");

  const { organizationsResponse, isLoading: isLoadingOrgs } = useOrganizations(
    "Org",
    { take: 300 },
  );
  const orgs = organizationsResponse?.items ?? [];

  const { data: unitsResponse, isLoading: isLoadingUnits } =
    useUnit().getList(orgId, { take: 300, skip: 0 }, isOpen);
  const units = unitsResponse?.data?.items ?? [];

  const {
    employeesResponseByOrg,
    isLoadingEmployeesByOrg,
    isErrorEmployeesByOrg,
    refetchEmployeesByOrg,
  } = useEmployees({
    organizationId: isOpen ? orgId : undefined,
    unitId: unitId || undefined,
    params: { take: 3000, skip: 0 },
  });

  const filteredEmployees = useMemo(() => {
    const query = search.trim().toLowerCase();
    const employees = employeesResponseByOrg?.items ?? [];
    if (!query) return employees;
    return employees.filter((employee: any) => {
      const name = localizedName(employee.user?.name).toLowerCase();
      const email = employee.user?.email?.toLowerCase() ?? "";
      return name.includes(query) || email.includes(query);
    });
  }, [employeesResponseByOrg, localizedName, search]);

  const selectOrg = (id: string) => {
    setOrgId(id);
    setUnitId("");
    setSelectedUserId("");
  };

  const selectUnit = (id: string) => {
    setUnitId(id);
    setSelectedUserId("");
  };

  const handleClose = () => {
    if (isAssigning) return;
    setSelectedUserId("");
    setSearch("");
    setOrgId(organizationId);
    setUnitId("");
    onClose();
  };

  // already-admin info only covers the page's org
  const knownAdminIds = orgId === organizationId ? existingAdminIds : [];

  useEffect(() => {
    if (isOpen) {
      setOrgId(organizationId);
      setUnitId("");
      setSelectedUserId("");
      setSearch("");
    }
  }, [isOpen, organizationId]);

  return (
    <Dialog open={isOpen} onOpenChange={(open) => !open && handleClose()}>
      <DialogContent className="sm:max-w-[960px]">
        <DialogHeader>
          <DialogTitle>{t("orgAdmins.assign.title")}</DialogTitle>
          <DialogDescription>
            {t("orgAdmins.assign.description")}
          </DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
          {/* Step 1: organization (page org preselected) */}
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("organization.organizations")}
            </Label>
            {isLoadingOrgs ? (
              <div className="flex h-[320px] items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : (
              <ScrollArea className="h-[320px] rounded-md border border-gray-200 p-2 dark:border-gray-700">
                <div className="space-y-1">
                  {orgs.map((org) => (
                    <button
                      key={org.id}
                      type="button"
                      onClick={() => selectOrg(org.id)}
                      className={cn(
                        "flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm transition-colors",
                        orgId === org.id
                          ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"
                          : "text-gray-700 hover:bg-emerald-50 dark:text-gray-300 dark:hover:bg-emerald-900/20",
                      )}
                    >
                      <span className="truncate">
                        {localizedName(org.name)}
                      </span>
                      {orgId === org.id && (
                        <Check className="ml-2 h-4 w-4 shrink-0" />
                      )}
                    </button>
                  ))}
                </div>
              </ScrollArea>
            )}
          </div>

          {/* Step 2: unit (or none → org admin) */}
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("orgAdmins.form.unit")}
            </Label>
            {isLoadingUnits ? (
              <div className="flex h-[320px] items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : (
              <ScrollArea className="h-[320px] rounded-md border border-gray-200 p-2 dark:border-gray-700">
                <div className="space-y-1">
                  <button
                    type="button"
                    onClick={() => selectUnit("")}
                    className={cn(
                      "flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm transition-colors",
                      !unitId
                        ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"
                        : "text-gray-700 hover:bg-emerald-50 dark:text-gray-300 dark:hover:bg-emerald-900/20",
                    )}
                  >
                    <span>{t("orgAdmins.form.noUnit")}</span>
                    {!unitId && <Check className="ml-2 h-4 w-4 shrink-0" />}
                  </button>
                  {units.map((unit: any) => (
                    <button
                      key={unit.id}
                      type="button"
                      onClick={() => selectUnit(unit.id)}
                      className={cn(
                        "flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm transition-colors",
                        unitId === unit.id
                          ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"
                          : "text-gray-700 hover:bg-emerald-50 dark:text-gray-300 dark:hover:bg-emerald-900/20",
                      )}
                    >
                      <span className="truncate">
                        {localizedName(unit.name)}
                      </span>
                      {unitId === unit.id && (
                        <Check className="ml-2 h-4 w-4 shrink-0" />
                      )}
                    </button>
                  ))}
                </div>
              </ScrollArea>
            )}
          </div>

          {/* Step 3: user */}
          <div className="space-y-2">
            <Label className="text-sm font-semibold">
              {t("orgAdmins.assign.users")}
            </Label>
            <Input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              placeholder={t("orgAdmins.assign.searchUsers")}
            />
            {isLoadingEmployeesByOrg ? (
              <div className="flex h-[272px] items-center justify-center">
                <Loader2 className="h-6 w-6 animate-spin text-primary" />
              </div>
            ) : isErrorEmployeesByOrg ? (
              <div className="flex h-[272px] flex-col items-center justify-center gap-2 text-sm text-red-600 dark:text-red-400">
                {t("orgAdmins.assign.loadError")}
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => refetchEmployeesByOrg()}
                >
                  {t("common.retry")}
                </Button>
              </div>
            ) : (
              <ScrollArea className="h-[272px] rounded-md border border-gray-200 p-2 dark:border-gray-700">
                <div className="space-y-1">
                  {filteredEmployees.map((employee: any) => {
                    const userId = employee.user?.id;
                    if (!userId) return null;
                    const isAlreadyAdmin = knownAdminIds.includes(userId);
                    return (
                      <button
                        key={userId}
                        type="button"
                        disabled={isAlreadyAdmin}
                        onClick={() => setSelectedUserId(userId)}
                        className={cn(
                          "flex w-full items-center justify-between rounded-md px-3 py-2 text-left text-sm transition-colors",
                          isAlreadyAdmin
                            ? "cursor-not-allowed opacity-50"
                            : selectedUserId === userId
                              ? "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300"
                              : "text-gray-700 hover:bg-emerald-50 dark:text-gray-300 dark:hover:bg-emerald-900/20",
                        )}
                      >
                        <div className="min-w-0 flex-1">
                          <p className="truncate font-medium">
                            {localizedName(employee.user?.name) ||
                              employee.user?.email}
                          </p>
                          <p className="truncate text-xs text-gray-500 dark:text-gray-400">
                            {employee.user?.email}
                          </p>
                        </div>
                        {isAlreadyAdmin ? (
                          <Badge variant="outline" className="ml-2 shrink-0">
                            {t("orgAdmins.assign.alreadyAdmin")}
                          </Badge>
                        ) : (
                          selectedUserId === userId && (
                            <Check className="ml-2 h-4 w-4 shrink-0" />
                          )
                        )}
                      </button>
                    );
                  })}
                  {filteredEmployees.length === 0 && (
                    <p className="mt-2 text-center text-sm text-gray-500 dark:text-gray-400">
                      {t("orgAdmins.assign.noUsersFound")}
                    </p>
                  )}
                </div>
              </ScrollArea>
            )}
          </div>
        </div>

        {apiError && (
          <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">
            {apiError}
          </div>
        )}

        <DialogFooter>
          <Button
            type="button"
            variant="outline"
            onClick={handleClose}
            disabled={isAssigning}
          >
            {t("common.cancel")}
          </Button>
          <Button
            type="button"
            disabled={isAssigning || !selectedUserId || !orgId}
            onClick={() =>
              onAssign(selectedUserId, orgId, unitId || undefined)
            }
          >
            {isAssigning ? (
              <Loader2 className="mr-2 h-4 w-4 animate-spin" />
            ) : (
              <UserPlus className="mr-2 h-4 w-4" />
            )}
            {t("orgAdmins.assign.submit")}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
