import i18n from "@/i18n";
import { isValidEthiopianPhone } from "@/record-management/common/editor/Utils";
import { Button } from "@/shared/common/ui/button";
import { Input } from "@/shared/common/ui/input";
import { Label } from "@/shared/common/ui/label";
import { useEmployeePositions } from "@/user-management/hooks/useEmployeePostions";
import { t } from "i18next";
import { useState } from "react";
import { toast } from "sonner";
import { useUnitConfiguration } from "@/shared/hooks/useUnitConfiguration";

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

export function AddUserUnderDepartmentForm({
  unitId,
  departmentId,
  departmentName,
  onSuccess,
  onCancel,
}: AddUserUnderDepartmentFormProps) {
  const { invite, isInviting } = useEmployeePositions();
  const { data: unitConfigData } = useUnitConfiguration(unitId, {
    enabled: !!unitId,
  });
  const isApprovalRequiredForPositionChange =
    unitConfigData?.data?.items?.[0]?.isApprovalRequiredForPositionChange ??
    false;
  const lang = i18n.language;
  const [formData, setFormData] = useState({
    positionId: departmentId,
    username: "",
    email: "",
    phoneNumber: "",
    name: {
      am: "",
      en: "",
    },
  });

  const [errors, setErrors] = useState({
    username: "",
    email: "",
    phoneNumber: "",
    nameAm: "",
    nameEn: "",
  });

  const handleChange = (field: string, value: string, lang?: "am" | "en") => {
    if (field === "name" && lang) {
      setFormData((prev) => ({
        ...prev,
        name: {
          ...prev.name,
          [lang]: value,
        },
      }));
      setErrors((prev) => ({
        ...prev,
        [`name${lang.toUpperCase()}`]: "",
      }));
    } else {
      setFormData((prev) => ({ ...prev, [field]: value }));
      setErrors((prev) => ({ ...prev, [field]: "" }));
    }
  };

  const validate = () => {
    const newErrors = {
      username: "",
      email: "",
      phoneNumber: "",
      nameAm: "",
      nameEn: "",
    };

    let valid = true;

    if (!formData.username.trim()) {
      newErrors.username =t("profile.usernameRequired");
      valid = false;
    }

    if (!formData.email.trim()) {
      newErrors.email = t("profile.emailRequired");
      valid = false;
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
      newErrors.email = t("profile.validEmailFormat");
      valid = false;
    }

    if (!formData.phoneNumber.trim()) {
      newErrors.phoneNumber = t("profile.phoneRequired");
      valid = false;
    } else if (!isValidEthiopianPhone(formData.phoneNumber)) {
      newErrors.phoneNumber =
        t("profile.validPhoneFormat");
      valid = false;
    }

    if (!formData.name.am.trim()) {
      newErrors.nameAm = t("profile.amharicNameRequired");
      valid = false;
    }

    if (!formData.name.en.trim()) {
      newErrors.nameEn = t("profile.englishNameRequired");
      valid = false;
    }

    setErrors(newErrors);
    return valid;
  };

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

    if (!validate()) return;

    invite({
      payload: formData,
      successCallback: () => {
        const displayName = lang === "en" ? formData.name.en : formData.name.am;
        if (isApprovalRequiredForPositionChange) {
          toast.success(
            t(
              "contentManagement.positionChangeApprovalRequiredSuccess",
              "Action completed successfully. Approval is required for position changes.",
            ),
            {
              description: t(
                "contentManagement.userInvitePendingApproval",
                `User "${displayName}" has been invited and is pending approval for this department.`,
              ),
            },
          );
        } else {
          toast.success("User invited", {
            description: `User "${displayName}" has been added to the department.`,
          });
        }
        onSuccess();
      },
    });
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <Label>{t("organization.Position")}</Label>
        <Input value={departmentName} disabled />
      </div>

      <div>
        <Label>{t("organization.username")} *</Label>
        <Input
          value={formData.username}
          onChange={(e) => handleChange("username", e.target.value)}
        />
        {errors.username && (
          <p className="text-red-500 text-sm">{errors.username}</p>
        )}
      </div>

      <div>
        <Label>{t("organization.email")} *</Label>
        <Input
          type="email"
          value={formData.email}
          onChange={(e) => handleChange("email", e.target.value)}
        />
        {errors.email && <p className="text-red-500 text-sm">{errors.email}</p>}
      </div>

      <div>
        <Label>{t("auth.phoneNumber")}</Label>
        <Input
          type="tel"
          placeholder="0912345678 or +251912345678"
          value={formData.phoneNumber}
          onChange={(e) => handleChange("phoneNumber", e.target.value)}
        />
        {errors.phoneNumber && (
          <p className="text-red-500 text-sm">{errors.phoneNumber}</p>
        )}
      </div>

      <div>
        <Label>{t("organization.enterAmharicName")}*</Label>
        <Input
          value={formData.name.am}
          onChange={(e) => handleChange("name", e.target.value, "am")}
        />
        {errors.nameAm && (
          <p className="text-red-500 text-sm">{errors.nameAm}</p>
        )}
      </div>

      <div>
        <Label>{t("organization.enterEnglishName")}*</Label>
        <Input
          value={formData.name.en}
          onChange={(e) => handleChange("name", e.target.value, "en")}
        />
        {errors.nameEn && (
          <p className="text-red-500 text-sm">{errors.nameEn}</p>
        )}
      </div>

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