import { useState } from "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 { toast } from "sonner";
import { UnitDto } from "@/user-management/dto/unit/unitDto";
import { t } from "i18next";
import i18n from "@/i18n";

interface EditUnitFormProps {
  unit: UnitDto;
  onSuccess: (unitName: string) => void;
  onCancel: () => void;
}

export function EditUnitForm({ unit, onSuccess, onCancel }: EditUnitFormProps) {
  const [nameEn, setNameEn] = useState(unit.name.en);
  const [nameAm, setNameAm] = useState(unit.name.am);
  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});
  const lang = i18n.language;
  const { updateUnit, isUpdating } = useUnit();

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    if (!nameEn.trim())
      newErrors.nameEn = t("organization.englishNameRequired");
    if (!nameAm.trim())
      newErrors.nameAm = t("organization.amharicNameRequired");
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const { id, key, organizationId, parentUnitId } = unit;

    if (!validateForm()) {
      toast.error(t("contentManagement.invalidMsg"));
      return;
    }

    // PUT /api/units/{id} expects { name, key, organizationId, parentUnitId }.
    const payload = {
      name: {
        en: nameEn.trim(),
        am: nameAm.trim(),
      },
      key: key.trim().toLowerCase().replace(/\s+/g, "-"),
      organizationId,
      parentUnitId: parentUnitId ?? undefined,
    };

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

  return (
    <form onSubmit={handleSubmit} className="min-w-0 max-w-full space-y-4 overflow-hidden">
      <div className="min-w-0 max-w-full space-y-2">
        <Label htmlFor="nameEn">{t("organization.enterEnglishName")}</Label>
        <Input
          id="nameEn"
          placeholder={t("organization.enterEnglishName")}
          value={nameEn}
          className="max-w-full"
          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="min-w-0 max-w-full space-y-2">
        <Label htmlFor="nameAm">{t("organization.enterEnglishName")}</Label>
        <Input
          id="nameAm"
          placeholder={t("organization.enterEnglishName")}
          value={nameAm}
          className="max-w-full"
          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="min-w-0 max-w-full space-y-2">
        <Label htmlFor="key">{t("contentManagement.key")}</Label>
        <Input id="key" value={unit.key} className="max-w-full" />
      </div>

      <div className="flex justify-end gap-2">
        <Button
          type="button"
          variant="outline"
          onClick={onCancel}
          disabled={isUpdating}
        >
          {t("common.Cancel")}
        </Button>
        <Button type="submit" disabled={isUpdating}>
          {isUpdating ? t("profile.updating") : t("delegation.update")}
        </Button>
      </div>
    </form>
  );
}
