
import { UnsavedChangesProvider, useUnsavedChangesContext } from "@erp/core/hooks";
import {
  Button,
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@repo/shadcn-ui/components";
import { Plus } from "lucide-react";
import { useCallback, useId } from 'react';
import { useTranslation } from "../../i18n";
import { useCustomerCreateController } from '../../pages/create/use-customer-create-controller';
import { CustomerFormData } from "../../schemas";
import { CustomerEditForm } from '../editor';


type CustomerCreateModalProps = {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  client: CustomerFormData;
  onChange: (customer: CustomerFormData) => void;
  onSubmit: () => void; // ← mantenemos tu firma (no se usa directamente aquí)
};

export function CustomerCreateModal({
  open,
  onOpenChange,
}: CustomerCreateModalProps) {
  const { t } = useTranslation();
  const formId = useId();

  const { requestConfirm } = useUnsavedChangesContext();

  const {
    form, isCreating, isCreateError, createError,
    handleSubmit, handleError, FormProvider
  } = useCustomerCreateController();

  const { isDirty } = form.formState;

  const guardClose = useCallback(async (nextOpen: boolean) => {
    if (nextOpen) return onOpenChange(true);

    if (isCreating) return;

    if (!isDirty) {
      return onOpenChange(false);
    }

    if (await requestConfirm()) {
      return onOpenChange(false);
    }
  }, [requestConfirm, isCreating, onOpenChange, isDirty]);


  const handleFormSubmit = (data: CustomerFormData) => handleSubmit(data /*, () => onOpenChange(false)*/);

  return (
    <UnsavedChangesProvider isDirty={isDirty}>

      <Dialog open={open} onOpenChange={guardClose}>
        <DialogContent className="bg-card border-border p-0 max-w-[calc(100vw-2rem)] sm:[calc(max-w-3xl-2rem)] h-[calc(100dvh-2rem)]">
          <DialogHeader className="px-6 pt-6 pb-4 border-b">
            <DialogTitle className="flex items-center gap-2">
              <Plus className="size-5" /> {t("pages.create.title")}
            </DialogTitle>
            <DialogDescription className='text-left'>{t("pages.create.description")}</DialogDescription>
          </DialogHeader>

          <div className="overflow-y-auto h:[calc(100%-8rem)]">
            <FormProvider {...form}>
              <CustomerEditForm
                formId={formId}
                onSubmit={handleFormSubmit}
                onError={handleError}
                className="max-w-none"
              />

              {isCreateError && (
                <p role="alert" className="mt-3 text-sm text-destructive">
                  {(createError as Error)?.message}
                </p>
              )}
            </FormProvider>
          </div>

          <DialogFooter className="px-6 py-4 border-t bg-card">
            <Button type="button" form={formId} variant="outline" className='cursor-pointer' onClick={() => guardClose(false)} disabled={isCreating}>
              {t('common.cancel', "Cancelar")}
            </Button>
            <Button type="submit" form={formId} disabled={isCreating} className='cursor-pointer'>
              {isCreating ? <span aria-live="polite">{t('common.saving', "Guardando")}</span> : <span>{t('common.save', "Guardar")}</span>}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

    </UnsavedChangesProvider>
  );
}