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;
  defaultValues: CustomerData; // ✅ ya no recibe DTO
  isPending?: boolean;
  onSubmit: (data: CustomerData) => void;
  onError: (errors: FieldErrors<CustomerUpdateData>) => void;
  errorMessage?: string; // ✅ prop nueva para mostrar error global
}

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

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

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

  return (
    <Form {...form}>
      <FormDebug form={form} />
      <form id={formId} onSubmit={form.handleSubmit(onSubmit, oError)}>
        <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>
  );
};
