import { useEffect, useMemo, useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { ScrollArea } from "@/shared/common/ui/scroll-area";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Check, Loader2 } from "lucide-react";
import { toast } from "sonner";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";

import { useEmployees } from "@/user-management/hooks/useEmployees";
import { cn } from "@/super-admin/lib/utils";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "../../../shared/common/ui/dialog";
import { useTranslation } from "react-i18next";
import {
  RemoveOrAssignUnitAdminPayload,
  assignUnitAdminRole,
} from "@/super-admin/services/api/userRoleService";
import { useQueryClient } from "@tanstack/react-query";
import { Input } from "@/shared/common/ui/input";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useUnit } from "@/user-management/hooks/useUnit";

export function AssignAdminDialog({
  onSuccess,
  onClose,
  isOpen,
  organizationId,
  unitId,
}: {
  onSuccess: () => void;
  isOpen: boolean;
  onClose: () => void;
  organizationId?: string;
  unitId?: string;
}) {
  const queryClient = useQueryClient();
  const [selectedOrg, setSelectedOrg] = useState<string>(organizationId ?? "");
  const [selectedUnit, setSelectedUnit] = useState<string>(unitId ?? "");
  const [selectedAssignmentUnit, setSelectedAssignmentUnit] =
    useState<string>("");
  const [selectedUser, setSelectedUser] = useState<string>("");
  const [isAssigning, setIsAssigning] = useState<boolean>(false);
  const [search, setSearch] = useState("");
  const { t } = useTranslation();
  const [page, setPage] = useState(0);
  const take = 3000; // items per page
  const localizedName = useLocalizedName();
  const hasPreselectedUnit = !!organizationId && !!unitId;
  const organizationIdForAssignment = organizationId || selectedOrg;
  const unitIdForAssignment =
    unitId || selectedUnit || selectedAssignmentUnit;
  const { organizationsResponse, isLoading: isLoadingOrgs } = useOrganizations(
    "Org",
    {
      take: 300,
    }
  );
  const { data: unitsResponse, isLoading: isLoadingUnits } = useUnit().getList(
    organizationIdForAssignment,
    { take: 300, skip: 0 },
    !hasPreselectedUnit
  );
  const {
    employeesResponseByOrg,
    isLoadingEmployeesByOrg: isLoadingEmployees,
    refetchEmployeesByOrg,
  } = useEmployees({
    organizationId: organizationIdForAssignment || undefined,
    unitId: unitIdForAssignment || undefined,
    params: {
      take,
      skip: page * take,
    },
  });

  // Refetch when unit selection changes
  useEffect(() => {
    if (unitIdForAssignment) {
      refetchEmployeesByOrg();
    }
  }, [unitIdForAssignment, refetchEmployeesByOrg]);

  useEffect(() => {
    if (selectedOrg && !hasPreselectedUnit) {
      setSelectedUnit("");
      setSelectedAssignmentUnit("");
      setSelectedUser("");
      setPage(0);
    }
  }, [hasPreselectedUnit, selectedOrg]);

  useEffect(() => {
    if (selectedUnit && !hasPreselectedUnit) {
      setSelectedAssignmentUnit("");
      setSelectedUser("");
      setPage(0);
    }
  }, [hasPreselectedUnit, selectedUnit]);

  useEffect(() => {
    if (!isOpen) return;

    setSelectedOrg(organizationId ?? "");
    setSelectedUnit(unitId ?? "");
    setSelectedAssignmentUnit("");
    setSelectedUser("");
    setPage(0);
    setSearch("");
  }, [isOpen, organizationId, unitId]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (
      !selectedUser ||
      !organizationIdForAssignment ||
      !unitIdForAssignment
    ) {
      toast.error("All fields are required");
      return;
    }

    const user = employeesResponseByOrg?.items.find(
      (e) => e.user.id === selectedUser
    );
    if (!user) return toast.error("User not found");

    setIsAssigning(true);

    const payload: RemoveOrAssignUnitAdminPayload = {
      unitId: unitIdForAssignment,
      userId: user.user.id,
    };

    assignUnitAdminRole(payload)
      .then(() => {
        queryClient.invalidateQueries({
          queryKey: ["organizationAdmins"],
        });
        queryClient.invalidateQueries({
          queryKey: ["unitAdmins", unitIdForAssignment],
        });
        toast.success(t("organization.userAssignedSuccess"));
        setIsAssigning(false);
        onClose();
        onSuccess();
      })
      .catch((error) => {
        toast.error(t("organization.userAssignFailed"), {
          description: error?.response?.data?.message,
        });
        setIsAssigning(false);
      });
  };

  const resetForm = () => {
    setSelectedOrg(organizationId ?? "");
    setSelectedUnit(unitId ?? "");
    setSelectedAssignmentUnit("");
    setSelectedUser("");
    setPage(0);
    setSearch("");
  };

  const filteredEmployees = useMemo(() => {
    if (!employeesResponseByOrg?.items) return [];

    return employeesResponseByOrg.items.filter((emp) => {
      const name = emp.user.name?.en?.toLowerCase() || "";
      const email = emp.user.email?.toLowerCase() || "";
      const query = search.toLowerCase();

      return name.includes(query) || email.includes(query);
    });
  }, [employeesResponseByOrg, search]);

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent
        className={hasPreselectedUnit ? "sm:max-w-[550px]" : "sm:max-w-[900px]"}
      >
        <DialogHeader>
          <DialogTitle>
            {hasPreselectedUnit
              ? t("contentManagement.manageUnitAdmin", "Manage Unit Admin")
              : t("organization.assignAdminToOrganization")}
          </DialogTitle>
          <DialogDescription>
            {hasPreselectedUnit
              ? t(
                  "organization.assignUnitAdminInstructions",
                  "Select a user to assign as an administrator for this unit."
                )
              : t("organization.assignAdminInstructions")}
          </DialogDescription>
        </DialogHeader>

        <form onSubmit={handleSubmit} className="space-y-6">
          <div
            className={
              hasPreselectedUnit
                ? "grid grid-cols-1 gap-4"
                : "grid grid-cols-3 gap-4"
            }
          >
            {/* Step 1: Organizations */}
            {!hasPreselectedUnit && <div className="space-y-2">
              <Label className="font-semibold text-sm">
                {t("organization.organizations")} <span className="text-red-500">*</span>
              </Label>
              {isLoadingOrgs ? (
                <div className="flex items-center justify-center h-64">
                  <Loader2 className="h-6 w-6 animate-spin text-primary" />
                </div>
              ) : (
                <ScrollArea className="h-[300px] border border-gray-200 dark:border-gray-700 rounded-md p-2">
                  <div className="space-y-1">
                    {organizationsResponse?.items?.map((org) => (
                      <button
                        key={`org-${org.id}`}
                        onClick={() => setSelectedOrg(org.id)}
                        type="button"
                        className={cn(
                          "w-full flex items-center justify-between px-3 py-2 rounded-md text-left text-sm transition-colors",
                          selectedOrg === org.id
                            ? "bg-green-200 text-green-800 dark:bg-green-900/40 dark:text-green-300"
                            : "hover:bg-green-100 dark:hover:bg-green-900/30 text-gray-700 dark:text-gray-300"
                        )}
                      >
                        <span>{localizedName(org.name)}</span>
                        {selectedOrg === org.id && (
                          <Check className="h-4 w-4" />
                        )}
                      </button>
                    ))}
                  </div>
                </ScrollArea>
              )}
            </div>}

            {/* Step 2: Units */}
            {!hasPreselectedUnit && <div className="space-y-2">
              <Label className="font-semibold text-sm">
                {t("organization.units")} <span className="text-red-500">*</span>
              </Label>
              {!selectedOrg ? (
                <div className="h-[300px] border border-gray-200 dark:border-gray-700 rounded-md p-4 flex items-center justify-center text-gray-500 dark:text-gray-400">
                  <p className="text-sm text-center">{t("organization.selectOrganizationFirst")}</p>
                </div>
              ) : isLoadingUnits ? (
                <div className="flex items-center justify-center h-64">
                  <Loader2 className="h-6 w-6 animate-spin text-primary" />
                </div>
              ) : (
                <ScrollArea className="h-[300px] border border-gray-200 dark:border-gray-700 rounded-md p-2">
                  <div className="space-y-1">
                    <button
                      onClick={() => setSelectedUnit("")}
                      type="button"
                      className={cn(
                        "w-full flex items-center justify-between px-3 py-2 rounded-md text-left text-sm transition-colors",
                        !selectedUnit
                          ? "bg-primary-200 text-primary-800 dark:bg-primary-900/40 dark:text-primary-300"
                          : "hover:bg-primary-100 dark:hover:bg-primary-900/30 text-gray-700 dark:text-gray-300"
                      )}
                    >
                      <span>
                        {t(
                          "organization.allOrganizationUsers",
                          "All organization users"
                        )}
                      </span>
                      {!selectedUnit && <Check className="h-4 w-4" />}
                    </button>
                    {unitsResponse?.data?.items?.map((unit: any) => (
                      <button
                        key={`unit-${unit.id}`}
                        onClick={() => setSelectedUnit(unit.id)}
                        type="button"
                        className={cn(
                          "w-full flex items-center justify-between px-3 py-2 rounded-md text-left text-sm transition-colors",
                          selectedUnit === unit.id
                            ? "bg-primary-200 text-primary-800 dark:bg-primary-900/40 dark:text-primary-300"
                            : "hover:bg-primary-100 dark:hover:bg-primary-900/30 text-gray-700 dark:text-gray-300"
                        )}
                      >
                        <span>{localizedName(unit.name)}</span>
                        {selectedUnit === unit.id && (
                          <Check className="h-4 w-4" />
                        )}
                      </button>
                    ))}
                    {unitsResponse?.data?.items?.length === 0 && (
                      <p className="text-sm text-gray-500 dark:text-gray-400 text-center mt-2">
                        {t("organization.noUnitsFound")}
                      </p>
                    )}
                  </div>
                </ScrollArea>
              )}
            </div>}

            {/* Step 3: Users */}
            <div className="space-y-2">
              <Label className="font-semibold text-sm">
                {t("organization.users")} <span className="text-red-500">*</span>
              </Label>
              {!organizationIdForAssignment ? (
                <div className="h-[300px] border border-gray-200 dark:border-gray-700 rounded-md p-4 flex items-center justify-center text-gray-500 dark:text-gray-400">
                  <p className="text-sm text-center">{t("organization.selectOrganizationFirst")}</p>
                </div>
              ) : isLoadingEmployees ? (
                <div className="flex items-center justify-center h-64">
                  <Loader2 className="h-6 w-6 animate-spin text-primary" />
                </div>
              ) : (
                <div className="space-y-2">
                  {!unitIdForAssignment && (
                    <div className="space-y-2">
                      <Label className="text-xs font-medium text-gray-600 dark:text-gray-300">
                        {t(
                          "organization.unitForAdminRole",
                          "Unit for admin role"
                        )}{" "}
                        <span className="text-red-500">*</span>
                      </Label>
                      <Select
                        value={selectedAssignmentUnit}
                        onValueChange={setSelectedAssignmentUnit}
                        disabled={isLoadingUnits}
                      >
                        <SelectTrigger className="h-9 border border-gray-200 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-gray-100 text-sm [&>span]:truncate w-full">
                          <SelectValue
                            placeholder={t("organization.selectUnit")}
                          />
                        </SelectTrigger>
                        <SelectContent className="w-full min-w-[200px]">
                          {unitsResponse?.data?.items?.map((unit: any) => (
                            <SelectItem key={unit.id} value={unit.id}>
                              <span className="truncate">{localizedName(unit.name)}</span>
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                    </div>
                  )}
                  <Input
                    placeholder={
                      unitIdForAssignment
                        ? t("organization.searchUsers")
                        : t(
                            "organization.searchOrganizationUsers",
                            "Search organization users"
                          )
                    }
                    value={search}
                    onChange={(e) => setSearch(e.target.value)}
                    className="border border-gray-200 dark:border-gray-700 rounded-md dark:bg-gray-800 dark:text-gray-100 text-sm"
                  />
                  {!unitIdForAssignment && (
                    <p className="text-xs text-gray-500 dark:text-gray-400">
                      {t(
                        "organization.selectUnitToFilterUsers",
                        "Select a unit to filter this organization user list."
                      )}
                    </p>
                  )}
                  <ScrollArea className="h-[250px] border border-gray-200 dark:border-gray-700 rounded-md p-2">
                    <div className="space-y-1">
                      {filteredEmployees.map((emp) => (
                        <button
                          key={`emp-${emp.id || emp.user.id}`}
                          onClick={() => setSelectedUser(emp.user.id)}
                          type="button"
                          className={cn(
                            "w-full flex items-center justify-between px-3 py-2 rounded-md text-left text-sm transition-colors",
                            selectedUser === emp.user.id
                              ? "bg-purple-200 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300"
                              : "hover:bg-purple-100 dark:hover:bg-purple-900/30 text-gray-700 dark:text-gray-300"
                          )}
                        >
                          <div className="flex-1">
                            <p className="font-medium">{emp.user.name?.en || emp.user.email}</p>
                            <p className="text-xs text-gray-500 dark:text-gray-400">{emp.user.email}</p>
                          </div>
                          {selectedUser === emp.user.id && (
                            <Check className="h-4 w-4 ml-2" />
                          )}
                        </button>
                      ))}
                      {filteredEmployees.length === 0 && (
                        <p className="text-sm text-gray-500 dark:text-gray-400 text-center mt-2">
                          {t("organization.noUsersFound")}
                        </p>
                      )}
                    </div>
                  </ScrollArea>
                  {/* Pagination */}
                  <div className="flex items-center justify-between mt-2 px-2">
                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => setPage((prev) => Math.max(prev - 1, 0))}
                      disabled={page === 0}
                    >
                      {"<"}
                    </Button>

                    <span className="text-xs text-gray-500 dark:text-gray-400">
                      {t("common.page")} {page + 1}
                    </span>

                    <Button
                      type="button"
                      variant="outline"
                      size="sm"
                      onClick={() => {
                        const total = employeesResponseByOrg?.count ?? 0;
                        const maxPage = Math.ceil(total / take) - 1;
                        setPage((prev) => Math.min(prev + 1, maxPage));
                      }}
                      disabled={
                        !employeesResponseByOrg?.count ||
                        (page + 1) * take >= employeesResponseByOrg.count
                      }
                    >
                      {">"}
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>

          <DialogFooter>
            <div className="flex justify-end gap-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => {
                  resetForm();
                  onClose();
                }}
                disabled={isAssigning}
              >
                {t("common.Cancel")}
              </Button>
              <Button 
                type="submit" 
                disabled={
                  isAssigning ||
                  !organizationIdForAssignment ||
                  !unitIdForAssignment ||
                  !selectedUser
                }
                className="bg-green-600 hover:bg-green-700"
              >
                {isAssigning
                  ? t("organization.assigning")
                  : t("organization.assignUser")}
              </Button>
            </div>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
