import { useForm } from "react-hook-form";
import { useNavigate, useParams } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { GenericForm } from "@/performance-management/utils/generic-form";
import { FormField } from "@/performance-management/utils/shared-field-types";
import {
  usePlanYear,
  usePlanYearMutations,
  usePlanYears,
} from "@/performance-management/hooks/usePlanYear";
import { PlanYearFormValues } from "@/performance-management/types/planYearTypes";
import { useAuth } from "@/shared/context/AuthContext";
import { generateEthiopianYearOptions } from "@/performance-management/utils/EthiopianYear";
import { useMemo } from "react";

export default function PlanYearForm() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const isEdit = !!id;

  const { data: planYearData } = usePlanYear(id || "");
  const { create, update } = usePlanYearMutations();
  const { user } = useAuth();
  const organizationId =
    user?.employee?.length && user.employee.length > 0
      ? user.employee[0].organizationId
      : undefined;

  // Fetch all plan years to check which years are taken
  const { data: allPlanYears } = usePlanYears(organizationId || "");

  const yearOptions = useMemo(() => {
    const baseOptions = generateEthiopianYearOptions();

    // Get taken years (excluding current plan year if editing)
    const takenYears = new Set(
      allPlanYears?.data?.items
        ?.filter((planYear: { id: string | undefined }) => planYear.id !== id)
        .map((planYear: { year: any }) => planYear.year) || []
    );

    // Mark taken years as disabled
    return baseOptions.map((option) => ({
      ...option,
      disabled: takenYears.has(Number(option.value)),
    }));
  }, [allPlanYears, id]);

  const initialValues: PlanYearFormValues = {
    year: Number(yearOptions[0].value),
    nameAm: planYearData?.data?.name?.am || "",
    nameEn: planYearData?.data?.name?.en || "",
    descriptionAm: "",
    descriptionEn: "",
    organizationId: organizationId || "",
  };

  const form = useForm<PlanYearFormValues>({
    defaultValues: initialValues,
    values: initialValues,
  });

  const planYearFormFields: FormField<PlanYearFormValues>[] = [
    {
      name: "year",
      label: t("planYear.year", "Year"),
      type: "year-picker",
      placeholder: t("planYear.enterYear", "Enter year (e.g., 2025)"),
      required: true,
      defaultValue: Number(yearOptions[0].value),
      calendarType: "habesha",
      language: "am",
      minYear: !isEdit ? Number(yearOptions[0].value) : undefined,
      colSpan: 12,
    },
    {
      name: "nameAm",
      label: t("planYear.nameAmharic", "Name (Amharic)"),
      type: "text",
      placeholder: t("planYear.enterAmharicName", "Enter Amharic name"),
      required: true,
      colSpan: 6,
    },
    {
      name: "nameEn",
      label: t("planYear.nameEnglish", "Name (English)"),
      type: "text",
      placeholder: t("planYear.enterEnglishName", "Enter English name"),
      required: true,
      colSpan: 6,
    },
  ];

  const handleSubmit = (values: PlanYearFormValues) => {
    const dto = {
      id: isEdit ? id : undefined,
      year: Number(values.year),
      name: {
        am: values.nameAm,
        en: values.nameEn,
      },
      organizationId: organizationId,
    };

    const mutation = isEdit ? update : create;

    mutation.mutate(dto, {
      onSuccess: () => {
        navigate("/performance-management/plan-years");
      },
    });
  };

  const handleCancel = () => {
    navigate("/performance-management/plan-years");
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <GenericForm<PlanYearFormValues>
        form={form}
        fields={planYearFormFields}
        onSubmit={handleSubmit}
        onCancel={handleCancel}
        title={
          isEdit
            ? t("planYear.editPlanYear", "Edit Plan Year")
            : t("planYear.createPlanYear", "Create Plan Year")
        }
        description={
          isEdit
            ? t(
                "planYear.updatePlanYearInfo",
                "Update the plan year information"
              )
            : t(
                "planYear.createPlanYearInfo",
                "Create a new plan year to organize your plans"
              )
        }
        submitButtonText={
          isEdit
            ? t("planYear.updatePlanYear", "Update Plan Year")
            : t("planYear.createPlanYear", "Create Plan Year")
        }
        cancelButtonText={t("common.cancel", "Cancel")}
      />
    </div>
  );
}
