import { useEffect, 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 {
  getPositionById,
  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 { PositionDto } from "@/user-management/dto/positions/positionDto";
import i18n from "@/i18n";
import { t } from "i18next";
import { useLocalizedName } from "@/shared/common/localizedName";

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

export function EditDepartmentForm({
  departmentId,
  onSuccess,
  onCancel,
}: EditDepartmentFormProps) {
  const { updatePosition, isUpdating } = usePositions();

  const [nameEn, setNameEn] = useState("");
  const [nameAm, setNameAm] = useState("");
  const [key, setKey] = useState("");
  const [unitId, setUnitId] = useState("");
  const [organizationId, setOrganizationId] = useState("");
  const [positionTypeId, setPositionTypeId] = useState("");

  const { commonPositionTypes, isLoadingCommonTypes } = usePositionTypes({
    unitId,
    params: {
      take: 1000, // Fetch all position types
      skip: 0,
      orderBy: "createdAt:Desc",
    },
  });

  const [errors, setErrors] = useState<Partial<Record<string, string>>>({});
  const [isLoading, setIsLoading] = useState(true);
  const lang = i18n.language;
  const localizedName = useLocalizedName();

  useEffect(() => {
    const fetchDepartment = async () => {
      try {
        const data = await getPositionById(departmentId);
        const res = data.data as PositionDto;
        setNameEn(res.name.en);
        setNameAm(res.name.am);
        setKey(res.key);
        setUnitId(res.unitId);
        setOrganizationId(res.organizationId);
        setPositionTypeId(res.positionTypeId);
      } catch {
        toast.error("Failed to fetch department");
      } finally {
        setIsLoading(false);
      }
    };

    fetchDepartment();
  }, [departmentId]);

  // Reset position type selection when unit changes
  useEffect(() => {
    if (unitId && commonPositionTypes.length > 0) {
      // Find the current position type in the new list
      const currentType = commonPositionTypes.find(
        (type) => type.id === positionTypeId
      );
      if (!currentType) {
        // If current position type is not in the new list, reset selection
        setPositionTypeId("");
      }
    }
  }, [unitId, commonPositionTypes, positionTypeId]);

  const validateForm = () => {
    const newErrors: Record<string, string> = {};
    if (!nameEn.trim())
      newErrors.nameEn = t("organization.englishNameRequired");
    if (!nameAm.trim())
      newErrors.nameAm = t("organization.amharicNameRequired");
    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,
      organizationId,
      positionTypeId,
    };

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

  if (isLoading) {
    return (
      <div className="text-sm text-muted-foreground">
        {" "}
        {t("contentManagement.loading")}
      </div>
    );
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="positionType">{t("organization.positionTypes")}</Label>
        <Select
          onValueChange={(value) => {
            setPositionTypeId(value);
            setErrors((prev) => ({ ...prev, positionTypeId: "" }));
          }}
          value={positionTypeId}
          disabled={isLoadingCommonTypes}
        >
          <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="e.g. finance-department"
          value={key}
          disabled
        />
      </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>
  );
}
