import { useEffect, useMemo, useState } from "react";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import { Input } from "@/shared/common/ui/input";
import { Switch } from "@/shared/common/ui/switch";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Search } from "lucide-react";
import { useEmployees } from "@/user-management/hooks/useEmployees";
import { useEmployeePositions } from "@/user-management/hooks/useEmployeePostions";
import { useOrganizations } from "@/super-admin/hooks/useOrganizations";
import { useUnit } from "@/user-management/hooks/useUnit";
import { toast } from "sonner";
import { AssignEmployeePayload } from "@/user-management/services/api/employeePositionsService";
import { t } from "i18next";
import i18n from "@/i18n";
import { useErrorHandler } from "@/shared/hooks/useErrorHandler";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";

interface AssignUserFormProps {
  unitId: string;
  positionId: string;
  positionName: string;
  onSuccess: () => void;
  onCancel: () => void;
}

export function AssignUserForm({
  unitId,
  positionId,
  positionName,
  onSuccess,
  onCancel,
}: AssignUserFormProps) {
  const { assignEmployee, isAssigning } = useEmployeePositions();
  const { handleError } = useErrorHandler(t);
  const localizedName = useLocalizedName();

  const [isAdvanced, setIsAdvanced] = useState(false);
  const [selectedOrg, setSelectedOrg] = useState<string>("");
  const [selectedUnit, setSelectedUnit] = useState<string>("");
  const [selectedUser, setSelectedUser] = useState<string>("");
  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});
  const [page, setPage] = useState(1);
  const [searchQuery, setSearchQuery] = useState("");
  const pageSize = 20;
  const activeUnitId = isAdvanced ? selectedUnit : unitId;
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const isApprovalRequiredForPositionChange =
    unitConfigData?.data?.items?.[0]?.isApprovalRequiredForPositionChange ??
    false;

  const { organizationsResponse, isLoading: isLoadingOrgs } = useOrganizations(
    "Org",
    {
      take: 300,
    },
  );
  const { data: unitsResponse, isLoading: isLoadingUnits } = useUnit().getList(
    selectedOrg,
    { take: 300, skip: 0 },
  );
  const { employeesResponse, isLoading } = useEmployees({
    unitId: activeUnitId,
  });

  const allUsers = employeesResponse?.items || [];
  const lang = i18n.language;

  useEffect(() => {
    setSelectedUser("");
    setSearchQuery("");
    setPage(1);
    setErrors({});
  }, [activeUnitId]);

  useEffect(() => {
    setSelectedUnit("");
  }, [selectedOrg]);

  useEffect(() => {
    if (!isAdvanced) {
      setSelectedOrg("");
      setSelectedUnit("");
    }
  }, [isAdvanced]);

  // Filter users based on search query
  const filteredUsers = useMemo(() => {
    if (!searchQuery.trim()) return allUsers;

    return allUsers.filter((emp) => {
      const name = lang === "en" ? emp.name?.en : emp.name?.am;
      const email = emp.email || "";

      return (
        name?.toLowerCase().includes(searchQuery.toLowerCase()) ||
        email.toLowerCase().includes(searchQuery.toLowerCase())
      );
    });
  }, [allUsers, searchQuery, lang]);

  const handleScroll = (e: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = e.currentTarget;
    if (scrollTop + clientHeight >= scrollHeight - 5) {
      if (page * pageSize < filteredUsers.length) {
        setPage((prev) => prev + 1);
      }
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (isAdvanced && (!selectedOrg || !selectedUnit)) {
      toast.error(t("contentManagement.requiredFields"));
      return;
    }

    if (!selectedUser) {
      setErrors({ selectedUser: t("contentManagement.userRequired") });
      toast.error(t("contentManagement.userRequiredMsg"));
      return;
    }

    const user = selectedUser;
    if (!user) {
      toast.error(t("contentManagement.userError"));
      return;
    }

    const payload: AssignEmployeePayload = {
      positionId,
      employeeId: user,
    };

    try {
      await assignEmployee(payload);
      toast.success(
        isApprovalRequiredForPositionChange
          ? t(
              "contentManagement.positionChangeApprovalRequiredSuccess",
              "User assigned successfully. Approval is required for position changes.",
            )
          : t("contentManagement.userSuccess"),
      );
      onSuccess();
    } catch (error) {
      handleError(error);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="flex items-center justify-between rounded-md border px-3 py-2">
        <div className="space-y-0.5">
          <Label htmlFor="advanced-assign">
            {t("organization.advancedAssign", "Advanced")}
          </Label>
          <p className="text-xs text-muted-foreground">
            {t(
              "organization.selectOrganizationAndUnit",
              "Select organization and unit before choosing a user",
            )}
          </p>
        </div>
        <Switch
          id="advanced-assign"
          checked={isAdvanced}
          onCheckedChange={setIsAdvanced}
          disabled={isAssigning}
        />
      </div>

      {isAdvanced && (
        <div className="space-y-4 border rounded-lg p-4 bg-muted/50">
          <div className="space-y-2">
            <Label htmlFor="organization">
              {t("organization.organizations")}
            </Label>
            <Select
              value={selectedOrg}
              onValueChange={(value) => setSelectedOrg(value)}
              disabled={isLoadingOrgs}
            >
              <SelectTrigger id="organization" className="w-full">
                <SelectValue
                  placeholder={t("organization.selectOrganization")}
                />
              </SelectTrigger>
              <SelectContent
                side="bottom"
                sideOffset={4}
                className="w-[var(--radix-select-trigger-width)]"
              >
                {organizationsResponse?.items?.map((org) => (
                  <SelectItem key={org.id} value={org.id}>
                    <span className="truncate">{localizedName(org.name)}</span>
                  </SelectItem>
                ))}
                {!isLoadingOrgs &&
                  organizationsResponse?.items?.length === 0 && (
                    <SelectItem value="no-organizations" disabled>
                      {t(
                        "organization.noOrganizationsFound",
                        "No organizations found",
                      )}
                    </SelectItem>
                  )}
              </SelectContent>
            </Select>
          </div>

          <div className="space-y-2">
            <Label htmlFor="unit">{t("organization.units")}</Label>
            <Select
              value={selectedUnit}
              onValueChange={(value) => setSelectedUnit(value)}
              disabled={!selectedOrg || isLoadingUnits}
            >
              <SelectTrigger id="unit" className="w-full">
                <SelectValue
                  placeholder={
                    selectedOrg
                      ? t("organization.selectUnit")
                      : t("organization.selectOrganizationFirst")
                  }
                />
              </SelectTrigger>
              <SelectContent
                side="bottom"
                sideOffset={4}
                className="w-[var(--radix-select-trigger-width)]"
              >
                {unitsResponse?.data?.items
                  ?.filter((unit: any) => unit.id !== unitId)
                  ?.map((unit: any) => (
                    <SelectItem key={unit.id} value={unit.id}>
                      <span className="truncate">
                        {localizedName(unit.name)}
                      </span>
                    </SelectItem>
                  ))}
                {!isLoadingUnits &&
                  unitsResponse?.data?.items?.filter(
                    (unit: any) => unit.id !== unitId,
                  )?.length === 0 && (
                    <SelectItem value="no-units" disabled>
                      {t("organization.noUnitsFound")}
                    </SelectItem>
                  )}
              </SelectContent>
            </Select>
          </div>
        </div>
      )}

      {/* User Select with Integrated Search */}
      <div className="space-y-2">
        <Label htmlFor="user">{t("contentManagement.selectUser")}</Label>
        <Select
          value={selectedUser}
          onValueChange={(value) => {
            setSelectedUser(value);
            setErrors((prev) => ({ ...prev, selectedUser: "" }));
          }}
          disabled={isLoading || (isAdvanced && !selectedUnit)}
        >
          <SelectTrigger id="user">
            <SelectValue placeholder={t("contentManagement.selectUser")} />
          </SelectTrigger>
          <SelectContent
            style={{ maxHeight: "300px", overflowY: "auto" }}
            onScroll={handleScroll}
          >
            {/* Search Input inside Dropdown */}
            <div className="sticky top-0 z-10 bg-background p-2 border-b">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <Input
                  type="text"
                  placeholder={t("organization.searchUsers")}
                  value={searchQuery}
                  onChange={(e) => {
                    e.stopPropagation();
                    setSearchQuery(e.target.value);
                    setPage(1); // Reset to first page when searching
                  }}
                  onClick={(e) => e.stopPropagation()}
                  className="pl-10 h-9 text-sm"
                />
              </div>
            </div>

            {/* User List */}
            {filteredUsers.length > 0 ? (
              filteredUsers.slice(0, page * pageSize).map((emp) => (
                <SelectItem key={emp.id} value={emp?.id}>
                  <div className="flex flex-col">
                    <span>
                      {lang === "en"
                        ? emp.name?.en
                        : emp.name?.am || emp.email || "Unnamed User"}
                    </span>
                    {emp.email && (
                      <span className="text-xs text-gray-500">{emp.email}</span>
                    )}
                  </div>
                </SelectItem>
              ))
            ) : (
              <div className="text-center py-4 text-sm text-muted-foreground">
                {searchQuery
                  ? t("organization.noUsersFound")
                  : t("organization.noUsersAvailable")}
              </div>
            )}
            {isLoading && (
              <div className="text-center py-2 text-sm text-muted-foreground">
                {t("contentManagement.loading")}
              </div>
            )}
          </SelectContent>
        </Select>
        {errors.selectedUser && (
          <p className="text-red-500 text-sm">{errors.selectedUser}</p>
        )}
      </div>

      {/* Position Name */}
      <div className="space-y-2">
        <Label>{t("organization.Position")}</Label>
        <div className="px-3 py-2 border rounded text-sm text-muted-foreground bg-muted">
          {positionName || "Unknown"}
        </div>
      </div>

      {/* Buttons */}
      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isAssigning}
        >
          {t("common.Cancel")}
        </Button>
        <Button type="submit" disabled={isAssigning || isLoading}>
          {isAssigning ? "Assigning..." : "Assign User"}
        </Button>
      </div>
    </form>
  );
}
