'use client';

import React, { useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { Alert, Button, Form, Input, Modal, Select } from 'antd';
import { ApiError } from '../../lib/api';
import { customersApi, type CustomerOption } from '../../lib/customers';
import { contactsApi, type Contact, type ContactDuplicate, type ContactInput } from '../../lib/contacts';
import type { DirectoryUser } from '../../lib/leads';
import { emailValidationRule, phoneValidationRule } from '../../lib/validation';

interface FormValues {
  name: string;
  accountId: string;
  title?: string;
  email?: string;
  phone?: string;
  ownerId?: string;
}

export interface CustomerContactModalProps {
  open: boolean;
  contact: Contact | null;
  currentUserId: string;
  people: DirectoryUser[];
  defaultAccountId?: string;
  onClose: () => void;
  onSaved: (saved: Contact) => void;
}

/**
 * Modal to add/edit an additional contact person under a customer.
 */
export function CustomerContactModal(props: CustomerContactModalProps) {
  if (!props.open) return null;
  return <CustomerContactModalInner {...props} />;
}

function CustomerContactModalInner({ open, contact, currentUserId, people, defaultAccountId, onClose, onSaved }: CustomerContactModalProps) {
  const [form] = Form.useForm<FormValues>();
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [accountOptions, setAccountOptions] = useState<CustomerOption[]>([]);
  const [accountsLoaded, setAccountsLoaded] = useState(false);
  const [dupResult, setDupResult] = useState<{
    key: string;
    items: ContactDuplicate[];
  } | null>(null);

  const editing = Boolean(contact);
  const emailValue = Form.useWatch('email', form);
  const trimmedEmail = emailValue?.trim() ?? '';
  const lookupKey = open && trimmedEmail.includes('@') && trimmedEmail.length >= 5 ? `${contact?.id ?? 'new'}|${trimmedEmail}` : '';
  const duplicates = lookupKey && dupResult?.key === lookupKey ? dupResult.items : [];
  const loadingAccounts = open && !accountsLoaded;

  const initialValues = useMemo<Partial<FormValues>>(() => {
    if (contact) {
      return {
        name: contact.name,
        accountId: contact.accountId ?? undefined,
        title: contact.title ?? undefined,
        email: contact.email,
        phone: contact.phone ?? undefined,
        ownerId: contact.owner?.id ?? currentUserId,
      };
    }
    return {
      name: '',
      accountId: defaultAccountId,
      ownerId: currentUserId,
    };
  }, [contact, currentUserId, defaultAccountId]);

  useEffect(() => {
    if (!open) return;
    let active = true;
    customersApi
      .options()
      .then((opts) => {
        if (active) setAccountOptions(opts);
      })
      .catch(() => {
        if (active) setAccountOptions([]);
      })
      .finally(() => {
        if (active) setAccountsLoaded(true);
      });
    return () => {
      active = false;
    };
  }, [open]);

  useEffect(() => {
    if (!lookupKey) return;
    let active = true;
    const timer = setTimeout(() => {
      contactsApi
        .checkDuplicate({
          email: trimmedEmail,
          excludeId: contact?.id,
        })
        .then((items) => {
          if (active) setDupResult({ key: lookupKey, items });
        })
        .catch(() => {
          if (active) setDupResult({ key: lookupKey, items: [] });
        });
    }, 350);
    return () => {
      active = false;
      clearTimeout(timer);
    };
  }, [lookupKey, trimmedEmail, contact?.id]);

  const submit = async (v: FormValues) => {
    setSaving(true);
    setError(null);
    const input: ContactInput = {
      name: v.name,
      accountId: v.accountId,
      email: v.email?.trim() || null,
      title: v.title ?? null,
      phone: v.phone ?? null,
      lifecycle: contact?.lifecycle ?? 'Customer',
      ownerId: v.ownerId ?? null,
    };
    try {
      const saved = contact ? await contactsApi.update(contact.id, input) : await contactsApi.create(input);
      onSaved(saved);
    } catch (err) {
      setError(err instanceof ApiError ? err.message : 'The contact could not be saved. Try again.');
    } finally {
      setSaving(false);
    }
  };

  const noAccounts = !loadingAccounts && accountOptions.length === 0;

  return (
    <Modal
      open={open}
      title={editing ? 'Edit contact person' : 'Add contact person'}
      onCancel={onClose}
      afterOpenChange={(visible) => {
        if (visible) {
          form.setFieldsValue(initialValues);
        } else {
          setError(null);
          setDupResult(null);
        }
      }}
      destroyOnHidden
      width={620}
      footer={
        <div className="flex justify-end gap-2">
          <Button type="text" onClick={onClose}>
            Cancel
          </Button>
          <Button type="primary" loading={saving} disabled={noAccounts} onClick={() => form.submit()}>
            {editing ? 'Save changes' : 'Add contact'}
          </Button>
        </div>
      }
    >
      {error ? <Alert type="error" showIcon title={error} className="mb-4" /> : null}
      {noAccounts ? (
        <Alert
          type="info"
          showIcon
          className="mb-4"
          title="Create a customer first"
          description={
            <span>
              Every contact person belongs to a customer.{' '}
              <Link href="/app/customers" onClick={onClose}>
                Open Customers
              </Link>{' '}
              to create your first record.
            </span>
          }
        />
      ) : null}
      {duplicates.length > 0 ? <Alert type="warning" showIcon className="mb-4" title="Possible duplicate contact email" description={duplicates.map((d) => (d.account ? `${d.name} (${d.account.name})` : d.name)).join(', ')} /> : null}

      <Form<FormValues> key={contact?.id ?? 'new'} form={form} layout="vertical" initialValues={initialValues} onFinish={(v) => void submit(v)} preserve={false}>
        <div className="grid grid-cols-1 gap-x-4 sm:grid-cols-2">
          <Form.Item
            name="name"
            label="Full name"
            rules={[
              {
                required: true,
                whitespace: true,
                message: 'Enter the contact name',
              },
              { max: 200, message: 'Use 200 characters or fewer' },
            ]}
          >
            <Input placeholder="Enter contact person name" autoFocus />
          </Form.Item>

          <Form.Item name="accountId" label="Customer" rules={[{ required: true, message: 'Select a customer' }]}>
            <Select
              showSearch
              optionFilterProp="label"
              loading={loadingAccounts}
              placeholder="Select a customer"
              options={accountOptions.map((a) => ({
                value: a.id,
                label: a.city ? `${a.name} (${a.city})` : a.name,
              }))}
            />
          </Form.Item>

          <Form.Item
            name="email"
            label="Email"
            dependencies={['phone']}
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const phoneVal = getFieldValue('phone');
                  const hasEmail = Boolean(typeof value === 'string' ? value.trim() : value);
                  const hasPhone = Boolean(typeof phoneVal === 'string' ? phoneVal.trim() : phoneVal);
                  if (!hasEmail && !hasPhone) {
                    return Promise.reject(new Error('Provide at least an Email or Phone'));
                  }
                  return Promise.resolve();
                },
              }),
              ...emailValidationRule(false),
            ]}
          >
            <Input placeholder="Enter email address" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="Phone"
            dependencies={['email']}
            validateTrigger={['onChange', 'onBlur']}
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  const emailVal = getFieldValue('email');
                  const hasEmail = Boolean(typeof emailVal === 'string' ? emailVal.trim() : emailVal);
                  const hasPhone = Boolean(typeof value === 'string' ? value.trim() : value);
                  if (!hasEmail && !hasPhone) {
                    return Promise.reject(new Error('Provide at least an Email or Phone'));
                  }
                  return Promise.resolve();
                },
              }),
              phoneValidationRule,
              { max: 40, message: 'Use 40 characters or fewer' },
            ]}
          >
            <Input placeholder="Enter phone number" inputMode="tel" />
          </Form.Item>

          <Form.Item name="title" label="Designation" rules={[{ max: 120, message: 'Use 120 characters or fewer' }]}>
            <Input placeholder="Enter designation or job title" />
          </Form.Item>

          <Form.Item name="ownerId" label="Contact owner">
            <Select allowClear placeholder="Assign owner" options={people.map((p) => ({ value: p.id, label: p.name }))} />
          </Form.Item>
        </div>
      </Form>
    </Modal>
  );
}

// Backwards-compatibility alias
export const ContactFormModal = CustomerContactModal;
