import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useTranslation } from "react-i18next";
import { useAuth } from "@/shared/context/AuthContext";
import { GenericForm } from "@/performance-management/utils/generic-form";
import { FormField } from "@/performance-management/utils/shared-field-types";
import { useServiceCategoryMutations } from "@/performance-management/hooks/useServiceCategory";
import {
  CreateServiceCategoryRequest,
  ServiceCategory,
} from "@/performance-management/services/api/serviceCategoryService";
import { useNavigate } from "react-router-dom";
import { useEffect } from "react";

// Validation schema factory
const createServiceCategorySchema = (t: (key: string) => string) =>
  z.object({
    slug: z.string().optional(),
    nameEn: z
      .string()
      .min(1, t("serviceCategory.validation.nameEnRequired"))
      .max(100, t("serviceCategory.validation.nameMaxLength")),
    nameAm: z
      .string()
      .min(1, t("serviceCategory.validation.nameAmRequired"))
      .max(100, t("serviceCategory.validation.nameMaxLength")),
    descriptionEn: z
      .string()
      .min(1, t("serviceCategory.validation.descriptionEnRequired"))
      .max(500, t("serviceCategory.validation.descriptionMaxLength")),
    descriptionAm: z
      .string()
      .min(1, t("serviceCategory.validation.descriptionAmRequired"))
      .max(500, t("serviceCategory.validation.descriptionMaxLength")),
  });

interface ServiceCategoryFormValues {
  slug?: string;
  nameEn: string;
  nameAm: string;
  descriptionEn: string;
  descriptionAm: string;
}

interface ServiceCategoryFormProps {
  category?: ServiceCategory;
  onSuccess?: () => void;
  onCancel?: () => void;
}

export const ServiceCategoryForm = ({
  category,
  onSuccess,
  onCancel,
}: ServiceCategoryFormProps) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { user } = useAuth();
  const { create, update } = useServiceCategoryMutations();

  const organizationId = user?.employee?.[0]?.organizationId;
  const isEditing = !!category;

  const form = useForm<ServiceCategoryFormValues>({
    resolver: zodResolver(createServiceCategorySchema(t)),
    defaultValues: {
      slug: category?.slug || "",
      nameEn: category?.name?.en || "",
      nameAm: category?.name?.am || "",
      descriptionEn: category?.description?.en || "",
      descriptionAm: category?.description?.am || "",
    },
  });

  // Reset form when category changes
  useEffect(() => {
    if (category) {
      form.reset({
        slug: category.slug,
        nameEn: category.name?.en || "",
        nameAm: category.name?.am || "",
        descriptionEn: category.description?.en || "",
        descriptionAm: category.description?.am || "",
      });
    }
  }, [category, form]);

  const serviceCategoryFormFields: FormField<ServiceCategoryFormValues>[] = [
    {
      name: "slug",
      label: t("serviceCategory.slug"),
      type: "text",
      placeholder: t("serviceCategory.slugPlaceholder"),
      description: t("serviceCategory.slugDescription"),
      required: false,
    },
    {
      name: "nameEn",
      label: t("serviceCategory.nameEn"),
      type: "text",
      placeholder: t("serviceCategory.nameEnPlaceholder"),
      required: true,
    },
    {
      name: "nameAm",
      label: t("serviceCategory.nameAm"),
      type: "text",
      placeholder: t("serviceCategory.nameAmPlaceholder"),
      required: true,
    },
    {
      name: "descriptionEn",
      label: t("serviceCategory.descriptionEn"),
      type: "textarea",
      placeholder: t("serviceCategory.descriptionEnPlaceholder"),
      required: true,
      rows: 4,
    },
    {
      name: "descriptionAm",
      label: t("serviceCategory.descriptionAm"),
      type: "textarea",
      placeholder: t("serviceCategory.descriptionAmPlaceholder"),
      required: true,
      rows: 4,
    },
  ];

  const handleSubmit = async (values: ServiceCategoryFormValues) => {
    if (!organizationId) {
      throw new Error(t("serviceCategory.organizationRequired"));
    }

    const requestData: CreateServiceCategoryRequest = {
      slug: values.slug || "",
      name: {
        en: values.nameEn,
        am: values.nameAm,
      },
      description: {
        en: values.descriptionEn,
        am: values.descriptionAm,
      },
      organizationId,
    };

    if (isEditing && category) {
      await update.mutateAsync({ id: category.id, data: requestData });
    } else {
      await create.mutateAsync(requestData);
    }

    onSuccess?.();
  };

  const handleCancel = () => {
    if (onCancel) {
      onCancel();
    } else {
      navigate(-1);
    }
  };

  return (
    <GenericForm<ServiceCategoryFormValues>
      form={form}
      fields={serviceCategoryFormFields}
      onSubmit={handleSubmit}
      onCancel={handleCancel}
      isSubmitting={create.isPending || update.isPending}
      submitButtonText={
        isEditing
          ? t("serviceCategory.updateCategory")
          : t("serviceCategory.createCategory")
      }
      cancelButtonText={t("common.cancel")}
      successMessage={
        isEditing
          ? t("serviceCategory.updateSuccess")
          : t("serviceCategory.createSuccess")
      }
      errorMessage={
        isEditing
          ? t("serviceCategory.updateError")
          : t("serviceCategory.createError")
      }
      title={
        isEditing
          ? t("serviceCategory.editTitle")
          : t("serviceCategory.createTitle")
      }
    />
  );
};
