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 { 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 {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/shared/common/ui/select";
import { t } from "i18next";
import i18n from "@/i18n";

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

export function AddDepartmentForm({
  unitId,
  organizationId,
  onSuccess,
  onCancel,
}: AddDepartmentFormProps) {
  const { createPosition, isCreating } = usePositions();
  const { commonPositionTypes, isLoading: isLoadingTypes } = usePositionTypes({
    unitId,
  });
  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");

    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,
      organizationId,
      ...(positionTypeId ? { positionTypeId } : {}),
    };

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

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="positionType">
          {t("organization.positionTypes")} ({t("common.optional")})
        </Label>
        <Select
          onValueChange={setPositionTypeId}
          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}>
                {lang === "en" ? type.name.en : type.name.am}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>
      </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="e.g. finance-department"
          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.addDepartment")}
        </Button>
      </div>
    </form>
  );
}
