
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 { 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 {
    form, isCreating, isCreateError, createError,
    handleSubmit, handleError, FormProvider
  } = useCustomerCreateController();

  const { isDirty } = form.formState;

  const guardClose = async (nextOpen: boolean) => {
    if (nextOpen) return onOpenChange(true);
    if (isCreating) return;
    const { requestConfirm } = useUnsavedChangesContext();
    const ok = await requestConfirm();
    if (ok) onOpenChange(false);
  };

  return (
    <UnsavedChangesProvider isDirty={isDirty}>
      <FormProvider {...form}>
        <Dialog open={open} onOpenChange={guardClose}>
          <DialogContent className="bg-card border-border p-0 max-w-[calc(100vw-2rem)] sm:max-w-[min(100vw-3rem,1280px)] 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>{t("pages.create.subtitle")}</DialogDescription>
            </DialogHeader>

            <div className="px-6 py-4 overflow-y-auto h:[calc(100%-8rem)]">

              <CustomerEditForm
                formId={formId}
                onSubmit={(data: CustomerFormData) => handleSubmit(data, () => onOpenChange(false))}
                onError={handleError}
                className="max-w-none"
              />

              {isCreateError && (
                <p role="alert" className="mt-3 text-sm text-destructive">
                  {(createError as Error)?.message}
                </p>
              )}
            </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>
      </FormProvider>
    </UnsavedChangesProvider>
  );
}