'use client';

import React, { useEffect, useMemo, useState } from 'react';
import { Alert, Button, Form, Modal } from 'antd';
import { ApiError } from '../../lib/api';
import { customersApi, type Customer, type CustomerDuplicate } from '../../lib/customers';
import type { DirectoryUser } from '../../lib/leads';
import { CUSTOMER_MODAL_WIDTH, CustomerFormFields, toCustomerInput, type CustomerFormValues } from './CustomerFormFields';

export interface CustomerFormModalProps {
  open: boolean;
  customer: Customer | null;
  currentUserId: string;
  people: DirectoryUser[];
  onClose: () => void;
  onSaved: (saved: Customer) => void;
}

/** Create / edit a customer with its primary contact, warning about possible duplicates by name or website. */
export function CustomerFormModal(props: CustomerFormModalProps) {
  if (!props.open) return null;
  return <CustomerFormModalInner {...props} />;
}

function CustomerFormModalInner({ open, customer, currentUserId, people, onClose, onSaved }: CustomerFormModalProps) {
  const [form] = Form.useForm<CustomerFormValues>();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [dupResult, setDupResult] = useState<{ key: string; items: CustomerDuplicate[] } | null>(null);

  const editing = Boolean(customer);
  const nameValue = Form.useWatch('name', form);
  const websiteValue = Form.useWatch('website', form);
  const trimmedName = nameValue?.trim() ?? '';
  const trimmedWeb = websiteValue?.trim() ?? '';
  const lookupKey = open && (trimmedName.length >= 2 || trimmedWeb.length >= 4) ? `${customer?.id ?? 'new'}|${trimmedName}|${trimmedWeb}` : '';
  const duplicates = lookupKey && dupResult?.key === lookupKey ? dupResult.items : [];

  const initialValues = useMemo<CustomerFormValues>(
    () =>
      customer
        ? {
            name: customer.name,
            contactPerson: customer.contactPerson ?? '',
            email: customer.email ?? '',
            contactTitle: customer.contactTitle ?? undefined,
            phone: customer.phone ?? undefined,
            city: customer.city ?? undefined,
            industry: customer.industry ?? undefined,
            website: customer.website ?? undefined,
            techStack: customer.techStack ?? undefined,
            ownerId: customer.owner?.id ?? undefined,
          }
        : { name: '', contactPerson: '', email: '', ownerId: currentUserId },
    [customer, currentUserId],
  );

  useEffect(() => {
    if (!lookupKey) return;
    let active = true;
    const timer = setTimeout(() => {
      customersApi
        .checkDuplicate({ name: trimmedName.length >= 2 ? trimmedName : undefined, website: trimmedWeb.length >= 4 ? trimmedWeb : undefined, excludeId: customer?.id })
        .then((items) => {
          if (active) setDupResult({ key: lookupKey, items });
        })
        .catch(() => {
          if (active) setDupResult({ key: lookupKey, items: [] });
        });
    }, 350);
    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [lookupKey, trimmedName, trimmedWeb, customer?.id]);

  const submit = async (v: CustomerFormValues) => {
    setSaving(true);
    setError(null);
    const input = toCustomerInput(v);
    try {
      const saved = customer ? await customersApi.update(customer.id, input) : await customersApi.create(input);
      onSaved(saved);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'The customer could not be saved. Try again.');
    } finally {
      setSaving(false);
    }
  };

  return (
    <Modal
      open={open}
      title={editing ? 'Edit customer' : 'New customer'}
      onCancel={onClose}
      afterOpenChange={() => {
        setError(null);
        setDupResult(null);
      }}
      destroyOnHidden
      width={CUSTOMER_MODAL_WIDTH}
      footer={
        <div className="flex justify-end gap-2">
          <Button type="text" onClick={onClose}>
            Cancel
          </Button>
          <Button type="primary" loading={saving} onClick={() => form.submit()}>
            {editing ? 'Save changes' : 'Create customer'}
          </Button>
        </div>
      }
    >
      {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}
      {duplicates.length > 0 ? <Alert type="warning" showIcon className="mb-4" title="Possible duplicate customer" description={duplicates.map((d) => (d.city ? `${d.name} (${d.city})` : d.name)).join(', ')} /> : null}
      <Form<CustomerFormValues> key={customer?.id ?? 'new'} form={form} layout="vertical" initialValues={initialValues} onFinish={(v) => void submit(v)} preserve={false}>
        <CustomerFormFields people={people} currentIndustry={customer?.industry} />
      </Form>
    </Modal>
  );
}

// Backwards-compatibility alias
export const AccountFormModal = CustomerFormModal;
