'use client';

import Link from 'next/link';
import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import type { AssociationCandidate } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import {
  CustomFieldInput,
  customValuesForCreate,
  type CustomUiValue,
} from '@/features/contacts/ui/actions/custom-fields';
import { isLockedField } from '@/features/custom-properties/api.client';
import { cn } from '@/lib/utils/cn';
import { createObjectRecord, getObjectRecord, listLinkedRecords } from '../../api.client';
import { saveErrorText } from '../../errors';
import { conflictRecordOf } from '../../leads';
import { objectRecordPath } from '../../paths';
import type { ObjectSchema } from '../../useObjectSchema';
import type { ObjectRecord } from '../../types';
import { uiValuesChanged } from '../../unsaved';
import { CreateFormEditLink } from '../CreateFormEditLink';
import { useDrawerEscape } from '../../useDrawerEscape';
import { useUnsavedGuard } from '../../useUnsavedGuard';

/** The design's lead fields after the name, pipeline and stage (components/create-form.js). */
const LEAD_FIELDS = ['hs_lead_type', 'hs_lead_label'];

/** A lead already linked to the picked record (LD1). */
export interface LeadDuplicate {
  id: string;
  name: string | null;
  company: string | null;
}

/**
 * LD1: the 26 Nov design's duplicate warning (list-page.js `dupFor`, :5279-5285): "A lead with
 * this email already exists: <lead> - <company>" for a contact, "A lead for this company already
 * exists: <lead>" for a company. The picked contact is the email's owner, so its leads count.
 */
export function leadDuplicateText(
  kind: 'contact' | 'company',
  singular: string,
  dup: LeadDuplicate,
): string {
  const lower = singular.toLowerCase();
  const who = (dup.name || 'Untitled') + (dup.company ? ` - ${dup.company}` : '');
  return kind === 'contact'
    ? `A ${lower} with this email already exists: ${who}`
    : `A ${lower} for this company already exists: ${who}`;
}

/**
 * "Create Lead" (28 Oct design, components/create-form.js): "Associate Lead with" Contact or
 * Company and a required Associate record first; the lead fields (Lead Name, Pipeline, Lead
 * stage, Lead Type, Lead Label) stay locked until a record is picked, and the name starts as the
 * record's name. "Edit this form ↗"; Create Lead · Cancel.
 */
export function LeadCreateDrawer({
  open,
  onClose,
  schema,
  timeZone,
  onCreated,
}: {
  open: boolean;
  onClose: () => void;
  schema: ObjectSchema;
  timeZone: string;
  onCreated: (record: ObjectRecord, warning: string | null) => void;
}) {
  const me = useCurrentUser();
  const isAdmin = Boolean(me.permissionSet.rules.app.manage_settings);
  const { definition, defs, pipelines } = schema;
  const nameField = definition.displayProperty;
  const [kind, setKind] = useState<'contact' | 'company'>('contact');
  const [record, setRecord] = useState<AssociationCandidate | null>(null);
  const [values, setValues] = useState<Record<string, CustomUiValue>>({});
  const [pipelineId, setPipelineId] = useState('');
  const [stageId, setStageId] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [openLead, setOpenLead] = useState<{ id: string; name: string | null } | null>(null);
  /** LD1: a lead already linked to the picked record (a warning; saving still decides). */
  const [dup, setDup] = useState<LeadDuplicate | null>(null);
  const [formKey, setFormKey] = useState(0);
  /** The values, pipeline and stage the form started with (HUB-728: what counts as a change). */
  const [start, setStart] = useState<{
    values: Record<string, CustomUiValue>;
    pipelineId: string;
    stageId: string;
  }>({ values: {}, pipelineId: '', stageId: '' });
  const formRef = useRef<HTMLFormElement>(null);

  /** Lead Type and Lead Label, then any other required field the form must not leave out. */
  const fieldDefs = useMemo(() => {
    const listed = LEAD_FIELDS.flatMap((n) => defs.filter((d) => d.name === n));
    const required = defs.filter(
      (d) =>
        d.required && d.name !== nameField && !isLockedField(d) && !LEAD_FIELDS.includes(d.name),
    );
    return [...listed, ...required].filter((d) => !isLockedField(d));
  }, [defs, nameField]);
  const nameDef = defs.find((d) => d.name === nameField);
  const pipeline = pipelines.find((p) => p.id === pipelineId) ?? pipelines[0];
  const stages = (pipeline?.stages ?? []).filter((s) => !s.archived);

  useEffect(() => {
    if (!open) return;
    setKind('contact');
    setRecord(null);
    // The design starts Lead stage on New and Lead Type on New Business.
    const type = defs
      .find((d) => d.name === 'hs_lead_type')
      ?.options?.find((o) => /new business/i.test(o.label));
    const initial: Record<string, CustomUiValue> = type ? { hs_lead_type: type.value } : {};
    setValues(initial);
    const first = pipelines[0];
    const firstStage =
      (
        first?.stages.find((s) => !s.archived && /^new$/i.test(s.name)) ??
        first?.stages.find((s) => !s.archived)
      )?.id ?? '';
    setPipelineId(first?.id ?? '');
    setStageId(firstStage);
    setStart({ values: initial, pipelineId: first?.id ?? '', stageId: firstStage });
    setError(null);
    setOpenLead(null);
    setFormKey((k) => k + 1);
    // eslint-disable-next-line react-hooks/exhaustive-deps -- reset on open only
  }, [open]);

  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]);

  // LD1: once a contact or company is picked, look for a lead it already has. A failed lookup
  // shows nothing: the API still refuses a second open lead on Save.
  const pickedId = record?.id ?? null;
  useEffect(() => {
    setDup(null);
    if (!open || !pickedId) return;
    let alive = true;
    listLinkedRecords({ fromType: kind, fromId: pickedId, toType: definition.key, limit: 1 })
      .then(async (page) => {
        const hit = page.data[0];
        if (!hit || !alive) return;
        const full = await getObjectRecord(definition.key, hit.id).catch(() => null);
        const company = full?.customProperties.hs_associated_company_name;
        if (alive) {
          setDup({
            id: hit.id,
            name: hit.name,
            company: typeof company === 'string' && company ? company : null,
          });
        }
      })
      .catch(() => {});
    return () => {
      alive = false;
    };
  }, [open, kind, pickedId, definition.key]);

  const setValue = (name: string, value: CustomUiValue) =>
    setValues((cur) => ({ ...cur, [name]: value }));

  // HUB-728: closing with a picked record or typed values asks first.
  const dirty =
    open &&
    (record !== null ||
      uiValuesChanged(start.values, values) ||
      pipelineId !== start.pipelineId ||
      stageId !== start.stageId);
  const { guard, dialog } = useUnsavedGuard(dirty);
  const close = () => guard(onClose);
  // GL4 (go-live M3): Escape closes the drawer, asking first when something was typed.
  const panelRef = useRef<HTMLElement>(null);
  useDrawerEscape(open, panelRef, close);

  const pick = (next: AssociationCandidate | null) => {
    // The name follows the picked record until someone types their own.
    setValues((cur) => {
      const typed = cur[nameField];
      const untouched = !typed || (record && typed === record.title);
      return untouched ? { ...cur, [nameField]: next?.title ?? '' } : cur;
    });
    setRecord(next);
    if (next) {
      window.setTimeout(
        () => formRef.current?.querySelector<HTMLInputElement>(`#leadCreate-${nameField}`)?.focus(),
        0,
      );
    }
  };

  const submit = async () => {
    if (!record) {
      setError('Select a record to associate the lead with.');
      return;
    }
    const name = values[nameField];
    if (!name || (typeof name === 'string' && !name.trim())) {
      setError(`${nameDef?.label ?? 'Lead Name'} is required.`);
      return;
    }
    const custom = customValuesForCreate(
      nameDef ? [nameDef, ...fieldDefs] : fieldDefs,
      values,
      timeZone,
    );
    if ('error' in custom) {
      setError(custom.error);
      return;
    }
    if (typeof name === 'string') custom.value[nameField] = name.trim();
    setBusy(true);
    setError(null);
    setOpenLead(null);
    try {
      const created = await createObjectRecord(definition.key, {
        customProperties: custom.value,
        ...(definition.hasPipeline && pipeline
          ? { pipelineId: pipeline.id, ...(stageId ? { stageId } : {}) }
          : {}),
        ...(kind === 'contact' ? { contactId: record.id } : { companyId: record.id }),
      });
      onCreated(created, null);
      onClose();
    } catch (err) {
      const conflict = conflictRecordOf(err);
      if (conflict?.record.objectKey) {
        setError(conflict.message);
        setOpenLead({ id: conflict.record.id, name: conflict.record.name });
      } else setError(saveErrorText(err, defs));
    } finally {
      setBusy(false);
    }
  };

  const locked = !record;
  return (
    <>
      {open ? (
        <div
          className="popup-overlay is-visible company-create-overlay"
          onClick={close}
          aria-hidden
        />
      ) : null}
      <aside
        ref={panelRef}
        className={cn(
          'popup-drawer company-create-drawer contact-create-drawer',
          open && 'is-open',
        )}
        role="dialog"
        aria-modal={open}
        aria-hidden={!open}
        aria-labelledby="createLeadDrawerTitle"
      >
        <header className="drawer-header">
          <div className="drawer-header-content">
            <h2 className="drawer-title" id="createLeadDrawerTitle">
              Create {definition.singularLabel}
            </h2>
          </div>
          <button type="button" className="drawer-close" aria-label="Close" onClick={close}>
            <svg
              className="icon iconSize-18"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              aria-hidden
            >
              <path d="M6 6l12 12M18 6 6 18" strokeLinecap="round" />
            </svg>
          </button>
        </header>

        <form
          ref={formRef}
          key={formKey}
          id="createLeadDrawerForm"
          className="popup-body-form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            void submit();
          }}
        >
          {isAdmin ? <CreateFormEditLink objectKey={definition.key} /> : null}
          {error ? (
            <Alert tone="danger">
              {error}
              {openLead ? (
                <>
                  {' '}
                  <Link href={objectRecordPath(definition.key, openLead.id)}>
                    Open {openLead.name ?? 'the lead'}
                  </Link>
                </>
              ) : null}
            </Alert>
          ) : null}

          <fieldset className="cf-with lc-with">
            <legend className="cf-with__h">Associate {definition.singularLabel} with</legend>
            <div className="cf-with__row">
              {(
                [
                  ['contact', 'Contact'],
                  ['company', 'Company'],
                ] as const
              ).map(([value, label]) => (
                <label key={value} className="cf-radio">
                  <input
                    type="radio"
                    name="leadCreateWith"
                    value={value}
                    checked={kind === value}
                    onChange={() => {
                      setKind(value);
                      pick(null);
                    }}
                  />
                  <span>{label}</span>
                </label>
              ))}
            </div>
          </fieldset>
          <div className="field">
            <label htmlFor="leadCreate-record">
              Associate record<span className="crm-text-danger"> *</span>
            </label>
            <RecordSearchInput
              key={kind}
              id="leadCreate-record"
              type={kind}
              value={record}
              onPick={pick}
            />
          </div>
          {dup && !openLead ? (
            <Alert tone="warning">
              {leadDuplicateText(kind, definition.singularLabel, dup)}{' '}
              <Link href={objectRecordPath(definition.key, dup.id)}>
                Open {dup.name || `the ${definition.singularLabel.toLowerCase()}`}
              </Link>
            </Alert>
          ) : null}
          <hr className="cf-hr lc-hr" />

          <div className={cn('cf-lockbox lc-lockbox', locked && 'is-locked')}>
            {locked ? (
              <p className="cf-lockbox__msg">Start by selecting an associate record.</p>
            ) : null}
            <div className="crm-d-grid crm-gap-3">
              <div className="field">
                <label htmlFor={`leadCreate-${nameField}`}>
                  {nameDef?.label ?? 'Lead Name'}
                  <span className="crm-text-danger"> *</span>
                </label>
                <input
                  className="input"
                  id={`leadCreate-${nameField}`}
                  autoComplete="off"
                  maxLength={191}
                  disabled={locked}
                  value={(values[nameField] as string | undefined) ?? ''}
                  onChange={(e) => setValue(nameField, e.target.value)}
                />
              </div>
              {definition.hasPipeline && pipelines.length > 0 ? (
                <>
                  <div className="field">
                    <label htmlFor="leadCreate-pipeline">Pipeline</label>
                    <select
                      className="input"
                      id="leadCreate-pipeline"
                      disabled={locked}
                      value={pipeline?.id ?? ''}
                      onChange={(e) => {
                        const next = pipelines.find((p) => p.id === e.target.value);
                        setPipelineId(e.target.value);
                        setStageId(next?.stages.find((s) => !s.archived)?.id ?? '');
                      }}
                    >
                      {pipelines.map((p) => (
                        <option key={p.id} value={p.id}>
                          {p.name}
                        </option>
                      ))}
                    </select>
                  </div>
                  <div className="field">
                    <label htmlFor="leadCreate-stage">Lead stage</label>
                    <select
                      className="input"
                      id="leadCreate-stage"
                      disabled={locked}
                      value={stageId}
                      onChange={(e) => setStageId(e.target.value)}
                    >
                      {stages.map((s) => (
                        <option key={s.id} value={s.id}>
                          {s.name}
                        </option>
                      ))}
                    </select>
                  </div>
                </>
              ) : null}
              {fieldDefs.map((def) => (
                <div key={def.id} className="field">
                  <label htmlFor={`leadCreate-${def.name}`} title={def.description ?? undefined}>
                    {def.label}
                    {def.required ? <span className="crm-text-danger"> *</span> : null}
                  </label>
                  <fieldset disabled={locked} className="lc-fieldset">
                    <CustomFieldInput
                      def={def}
                      id={`leadCreate-${def.name}`}
                      value={values[def.name] ?? (def.type === 'multiselect' ? [] : '')}
                      onChange={(v) => setValue(def.name, v)}
                    />
                  </fieldset>
                </div>
              ))}
            </div>
          </div>
        </form>

        <footer className="drawer-footer">
          <div className="drawer-footer-actions cc-foot">
            <button
              type="submit"
              form="createLeadDrawerForm"
              className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
              disabled={busy || locked}
            >
              <span className="btn-crm__spinner" aria-hidden />
              <span className="btn-crm__text">Create {definition.singularLabel}</span>
            </button>
            <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
              Cancel
            </button>
          </div>
        </footer>
      </aside>
      {dialog}
    </>
  );
}
