import { zodResolver } from "@hookform/resolvers/zod";
import { FieldErrors, useForm } from "react-hook-form";

import { Form } from "@repo/shadcn-ui/components";

import { useUnsavedChangesNotifier } from "@erp/core/hooks";
import { FormDebug } from "../../components/form-debug";
import { useTranslation } from "../../i18n";
import { CustomerData, CustomerUpdateData, CustomerUpdateSchema } from "../../schemas";
import { CustomerAdditionalConfigFields } from "./customer-additional-config-fields";
import { CustomerAddressFields } from "./customer-address-fields";
import { CustomerBasicInfoFields } from "./customer-basic-info-fields";
import { CustomerContactFields } from "./customer-contact-fields";

interface CustomerFormProps {
  formId: string;
  data?: CustomerData;
  isPending?: boolean;
  /**
   * Callback function to handle form submission.
   * @param data - The customer data submitted by the form.
   */
  onSubmit?: (data: CustomerUpdateData) => void;
}

export const CustomerEditForm = ({ formId, data, onSubmit, isPending }: CustomerFormProps) => {
  const { t } = useTranslation();

  const form = useForm<CustomerUpdateData>({
    resolver: zodResolver(CustomerUpdateSchema),
    defaultValues: data,
    disabled: isPending,
  });

  useUnsavedChangesNotifier({
    isDirty: form.formState.isDirty,
  });

  const handleSubmit = (data: CustomerUpdateData) => {
    console.log("Datos del formulario:", data);
    onSubmit?.(data);
  };

  const handleError = (errors: FieldErrors<CustomerUpdateData>) => {
    console.error("Errores en el formulario:", errors);
    // Aquí puedes manejar los errores, por ejemplo, mostrar un mensaje al usuario
  };

  const handleCancel = () => {
    form.reset(data);
  };

  return (
    <Form {...form}>
      <FormDebug form={form} />
      <form id={formId} onSubmit={form.handleSubmit(handleSubmit, handleError)}>
        <div className='w-full grid grid-cols-1 space-y-8 space-x-8 xl:grid-cols-2'>
          <CustomerBasicInfoFields control={form.control} />
          <CustomerAddressFields control={form.control} />
          <CustomerContactFields control={form.control} />
          <CustomerAdditionalConfigFields control={form.control} />
        </div>
      </form>
    </Form>
  );
};
