import { useEffect, useMemo, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { Button } from "@/shared/common/ui/button";
import { Label } from "@/shared/common/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { toast } from "sonner";
import { AlertCircle, Loader2 } from "lucide-react";
import { t } from "i18next";
import { useUnit } from "@/user-management/hooks/useUnit";
import { getOrganizations } from "@/shared/services/organizationsService";
import {
  getUnitList,
  RelateUnitToUnitPayload,
} from "@/user-management/services/api/unitService";
import { useLocalizedName } from "@/shared/common/localizedName";
import { useAuth } from "@/shared/context/AuthContext";
import { useGetOrganizationConfig } from "@/super-admin/hooks/useConfig";
import { useOrgUnitTotalCount } from "@/user-management/hooks/useOrgUnitTotalCount";
import { Name } from "../types";

interface SubCityOrg {
  id: string;
  name: Name;
}

interface SubCityUnit {
  id: string;
  name: Name;
}

interface AddFromSubCityFormProps {
  parentUnitId: string;
  onSuccess: () => void;
  onCancel: () => void;
}

export function AddFromSubCityForm({
  parentUnitId,
  onSuccess,
  onCancel,
}: AddFromSubCityFormProps) {
  const localizedName = useLocalizedName();
  const { user } = useAuth();
  const organizationId =
    user?.employee && user.employee.length > 0
      ? user.employee[0].organizationId
      : "";

  const [selectedSubCityId, setSelectedSubCityId] = useState("");
  const [selectedUnitId, setSelectedUnitId] = useState("");
  const [error, setError] = useState("");

  const { relateUnit, isRelating } = useUnit();

  const { data: subCitiesResp, isLoading: isLoadingSubCities } = useQuery({
    queryKey: ["organizationsFilter", "subcity"],
    queryFn: () =>
      getOrganizations({
        organizationTypeKey: "subcity",
        take: 1000,
        skip: 0,
      }),
    staleTime: 60_000,
  });

  const subCities: SubCityOrg[] = useMemo(() => {
    const items = subCitiesResp?.data?.items ?? subCitiesResp?.data ?? [];
    return Array.isArray(items) ? items : [];
  }, [subCitiesResp]);

  const { data: unitsResp, isLoading: isLoadingUnits } = useQuery({
    queryKey: ["unitList", selectedSubCityId],
    queryFn: () => getUnitList(selectedSubCityId, { take: 1000, skip: 0 }),
    enabled: !!selectedSubCityId,
    staleTime: 0,
  });

  const subCityUnits: SubCityUnit[] = useMemo(() => {
    const items = unitsResp?.data?.items ?? [];
    return Array.isArray(items) ? items : [];
  }, [unitsResp]);

  // --- Capacity check (Manage Organization Configuration) ---
  const { data: orgConfigResp, isLoading: isLoadingConfig } =
    useGetOrganizationConfig(organizationId);

  const capacity = useMemo<number | null>(() => {
    const items = orgConfigResp?.data?.items ?? [];
    if (!Array.isArray(items) || items.length === 0) return null;
    const match =
      items.find((it: any) => it?.organizationId === organizationId) ??
      items[0];
    const value = Number(match?.maximumNumberOfUnits);
    return Number.isFinite(value) ? value : null;
  }, [orgConfigResp, organizationId]);

  const { total: currentCount, isLoading: isLoadingCurrentCount } =
    useOrgUnitTotalCount(organizationId);

  const isAtCapacity =
    capacity !== null && capacity >= 0 && currentCount >= capacity;
  const remainingSlots =
    capacity !== null ? Math.max(capacity - currentCount, 0) : null;

  useEffect(() => {
    setSelectedUnitId("");
  }, [selectedSubCityId]);

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

    if (!selectedSubCityId) {
      setError(
        t("contentManagement.subCityRequired", "Please select a sub city")
      );
      return;
    }
    if (!selectedUnitId) {
      setError(t("contentManagement.unitRequired", "Please select a unit"));
      return;
    }
    if (!parentUnitId) {
      setError(
        t("contentManagement.parentUnitMissing", "Parent unit is missing")
      );
      return;
    }
    if (capacity === null) {
      setError(
        t(
          "contentManagement.noCapacityConfigured",
          "No unit capacity configured for this organization. Ask the super admin to configure it in Manage Organization Configuration."
        )
      );
      return;
    }
    if (isAtCapacity) {
      setError(
        t(
          "contentManagement.capacityReached",
          "Capacity limit reached. Configured maximum is {{max}}.",
          { max: capacity ?? 0 }
        )
      );
      return;
    }

    const payload: RelateUnitToUnitPayload = {
      unitId: selectedUnitId,
      newParentUnitId: parentUnitId,
    };

    try {
      await relateUnit({
        payload,
        successCallback: () => {
          toast.success(
            t(
              "contentManagement.unitRelatedSuccess",
              "Unit related successfully"
            )
          );
          onSuccess();
        },
      });
    } catch {
      // error handled by useUnit hook
    }
  };

  const isCheckingCapacity = isLoadingConfig || isLoadingCurrentCount;
  const isCapacityMissing = !isCheckingCapacity && capacity === null;
  const formLocked = isCheckingCapacity || isCapacityMissing || isAtCapacity;
  const submitDisabled =
    !selectedSubCityId ||
    !selectedUnitId ||
    isRelating ||
    formLocked;

  return (
    <form
      onSubmit={handleSubmit}
      className="flex flex-col gap-4 w-full min-w-0"
    >
      {/* Capacity status (configured by super admin) */}
      <div
        className={`rounded-md border px-3 py-2 text-sm ${
          isCheckingCapacity
            ? "border-gray-200 bg-gray-50 text-gray-600 dark:border-gray-700 dark:bg-gray-800/50 dark:text-gray-300"
            : capacity === null
            ? "border-amber-200 bg-amber-50 text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300"
            : isAtCapacity
            ? "border-red-200 bg-red-50 text-red-700 dark:border-red-900/50 dark:bg-red-950/30 dark:text-red-300"
            : "border-primary-200 bg-primary-50 text-primary-700 dark:border-primary-900/50 dark:bg-primary-950/30 dark:text-primary-300"
        }`}
      >
        <div className="flex items-start gap-2">
          {isCheckingCapacity ? (
            <Loader2 className="h-4 w-4 mt-0.5 shrink-0 animate-spin" />
          ) : (
            <AlertCircle className="h-4 w-4 mt-0.5 shrink-0" />
          )}
          <div className="min-w-0 break-words flex-1">
            {isCheckingCapacity ? (
              <span>
                {t(
                  "contentManagement.checkingCapacity",
                  "Checking configured capacity…"
                )}
              </span>
            ) : capacity === null ? (
              <span>
                {t(
                  "contentManagement.noCapacityConfigured",
                  "No unit capacity configured for this organization. Ask the super admin to configure it in Manage Organization Configuration."
                )}
              </span>
            ) : (
              <div className="space-y-1">
                <div className="font-medium">
                  {t(
                    "contentManagement.configuredUnitLimit",
                    "Configured unit limit: {{max}}",
                    { max: capacity }
                  )}
                </div>
                <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs opacity-90">
                  <span>
                    {t("contentManagement.linkedUnits", "Linked")}: {currentCount}
                  </span>
                  <span>
                    {t("contentManagement.remainingSlots", "Remaining")}:{" "}
                    {remainingSlots ?? 0}
                  </span>
                </div>
                {isAtCapacity && (
                  <div className="text-xs font-medium">
                    {t(
                      "contentManagement.capacityReachedShort",
                      "Limit reached — cannot relate more units."
                    )}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="flex flex-col gap-2 min-w-0">
        <Label htmlFor="subCity" className="text-sm">
          {t("contentManagement.selectSubCity", "Select Sub City")}
        </Label>
        <Select
          value={selectedSubCityId}
          onValueChange={(value) => {
            setSelectedSubCityId(value);
            setError("");
          }}
          disabled={isLoadingSubCities || formLocked}
        >
          <SelectTrigger id="subCity" className="w-full max-w-full">
            <SelectValue
              placeholder={
                isLoadingSubCities
                  ? t("organization.loading")
                  : t("contentManagement.selectSubCity", "Select Sub City")
              }
            />
          </SelectTrigger>
          <SelectContent className="max-w-[var(--radix-select-trigger-width)]">
            {isLoadingSubCities ? (
              <div className="flex items-center justify-center px-2 py-3 text-sm text-gray-500">
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
                {t("organization.loading")}
              </div>
            ) : subCities.length === 0 ? (
              <div className="px-2 py-3 text-sm text-gray-500">
                {t("contentManagement.noSubCities", "No sub cities found")}
              </div>
            ) : (
              subCities.map((sc) => (
                <SelectItem key={sc.id} value={sc.id}>
                  <span className="block truncate">
                    {localizedName(sc.name)}
                  </span>
                </SelectItem>
              ))
            )}
          </SelectContent>
        </Select>
      </div>

      <div className="flex flex-col gap-2 min-w-0">
        <Label htmlFor="subCityUnit" className="text-sm">
          {t("contentManagement.selectUnit", "Select Unit")}
        </Label>
        <Select
          value={selectedUnitId}
          onValueChange={(value) => {
            setSelectedUnitId(value);
            setError("");
          }}
          disabled={!selectedSubCityId || isLoadingUnits || formLocked}
        >
          <SelectTrigger id="subCityUnit" className="w-full max-w-full">
            <SelectValue
              placeholder={
                !selectedSubCityId
                  ? t(
                      "contentManagement.selectSubCityFirst",
                      "Select a sub city first"
                    )
                  : isLoadingUnits
                  ? t("organization.loading")
                  : t("contentManagement.selectUnit", "Select Unit")
              }
            />
          </SelectTrigger>
          <SelectContent className="max-w-[var(--radix-select-trigger-width)]">
            {isLoadingUnits ? (
              <div className="flex items-center justify-center px-2 py-3 text-sm text-gray-500">
                <Loader2 className="w-4 h-4 animate-spin mr-2" />
                {t("organization.loading")}
              </div>
            ) : subCityUnits.length === 0 ? (
              <div className="px-2 py-3 text-sm text-gray-500">
                {t("contentManagement.noUnit")}
              </div>
            ) : (
              subCityUnits.map((u) => (
                <SelectItem key={u.id} value={u.id}>
                  <span className="block truncate">{localizedName(u.name)}</span>
                </SelectItem>
              ))
            )}
          </SelectContent>
        </Select>
      </div>

      {error && (
        <p className="text-red-500 text-sm break-words">{error}</p>
      )}

      <div className="flex justify-end gap-2 pt-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isRelating}
        >
          {t("common.Cancel")}
        </Button>
        <Button type="submit" disabled={submitDisabled}>
          {isRelating ? (
            <span className="flex items-center gap-2">
              <Loader2 className="h-4 w-4 animate-spin" />
              {t("organization.adding")}
            </span>
          ) : (
            t("contentManagement.addFromSubCity", "Add From Sub City")
          )}
        </Button>
      </div>
    </form>
  );
}
