'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { createCompany, findDuplicateDomains } from '@/features/companies/api.client';
import type { CreateCompanyBody } from '@/features/companies/types';
import {
  DEFAULT_COMPANY_FORM,
  createErrorPlacement,
  duplicateLookupDomain,
  escapeClosesPanel,
  shownDuplicates,
  forgetDuplicates,
  rememberDuplicates,
  type DuplicateAnswers,
} from '@/features/companies/ui/companyCreate';
import { DuplicateDomainNotice } from '@/features/companies/ui/DuplicateDomainNotice';
import { listContacts } from '@/features/contacts/api.client';
import {
  CustomFieldsForm,
  customValuesForCreate,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import {
  getCreateForm,
  standardLabels,
  type CreateFormField,
} from '@/features/create-forms/api.client';
import type { CustomPropertyDefinition } from '@/features/custom-properties/api.client';
import { applyPropertyLogic, usePropertyLogic } from '@/features/custom-properties/logic';
import { linkRecords, listLinkLabels } from '@/features/objects/api.client';
import { ownerOnCreate } from '@/features/owners/labels';
import type { useFieldAccess } from '@/features/permission-sets/field-access';
import { cn } from '@/lib/utils/cn';
import {
  domainFromWebsite,
  normalizeWebsite,
  phoneError,
  sanitizePhoneInput,
  websiteError,
} from '@/lib/validation/contact-company';

/** The form until (or if) the business's form fails to load: the API's default (B3). */
const DEFAULT_FIELDS: CreateFormField[] = DEFAULT_COMPANY_FORM;

/** Wait this long after typing before looking the domain up. */
const DUPLICATE_LOOKUP_MS = 400;
/** The duplicate note's live region, which the domain input points at. */
const DUPLICATE_NOTE_ID = 'companyCreate-duplicates';

type TextKey = 'domain' | 'name' | 'phone' | 'city' | 'state' | 'country' | 'website';
type Form = Record<TextKey | 'ownerId' | 'industry', string> & {
  contactId: string;
  contactName: string;
  labelId: string;
};

// The design's form starts with every dropdown on "Select".
const emptyForm = (): Form => ({
  domain: '',
  name: '',
  phone: '',
  city: '',
  state: '',
  country: '',
  website: '',
  ownerId: '',
  industry: '',
  contactId: '',
  contactName: '',
  labelId: '',
});

/**
 * "Create Company" (28 Oct design, components/create-form.js): the fields of the business's
 * create form in its order, errors under each field ("Company name is required."), "Edit this
 * form ↗", an Associations section (Contacts: Associate record + Association label), and
 * Create · Create and add another · Cancel.
 */
export function CreateCompanyDrawer({
  open,
  singular,
  ownerOptions,
  industryOptions,
  customDefs,
  access,
  timeZone,
  onClose,
  onCreated,
  onCreatedAnother,
}: {
  open: boolean;
  /** "Company", or the business's name for it. */
  singular: string;
  /** Kept for callers; the design starts the owner on "Select". */
  defaultOwnerId?: string;
  ownerOptions: CustomSelectOption[];
  industryOptions: CustomSelectOption[];
  customDefs: CustomPropertyDefinition[];
  access: ReturnType<typeof useFieldAccess>;
  timeZone: string;
  onClose: () => void;
  /** After Create (not after Create and add another). */
  onCreated: (id: string) => void;
  /** After Create and add another (the list behind shows the new company). */
  onCreatedAnother?: () => void;
}) {
  const me = useCurrentUser();
  const toast = useToast();
  const isAdmin = Boolean(me.permissionSet.rules.app.manage_settings);
  const [formFields, setFormFields] = useState<CreateFormField[]>(DEFAULT_FIELDS);
  const [form, setForm] = useState<Form>(emptyForm);
  const [custom, setCustom] = useState<Record<string, CustomUiValue>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [formError, setFormError] = useState<string | null>(null);
  const [saving, setSaving] = useState<false | 'one' | 'another'>(false);
  const [labels, setLabels] = useState<CustomSelectOption[]>([]);
  /** B3, point 33: the duplicate lookups' answers, by the domain each asked about. */
  const [duplicates, setDuplicates] = useState<DuplicateAnswers>({});
  const formRef = useRef<HTMLFormElement>(null);
  const panelRef = useRef<HTMLElement>(null);
  // HUB-355: conditional property logic decides which custom fields the create form shows.
  const propertyLogic = usePropertyLogic('company');

  const reset = useCallback(() => {
    setForm(emptyForm());
    setCustom({});
    setErrors({});
    setFormError(null);
    setDuplicates({});
  }, []);

  useEffect(() => {
    if (!open) return;
    reset();
    getCreateForm('company').then(
      (res) => setFormFields(res.fields.length ? res.fields : DEFAULT_FIELDS),
      () => setFormFields(DEFAULT_FIELDS),
    );
    listLinkLabels('company', 'contact').then(
      (rows) =>
        setLabels(
          rows.map((l) => ({
            value: l.id,
            label: l.aType === 'company' ? l.name : (l.inverseName ?? l.name),
          })),
        ),
      () => setLabels([]),
    );
    const t = window.setTimeout(
      () => formRef.current?.querySelector<HTMLElement>('input, textarea')?.focus(),
      120,
    );
    return () => window.clearTimeout(t);
  }, [open, reset]);

  // B3, point 2: Escape closes the panel (create-form.js:339-340). A picker open inside it
  // (owner, industry, a custom field, the contact search) closes first, on its own Escape.
  // Capture phase: the open pickers are counted before any of them handles the key, since
  // React applies a picker's close between listeners, before a bubbling window listener runs.
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      const openPickers = panelRef.current?.querySelectorAll('[aria-expanded="true"]').length ?? 0;
      if (escapeClosesPanel(e.key, openPickers)) onClose();
    };
    window.addEventListener('keydown', onKey, true);
    return () => window.removeEventListener('keydown', onKey, true);
  }, [open, onClose]);

  useEffect(() => {
    if (!open) return;
    document.documentElement.classList.add('company-drawer-open');
    document.body.classList.add('company-drawer-open');
    return () => {
      document.documentElement.classList.remove('company-drawer-open');
      document.body.classList.remove('company-drawer-open');
    };
  }, [open]);

  const required = new Set(formFields.filter((f) => f.required).map((f) => f.field));
  // The name is always needed (the API refuses a company without one).
  required.add('name');
  const byName = useMemo(() => new Map(customDefs.map((d) => [d.name, d])), [customDefs]);
  /** The form's custom fields (and required ones it leaves out), after property logic. */
  const formCustom = useMemo(() => {
    const listed = formFields
      .filter((f) => f.field.startsWith('custom.'))
      .flatMap((f) => {
        const def = byName.get(f.field.slice('custom.'.length));
        return def && !def.readOnly && !def.calculated
          ? [{ ...def, required: def.required || f.required }]
          : [];
      });
    const extra = customDefs.filter(
      (d) => d.required && !d.readOnly && !d.calculated && !listed.some((l) => l.name === d.name),
    );
    return applyPropertyLogic([...listed, ...extra], propertyLogic, custom);
  }, [customDefs, byName, formFields, propertyLogic, custom]);
  const shownCustom = new Set(formCustom.map((d) => d.name));
  const extraCustom = formCustom.filter(
    (d) => !formFields.some((f) => f.field === `custom.${d.name}`),
  );

  const label = (field: string) =>
    field === 'domain' ? 'Company domain name' : (standardLabels('company')[field] ?? field);
  const clearError = (field: string) =>
    setErrors((e) => {
      const rest = { ...e };
      delete rest[field];
      return rest;
    });
  const setField = (key: keyof Form, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    clearError(key);
  };
  const on = (field: string) =>
    formFields.some((f) => f.field === field) &&
    !access.locked(field === 'domain' ? 'domain' : field);

  // B3, point 33: which field takes the domain (the form's domain, else its website), and the
  // domain typed there once it looks whole.
  const domainField = on('domain') ? 'domain' : on('website') ? 'website' : null;
  const lookupDomain =
    open && domainField ? duplicateLookupDomain(form.website || form.domain) : null;
  useEffect(() => {
    if (!lookupDomain) return;
    const t = window.setTimeout(() => {
      // Kept by domain, so an answer arriving late never replaces the current one. The check
      // only advises: a failed lookup shows nothing, and Create still gets the 409.
      findDuplicateDomains(lookupDomain).then(
        (res) =>
          setDuplicates((all) =>
            rememberDuplicates(all, {
              domain: lookupDomain,
              matches: res.matches,
              hidden: res.hidden ?? 0,
            }),
          ),
        () => setDuplicates((all) => forgetDuplicates(all, lookupDomain)),
      );
    }, DUPLICATE_LOOKUP_MS);
    return () => window.clearTimeout(t);
  }, [lookupDomain]);
  const duplicateNotice = shownDuplicates(lookupDomain, duplicates);

  const validate = (): Record<string, string> => {
    const out: Record<string, string> = {};
    for (const f of formFields) {
      if (f.field.startsWith('custom.') || !required.has(f.field) || access.locked(f.field))
        continue;
      const v = (form as Record<string, string>)[f.field] ?? '';
      if (!v.trim()) out[f.field] = `${label(f.field)} is required.`;
    }
    if (!form.name.trim()) out.name = 'Company name is required.';
    const site = form.website || form.domain;
    if (!out.domain && site.trim() && !access.locked('domain')) {
      const bad = websiteError(site);
      if (bad) out[form.website ? 'website' : 'domain'] = bad;
    }
    if (!out.phone && form.phone.trim() && !access.locked('phone')) {
      const bad = phoneError(form.phone);
      if (bad) out.phone = bad;
    }
    return out;
  };

  const submit = async (another: boolean) => {
    const found = validate();
    setErrors(found);
    setFormError(null);
    if (Object.keys(found).length) {
      const first = Object.keys(found)[0];
      formRef.current?.querySelector<HTMLElement>(`#companyCreate-${first}`)?.focus();
      return;
    }
    const customValues = customValuesForCreate(formCustom, custom, timeZone);
    if ('error' in customValues) {
      setFormError(customValues.error);
      return;
    }
    const site = form.website.trim() || form.domain.trim();
    const text = (v: string) => v.trim() || null;
    const body: CreateCompanyBody = {
      name: form.name.trim(),
      ...(site && !access.locked('domain')
        ? { domain: domainFromWebsite(site), website: normalizeWebsite(site) }
        : {}),
      ...(on('phone') ? { phone: text(form.phone) } : {}),
      ...(on('industry') ? { industry: text(form.industry) } : {}),
      ...(on('city') ? { city: text(form.city) } : {}),
      ...(on('state') ? { state: text(form.state) } : {}),
      ...(on('country') ? { country: text(form.country) } : {}),
      ...ownerOnCreate(form.ownerId, on('ownerId')),
      ...(Object.keys(customValues.value).length ? { customProperties: customValues.value } : {}),
    };
    setSaving(another ? 'another' : 'one');
    try {
      const created = await createCompany(body);
      if (form.contactId) {
        await linkRecords({
          from: { type: 'company', id: created.id },
          to: { type: 'contact', id: form.contactId },
          ...(form.labelId ? { labelIds: [form.labelId] } : {}),
        }).catch(() => toast('Created, but the contact could not be associated', 'info'));
      }
      if (another) {
        toast(`Company "${created.name}" created. Add another.`, 'success');
        reset();
        onCreatedAnother?.();
      } else {
        toast(`Company "${created.name}" created`, 'success');
        onClose();
        onCreated(created.id);
      }
    } catch (err) {
      // B3: a used domain (409) is said under the domain field; anything else at the top.
      const placed = createErrorPlacement(err, domainField !== null);
      if ('form' in placed) setFormError(placed.form);
      else {
        setErrors((e) => ({ ...e, [domainField!]: placed.message }));
        formRef.current?.querySelector<HTMLElement>(`#companyCreate-${domainField}`)?.focus();
      }
    } finally {
      setSaving(false);
    }
  };

  const fieldBox = (field: string, input: ReactNode) => (
    <div key={field} className={cn('field', errors[field] && 'is-invalid')}>
      <label htmlFor={`companyCreate-${field}`}>
        {label(field)}
        {/* The design's mark: joined to the label, in its colour (create-form.js:136). */}
        {required.has(field) ? (
          <span className="cf-req" aria-hidden>
            *
          </span>
        ) : null}
      </label>
      {input}
      {errors[field] ? (
        <span className="field__error" role="alert">
          {errors[field]}
        </span>
      ) : null}
      {field === domainField ? (
        // Always there and empty while idle, so screen readers announce the note when it fills.
        <div id={DUPLICATE_NOTE_ID} role="status" aria-live="polite">
          {duplicateNotice ? (
            <DuplicateDomainNotice
              matches={duplicateNotice.matches}
              hidden={duplicateNotice.hidden}
            />
          ) : null}
        </div>
      ) : null}
    </div>
  );
  const textInput = (field: TextKey, type = 'text', maxLength?: number) =>
    fieldBox(
      field,
      <input
        className="input"
        id={`companyCreate-${field}`}
        type={type}
        maxLength={maxLength}
        aria-required={required.has(field) || undefined}
        aria-invalid={Boolean(errors[field])}
        aria-describedby={field === domainField && duplicateNotice ? DUPLICATE_NOTE_ID : undefined}
        value={form[field]}
        onChange={(e) =>
          setField(field, field === 'phone' ? sanitizePhoneInput(e.target.value) : e.target.value)
        }
      />,
    );
  const renderField = (field: string): ReactNode => {
    if (field.startsWith('custom.')) {
      const def = byName.get(field.slice('custom.'.length));
      if (!def || !shownCustom.has(def.name)) return null;
      const shown = formCustom.find((d) => d.name === def.name)!;
      return (
        <CustomFieldsForm
          key={field}
          defs={[shown]}
          values={custom}
          onChange={(name, value) => setCustom((cur) => ({ ...cur, [name]: value }))}
          idPrefix="companyCreateCustom"
          designLabels
          designSelects
          timeZone={timeZone}
        />
      );
    }
    if (access.locked(field)) return null;
    switch (field) {
      case 'name':
        return textInput('name', 'text', 191);
      case 'domain':
      case 'website':
        return textInput(field, 'text', 255);
      case 'phone':
        return textInput('phone', 'tel', 32);
      case 'city':
      case 'state':
      case 'country':
        return textInput(field, 'text', 191);
      case 'ownerId':
        return fieldBox(
          field,
          <CustomSelect
            id="companyCreate-ownerId"
            className="company-drawer-select"
            placeholder="Select"
            value={form.ownerId}
            options={ownerOptions}
            onChange={(v) => setField('ownerId', v)}
          />,
        );
      case 'industry':
        return fieldBox(
          field,
          <CustomSelect
            id="companyCreate-industry"
            className="company-drawer-select"
            placeholder="Select"
            value={form.industry}
            options={industryOptions}
            onChange={(v) => setField('industry', v)}
          />,
        );
      default:
        return null;
    }
  };

  return (
    <>
      {open ? (
        <div
          className="popup-overlay is-visible company-create-overlay cc-design"
          onClick={onClose}
          aria-hidden
        />
      ) : null}
      <aside
        ref={panelRef}
        className={cn(
          // B3: `cc-design` scopes the 28 Oct panel styles (companies.css) to this drawer only.
          'popup-drawer company-create-drawer contact-create-drawer cc-design',
          open && 'is-open',
        )}
        role="dialog"
        aria-modal={open}
        aria-hidden={!open}
        inert={!open}
        aria-labelledby="createCompanyDrawerTitle"
      >
        <header className="drawer-header">
          <div className="drawer-header-content">
            <h2 className="drawer-title" id="createCompanyDrawerTitle">
              Create {singular}
            </h2>
          </div>
          <button type="button" className="drawer-close" aria-label="Close" onClick={onClose}>
            <svg
              className="icon iconSize-18"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              aria-hidden
            >
              <path d="M6 6l12 12M18 6 6 18" strokeLinecap="round" />
            </svg>
          </button>
        </header>

        <form
          ref={formRef}
          id="createCompanyDrawerForm"
          className="popup-body-form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void submit(false);
          }}
        >
          {isAdmin ? (
            <p className="cf-editlink cc-editlink">
              <Link href="/create-form-editor?object=company" target="_blank" rel="noopener">
                Edit this form
                <svg
                  className="icon iconSize-14"
                  viewBox="0 0 24 24"
                  fill="none"
                  stroke="currentColor"
                  strokeWidth="2"
                  aria-hidden
                >
                  <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6M15 3h6v6M10 14 21 3" />
                </svg>
                <span className="crm-visually-hidden"> (opens in a new tab)</span>
              </Link>
            </p>
          ) : null}
          {formError ? <Alert tone="danger">{formError}</Alert> : null}
          <div className="crm-d-grid crm-gap-3">
            {formFields.map((f) => renderField(f.field))}
            {extraCustom.length ? (
              <CustomFieldsForm
                defs={extraCustom}
                values={custom}
                onChange={(name, value) => setCustom((cur) => ({ ...cur, [name]: value }))}
                idPrefix="companyCreateCustom"
                designLabels
                designSelects
                timeZone={timeZone}
              />
            ) : null}
          </div>
          <section className="cf-assoc cc-assoc" aria-labelledby="companyCreateAssoc">
            <h3 id="companyCreateAssoc">Associations</h3>
            <div className="cf-assoc__item">
              <p className="cf-assoc__obj">Contacts</p>
              <div className="field">
                <label htmlFor="companyCreate-contact">Associate record</label>
                <ContactSearch
                  id="companyCreate-contact"
                  value={form.contactId ? { id: form.contactId, name: form.contactName } : null}
                  onChange={(c) =>
                    setForm((f) => ({ ...f, contactId: c?.id ?? '', contactName: c?.name ?? '' }))
                  }
                />
              </div>
              <div className="field">
                <label htmlFor="companyCreate-label">
                  Association label
                  <span className="cf-req" aria-hidden>
                    *
                  </span>
                </label>
                <CustomSelect
                  id="companyCreate-label"
                  className="company-drawer-select"
                  placeholder="Unlabeled"
                  value={form.labelId}
                  options={[{ value: '', label: 'Unlabeled' }, ...labels]}
                  onChange={(v) => setForm((f) => ({ ...f, labelId: v }))}
                  searchable={false}
                />
              </div>
            </div>
          </section>
        </form>

        <footer className="drawer-footer">
          <div className="drawer-footer-actions cc-foot">
            <button
              type="submit"
              form="createCompanyDrawerForm"
              className={cn('btn-crm btn-crm--primary', saving === 'one' && 'is-loading')}
              disabled={Boolean(saving)}
            >
              <span className="btn-crm__spinner" aria-hidden />
              <span className="btn-crm__text">Create</span>
            </button>
            <button
              type="button"
              className={cn('btn-crm btn-crm--outline', saving === 'another' && 'is-loading')}
              disabled={Boolean(saving)}
              onClick={() => void submit(true)}
            >
              <span className="btn-crm__spinner" aria-hidden />
              <span className="btn-crm__text">Create and add another</span>
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
              Cancel
            </button>
          </div>
        </footer>
      </aside>
    </>
  );
}

/** Contact picker that searches every contact through the API. */
function ContactSearch({
  id,
  value,
  onChange,
}: {
  id: string;
  value: { id: string; name: string } | null;
  onChange: (contact: { id: string; name: string } | null) => void;
}) {
  const [text, setText] = useState('');
  const [results, setResults] = useState<Array<{ id: string; name: string; email: string | null }>>(
    [],
  );
  const [open, setOpen] = useState(false);
  const [loading, setLoading] = useState(false);
  const boxRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!open) return;
    let alive = true;
    setLoading(true);
    const t = window.setTimeout(() => {
      listContacts({ search: text.trim() || undefined, limit: 20 })
        .then((page) => {
          if (alive)
            setResults(
              page.data.map((c) => ({
                id: c.id,
                name: [c.firstName, c.lastName].filter(Boolean).join(' ') || c.email || 'Contact',
                email: c.email ?? null,
              })),
            );
        })
        .catch(() => {
          if (alive) setResults([]);
        })
        .finally(() => {
          if (alive) setLoading(false);
        });
    }, 250);
    return () => {
      alive = false;
      window.clearTimeout(t);
    };
  }, [text, open]);

  useEffect(() => {
    if (!open) return;
    const onDown = (e: MouseEvent) => {
      if (!boxRef.current?.contains(e.target as Node)) setOpen(false);
    };
    document.addEventListener('mousedown', onDown);
    return () => document.removeEventListener('mousedown', onDown);
  }, [open]);

  if (value) {
    return (
      <div className="crm-d-flex crm-align-items-center crm-gap-2">
        <span className="input crm-d-flex crm-align-items-center" style={{ flex: 1 }}>
          {value.name}
        </span>
        <button
          type="button"
          className="btn-crm btn-crm--ghost btn-crm--sm"
          onClick={() => onChange(null)}
        >
          Change
        </button>
      </div>
    );
  }
  return (
    <div ref={boxRef} className="custom-select" style={{ position: 'relative' }}>
      <input
        id={id}
        className="input"
        type="search"
        placeholder="Search contacts"
        autoComplete="off"
        role="combobox"
        aria-expanded={open}
        aria-controls={`${id}-list`}
        value={text}
        onFocus={() => setOpen(true)}
        // Escape closes the results first; the panel closes on the next one (B3).
        onKeyDown={(e) => {
          if (e.key === 'Escape') setOpen(false);
        }}
        onChange={(e) => {
          setText(e.target.value);
          setOpen(true);
        }}
      />
      {open ? (
        <div
          id={`${id}-list`}
          className="custom-select__dropdown"
          role="listbox"
          style={{ display: 'block' }}
        >
          <ul className="custom-select__options">
            {loading ? <li className="custom-select__option">Searching…</li> : null}
            {!loading && results.length === 0 ? (
              <li className="custom-select__option">No contacts found</li>
            ) : null}
            {results.map((c) => (
              <li
                key={c.id}
                className="custom-select__option"
                role="option"
                aria-selected={false}
                onMouseDown={(e) => {
                  e.preventDefault();
                  onChange({ id: c.id, name: c.name });
                  setText('');
                  setOpen(false);
                }}
              >
                <span className="custom-select__option-text">
                  {c.name}
                  {c.email ? <span className="crm-text-muted"> · {c.email}</span> : null}
                </span>
              </li>
            ))}
          </ul>
        </div>
      ) : null}
    </div>
  );
}
