import {
  Card,
  CardContent,
  CardDescription,
  CardFooter,
  CardHeader,
  CardTitle,
} from "@repo/shadcn-ui/components";

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 {
  defaultValues: CustomerData; // ✅ ya no recibe DTO
  isPending?: boolean;
  onSubmit: (data: CustomerUpdateData) => void;
  onError: (errors: FieldErrors<CustomerUpdateData>) => void;
}

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

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

  const {
    watch,
    formState: { isDirty, dirtyFields },
  } = form;

  useUnsavedChangesNotifier({
    isDirty,
  });

  const currentValues = watch();

  const handleSubmit = (data: CustomerUpdateData) => {
    console.log("Datos del formulario:", data);
    const changedData: Record<string, string> = {};

    Object.keys(dirtyFields).forEach((field) => {
      const value = String(currentValues[field as keyof CustomerUpdateData]);
      changedData[field] = value;
    });

    console.log(changedData);

    onSubmit(changedData);
  };

  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(defaultValues);
  };

  return (
    <Form {...form}>
      <FormDebug form={form} />
      <form onSubmit={form.handleSubmit(handleSubmit, handleError)}>
        <div className='flex gap-6'>
          <div className='w-full xl:w-2/3 space-y-12'>
            <CustomerBasicInfoFields control={form.control} />
            <CustomerContactFields control={form.control} />
            <CustomerAddressFields control={form.control} />
            <CustomerAdditionalConfigFields control={form.control} />
          </div>
        </div>
      </form>
    </Form>
  );

  return (
    <Form {...form}>
      <FormDebug form={form} />
      <form id={formId} onSubmit={form.handleSubmit(handleSubmit, handleError)}>
        <div className='grid grid-cols-3 gap-12'>
          <div className='col-span-2'>
            <Card className='border-0 shadow-none bg-background'>
              <CardHeader className='px-0'>
                <CardTitle>{t("form_groups.basic_info.title")}</CardTitle>
                <CardDescription>{t("form_groups.basic_info.description")}</CardDescription>
              </CardHeader>
              <CardContent className='px-0'>
                <CustomerBasicInfoFields />
              </CardContent>
              <CardFooter>
                <p>&nbsp;</p>
              </CardFooter>
            </Card>
          </div>
          <div>
            <CustomerAdditionalConfigFields />
          </div>
        </div>
      </form>
    </Form>
  );

  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>
  );
};
