import { useState } from "react";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { usePositions } from "@/user-management/hooks/usePosition";
import { PositionPayload } from "@/user-management/services/api/positionService";
import { toast } from "sonner";
import { usePositionTypes } from "@/user-management/hooks/usePositionTypes";
import i18n from "@/i18n";
import { t } from "i18next";
import { useLocalizedName } from "@/shared/common/localizedName";

interface AddSubDepartmentFormProps {
  departmentId: string;
  unitId: string;
  organizationId: string;
  departmentName: string;
  onSuccess: (subDepartmentName: string) => void;
  onCancel: () => void;
}

export function AddSubDepartmentForm({
  departmentId,
  departmentName,
  organizationId,
  unitId,
  onSuccess,
  onCancel,
}: AddSubDepartmentFormProps) {
  const { createPosition, isCreating } = usePositions();
  const { commonPositionTypes, isLoading: isLoadingTypes } = usePositionTypes({
    unitId,
    params: {
      take: 1000, // Fetch all position types
      skip: 0,
      orderBy: "createdAt:Desc",
    },
  });

  const [nameEn, setNameEn] = useState("");
  const [nameAm, setNameAm] = useState("");
  const [key, setKey] = useState("");
  const [positionTypeId, setPositionTypeId] = useState("");
  const lang = i18n.language;
  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});

  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");
    if (!positionTypeId)
      newErrors.positionTypeId = t("contentManagement.selectPosType");
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

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

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

    createPosition({
      payload,
      successCallback: () => {
        onSuccess(nameEn.trim());
        toast.success(t("contentManagement.success"), {
          description: `${t("contentManagement.subDep")} "${
            lang === "en" ? nameEn : nameAm
          }${t("contentManagement.msg")}`,
        });
      },
    });
  };
const localizedName = useLocalizedName()
  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="parentDepartment">
          {t("contentManagement.parentDep")}
        </Label>
        <Input
          id="parentDepartment"
          value={departmentName}
          disabled
          className="bg-gray-50"
        />
      </div>

      <div className="space-y-2">
        <Label htmlFor="positionType">{t("organization.positionTypes")}</Label>
        <Select
          onValueChange={(value) => {
            setPositionTypeId(value);
            setErrors((prev) => ({ ...prev, positionTypeId: "" }));
          }}
          value={positionTypeId}
          disabled={isLoadingTypes}>
          <SelectTrigger>
            <SelectValue placeholder={t("contentManagement.selectPosType")} />
          </SelectTrigger>
          <SelectContent className="max-h-60 overflow-y-auto">
            {commonPositionTypes.map((type) => (
              <SelectItem key={type.id} value={type.id}>
                { localizedName(type.name)}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
        {errors.positionTypeId && (
          <p className="text-red-500 text-sm">{errors.positionTypeId}</p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="nameEn">{t("organization.enterEnglishName")}</Label>
        <Input
          id="nameEn"
          placeholder={t("organization.enterEnglishName")}
          value={nameEn}
          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}
          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={t("contentManagement.key")}
          value={key}
          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}>
          {isCreating
            ? t("organization.adding")
            : t("contentManagement.addSubdepartement")}
        </Button>
      </div>
    </form>
  );
}
