import { useMemo, useState } from "react";
import { AlertCircle, Loader2 } from "lucide-react";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { useUnit } from "@/user-management/hooks/useUnit";
import { useGetOrganizationConfig } from "@/super-admin/hooks/useConfig";
import { useOrgUnitTotalCount } from "@/user-management/hooks/useOrgUnitTotalCount";
import { toast } from "sonner";
import i18n from "@/i18n";
import { t } from "i18next";

interface AddUnitFormProps {
  organizationId: string;
  onSuccess: (unitName: string) => void;
  onCancel: () => void;
}

export function AddUnitForm({
  organizationId,
  onSuccess,
  onCancel,
}: AddUnitFormProps) {
  const [nameEn, setNameEn] = useState("");
  const [nameAm, setNameAm] = useState("");
  const [key, setKey] = useState("");
  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});
  const lang = i18n.language;
  const { createUnit, isCreating } = useUnit();

  // --- 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 isCheckingCapacity = isLoadingConfig || isLoadingCurrentCount;
  const isAtCapacity =
    capacity !== null && capacity >= 0 && currentCount >= capacity;
  const isCapacityMissing = !isCheckingCapacity && capacity === null;
  const remainingSlots =
    capacity !== null ? Math.max(capacity - currentCount, 0) : null;
  const formLocked = isCheckingCapacity || isCapacityMissing || isAtCapacity;

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    if (!nameEn.trim())
      newErrors.nameEn = t("organization.englishNameRequired");
    if (!nameAm.trim())
      newErrors.nameAm = t("organization.amharicNameRequired");
    if (!key.trim()) newErrors.key = t("contentManagement.keyRequired");

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

    if (isCheckingCapacity) return;
    if (isCapacityMissing) {
      toast.error(
        t(
          "contentManagement.noCapacityConfigured",
          "No unit capacity configured for this organization. Ask the super admin to configure it in Manage Organization Configuration."
        )
      );
      return;
    }
    if (isAtCapacity) {
      toast.error(
        t(
          "contentManagement.capacityReached",
          "Capacity limit reached. Configured maximum is {{max}}.",
          { max: capacity ?? 0 }
        )
      );
      return;
    }
    if (!validateForm()) {
      toast.error(t("contentManagement.invalidMsg"));
      return;
    }

    const payload = {
      organizationId,
      key: key.trim().toLowerCase().replace(/\s+/g, "-"),
      name: {
        en: nameEn.trim(),
        am: nameAm.trim(),
      },
    };

    createUnit({
      payload,
      successCallback: () => {
        toast.success(t("contentManagement.success"), {
          description: `${t("contentManagement.unit")} "${
            lang === "en" ? nameEn : nameAm
          }" ${t("contentManagement.msg")}`,
        });
        onSuccess(nameEn.trim());
      },
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      {/* 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"
            : isCapacityMissing
            ? "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>
            ) : isCapacityMissing ? (
              <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", "Used")}: {currentCount}
                  </span>
                  <span>
                    {t("contentManagement.remainingSlots", "Remaining")}:{" "}
                    {remainingSlots ?? 0}
                  </span>
                </div>
                {isAtCapacity && (
                  <div className="text-xs font-medium">
                    {t(
                      "contentManagement.capacityReachedShort",
                      "Limit reached — cannot create more units."
                    )}
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>

      <div className="space-y-2">
        <Label htmlFor="nameEn">{t("organization.enterEnglishName")}</Label>
        <Input
          id="nameEn"
          placeholder={t("organization.enterEnglishName")}
          value={nameEn}
          disabled={formLocked}
          onChange={(e) => {
            setNameEn(e.target.value);
            setErrors((prev) => ({ ...prev, nameEn: "" }));
          }}
        />
        {errors.nameEn && (
          <p className="text-red-500 text-sm">{errors.nameEn}</p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="nameAm">{t("organization.enterAmharicName")}</Label>
        <Input
          id="nameAm"
          placeholder={t("organization.enterAmharicName")}
          value={nameAm}
          disabled={formLocked}
          onChange={(e) => {
            setNameAm(e.target.value);
            setErrors((prev) => ({ ...prev, nameAm: "" }));
          }}
        />
        {errors.nameAm && (
          <p className="text-red-500 text-sm">{errors.nameAm}</p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="key">{t("contentManagement.key")}</Label>
        <Input
          id="key"
          placeholder="e.g. finance-unit"
          value={key}
          disabled={formLocked}
          onChange={(e) => {
            setKey(e.target.value);
            setErrors((prev) => ({ ...prev, key: "" }));
          }}
        />
        {errors.key && <p className="text-red-500 text-sm">{errors.key}</p>}
      </div>

      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isCreating}
        >
          {t("common.Cancel")}
        </Button>
        <Button type="submit" disabled={isCreating || formLocked}>
          {isCreating
            ? t("organization.adding")
            : t("contentManagement.addUnit")}
        </Button>
      </div>
    </form>
  );
}
