'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import type { AssociationCandidate } from '@/features/associations/types';
import { amountError, cleanAmount } from '@/features/deals/amount';
import { createDeal } from '@/features/deals/api.client';
import type { CreateDealBody, DealPriority, Pipeline } from '@/features/deals/types';
import { RecordMultiPicker } from '@/features/deals/ui/actions/RecordMultiPicker';
import { SameNameDealsWarning, useSameNameDeals } from '@/features/deals/ui/SameNameDeals';
import { getContact } from '@/features/contacts/api.client';
import { focusFirstInvalid, placeFieldErrors } from '@/features/contacts/ui/actions/fieldErrors';
import {
  CREATE_INLINE_FIELDS,
  createDealProblems,
  dealFieldLabel,
  removedIds,
  withContactCompany,
} from '@/features/deals/dealForm';
import { useDrawerEscape } from '@/features/objects/useDrawerEscape';
import { useUnsavedGuard } from '@/features/objects/useUnsavedGuard';
import { ownerOnCreate } from '@/features/owners/labels';
import type { useFieldAccess } from '@/features/permission-sets/field-access';
import { listPicklistOptions, type PicklistOption } from '@/features/picklists/api.client';
import { useAccountCurrencies } from '@/features/settings/currencies';
import { isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';

export const PRIORITY_OPTIONS: CustomSelectOption[] = [
  { value: 'low', label: 'Low' },
  { value: 'medium', label: 'Medium' },
  { value: 'high', label: 'High' },
];

function parsePriority(raw: string | null): DealPriority | '' {
  return raw === 'low' || raw === 'medium' || raw === 'high' ? raw : '';
}

/** DL4: the inputs the form's errors focus, by field key. */
const FIELD_IDS: Record<string, string> = {
  name: 'deal-name',
  stageId: 'deal-stage',
  amount: 'deal-amount',
  closeDate: 'deal-close-date',
};

/** "Create deal" side panel of the deals list. */

export function CreateDealDrawer({
  open,
  singular,
  pipeline,
  pipelines = [],
  defaultOwnerId,
  ownerOptions,
  access,
  beforeCreate,
  onClose,
  onCreated,
}: {
  /**
   * DL2: asks what creating in the stage needs (its required properties, the Closed Lost reason;
   * `gateDealCreate`) and returns the body to send, or null when the person cancelled.
   */
  beforeCreate?: (
    body: CreateDealBody,
    stage: Pipeline['stages'][number] | undefined,
  ) => Promise<CreateDealBody | null>;
  open: boolean;
  singular: string;
  /** The pipeline the deal goes into (the list's picked pipeline, else the first). */
  pipeline: Pipeline | undefined;
  /** All pipelines so the create form can switch (#353). */
  pipelines?: Pipeline[];
  defaultOwnerId: string;
  ownerOptions: CustomSelectOption[];
  access: ReturnType<typeof useFieldAccess>;
  onClose: () => void;
  onCreated: () => void;
}) {
  const pipelineList = pipelines.length ? pipelines : pipeline ? [pipeline] : [];
  const [pipelineId, setPipelineId] = useState(pipeline?.id ?? '');
  const activePipeline =
    pipelineList.find((p) => p.id === pipelineId) ?? pipelineList[0] ?? pipeline;
  const stageOptions: CustomSelectOption[] = useMemo(
    () =>
      (activePipeline?.stages ?? [])
        .filter((s) => !s.archived)
        .slice()
        .sort((a, b) => a.displayOrder - b.displayOrder)
        .map((s) => ({ value: s.id, label: s.name })),
    [activePipeline],
  );
  const pipelineOptions: CustomSelectOption[] = useMemo(
    () => pipelineList.map((p) => ({ value: p.id, label: p.name })),
    [pipelineList],
  );
  const [saving, setSaving] = useState(false);
  const [formError, setFormError] = useState<string | null>(null);
  const [amountMsg, setAmountMsg] = useState<string | null>(null);
  /** DL4: errors under their fields (name, stage, close date), as the design's create form. */
  const [errors, setErrors] = useState<Record<string, string>>({});
  /** DL4: anything typed or picked since the panel opened (the unsaved-changes guard). */
  const [dirty, setDirty] = useState(false);
  /** DL4: companies the person took off the form: a later contact pick doesn't add them back. */
  const removedCompanies = useRef<Set<string>>(new Set());
  /** The open panel, so a contact lookup from an earlier opening adds nothing. */
  const sessionRef = useRef(0);
  const formRef = useRef<HTMLFormElement>(null);
  const [form, setForm] = useState({
    name: '',
    amount: '',
    currency: 'USD',
    ownerId: '',
    stageId: '',
    closeDate: '',
    priority: '' as DealPriority | '',
    dealType: '',
  });
  const [contacts, setContacts] = useState<AssociationCandidate[]>([]);
  const [companies, setCompanies] = useState<AssociationCandidate[]>([]);
  const [session, setSession] = useState(0);
  const [dealTypes, setDealTypes] = useState<PicklistOption[]>([]);
  const currencies = useAccountCurrencies(form.currency);
  /** Deals that already have the typed name (CRM-BUG, Deals parity #16): a warning only. DL14: the
   * lookup is shared with the record pages' "Add deal > Create new". */
  const sameName = useSameNameDeals(open, form.name);

  useEffect(() => {
    if (!open) return;
    setFormError(null);
    setAmountMsg(null);
    setErrors({});
    setDirty(false);
    removedCompanies.current = new Set();
    setSaving(false);
    const startPipeline = pipeline?.id ?? pipelineList[0]?.id ?? '';
    setPipelineId(startPipeline);
    const startStages = (
      pipelineList.find((p) => p.id === startPipeline) ??
      pipeline ??
      pipelineList[0]
    )?.stages
      ?.filter((s) => !s.archived)
      .slice()
      .sort((a, b) => a.displayOrder - b.displayOrder);
    setForm({
      name: '',
      amount: '',
      currency: 'USD',
      ownerId: defaultOwnerId,
      stageId: startStages?.[0]?.id ?? '',
      closeDate: '',
      priority: '',
      dealType: '',
    });
    setContacts([]);
    setCompanies([]);
    setSession((n) => n + 1);
    sessionRef.current += 1;
    let cancelled = false;
    listPicklistOptions({ objectType: 'deal', field: 'dealType' }).then(
      (list) => {
        if (!cancelled) setDealTypes(list.filter((o) => o.field === 'dealType' && !o.archived));
      },
      () => {
        if (!cancelled) setDealTypes([]);
      },
    );
    return () => {
      cancelled = true;
    };
    // Reset when the panel opens; stage options load with the pipeline.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open]);

  const dealTypeOptions: CustomSelectOption[] = useMemo(
    () => dealTypes.map((o) => ({ value: o.value, label: o.label })),
    [dealTypes],
  );

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    // DL4 (#142/#353): the form's own checks under their fields, the first one focused
    // (create-form.js:276-279).
    const found = createDealProblems({
      name: form.name,
      stageId: form.stageId || stageOptions[0]?.value || '',
      hasStages: stageOptions.length > 0,
    });
    const badAmount = access.locked('amount') ? null : amountError(form.amount);
    if (Object.keys(found).length || badAmount) {
      setErrors(found);
      if (badAmount) setAmountMsg(badAmount);
      showFirstError([...Object.keys(found), ...(badAmount ? ['amount'] : [])]);
      return;
    }
    setSaving(true);
    setFormError(null);
    setErrors({});
    const body: CreateDealBody = {
      name: form.name.trim(),
      pipelineId: activePipeline?.id || undefined,
      stageId: form.stageId || stageOptions[0]?.value || undefined,
      // Fields the permission set locks aren't set on create (HUB-317).
      ...(access.locked('amount') ? {} : { amount: cleanAmount(form.amount) || null }),
      currency: form.currency.trim() || undefined,
      ...ownerOnCreate(form.ownerId, !access.locked('ownerId')),
      ...(access.locked('closeDate') ? {} : { closeDate: form.closeDate || null }),
      ...(access.locked('priority') ? {} : { priority: form.priority || null }),
      ...(access.locked('dealType') ? {} : { dealType: form.dealType || null }),
      ...(contacts.length ? { contactIds: contacts.map((c) => c.id) } : {}),
      ...(companies.length ? { companyIds: companies.map((c) => c.id) } : {}),
    };
    try {
      const stage = activePipeline?.stages.find((s) => s.id === body.stageId);
      const toSend = beforeCreate ? await beforeCreate(body, stage) : body;
      if (!toSend) {
        // Cancelled in the stage's prompt: the form stays as it was.
        setSaving(false);
        return;
      }
      await createDeal(toSend);
      setDirty(false);
      onClose();
      onCreated();
    } catch (err) {
      // DL4 (D11): the API's field errors under the form's fields, in words; the rest (and
      // errors that name no field: a stage rule's 422, 403, the network) in the banner.
      const placed = placeFieldErrors(err, {
        onForm: (key) => CREATE_INLINE_FIELDS.has(key) && !access.locked(key),
        labelOf: (key) => dealFieldLabel(key),
      });
      if (placed && Object.keys(placed.fields).length) {
        const { amount: amountText, ...rest } = placed.fields;
        setErrors(rest);
        if (amountText) setAmountMsg(amountText);
        showFirstError(Object.keys(placed.fields));
      }
      setFormError(
        placed ? placed.form : isApiError(err) ? err.message : 'Could not create the deal.',
      );
      setSaving(false);
    }
  };

  /** Focuses the first field with an error, in form order. */
  const showFirstError = (keys: string[]) => {
    const ids = new Set(keys.map((key) => FIELD_IDS[key] ?? key));
    window.setTimeout(() => focusFirstInvalid(formRef.current, ids));
  };
  const clearError = (key: string) =>
    setErrors((cur) => {
      if (!(key in cur)) return cur;
      const rest = { ...cur };
      delete rest[key];
      return rest;
    });

  // DL4 (D22): closing with something typed or picked asks "Discard unsaved changes?" first.
  const { guard, dialog: unsavedDialog } = useUnsavedGuard(open && 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);
  /** The form's values changed: the panel counts as edited. */
  const edit = (next: (f: typeof form) => typeof form) => {
    setDirty(true);
    setForm(next);
  };

  /**
   * DL4 (#268): a picked contact brings its primary company, as HubSpot. A failed lookup adds
   * nothing (the company can still be picked by hand).
   */
  const pickContacts = (next: AssociationCandidate[]) => {
    setDirty(true);
    const added = next.filter((c) => !contacts.some((p) => p.id === c.id));
    setContacts(next);
    const opened = sessionRef.current;
    for (const contact of added) {
      getContact(contact.id).then(
        (full) => {
          if (sessionRef.current !== opened) return;
          setCompanies((cur) => withContactCompany(cur, removedCompanies.current, full.companies));
        },
        () => {},
      );
    }
  };
  const pickCompanies = (next: AssociationCandidate[]) => {
    setDirty(true);
    for (const id of removedIds(companies, next)) removedCompanies.current.add(id);
    setCompanies(next);
  };

  return (
    <>
      {unsavedDialog}
      {open ? <div className="popup-overlay is-visible" onClick={close} aria-hidden /> : null}
      <aside
        ref={panelRef}
        className={cn('popup-drawer company-create-drawer', open && 'is-open')}
        role="dialog"
        aria-modal={open}
        aria-hidden={!open}
      >
        <header className="drawer-header">
          <div>
            <h2 className="drawer-title">Create {singular.toLowerCase()}</h2>
            <p className="drawer-subtitle">Add a deal to the pipeline</p>
          </div>
          <button type="button" className="drawer-close" aria-label="Close" onClick={close}>
            ×
          </button>
        </header>
        <form ref={formRef} className="popup-body-form" noValidate onSubmit={onSubmit}>
          {formError ? <Alert tone="danger">{formError}</Alert> : null}
          <div className={cn('field', errors.name && 'is-invalid')}>
            <label className="field__label" htmlFor="deal-name">
              Deal name *
            </label>
            <input
              className="input"
              id="deal-name"
              value={form.name}
              aria-invalid={errors.name ? true : undefined}
              aria-describedby={errors.name ? 'deal-name-error' : undefined}
              onChange={(e) => {
                const name = e.target.value;
                edit((f) => ({ ...f, name }));
                clearError('name');
              }}
            />
            {errors.name ? (
              <p className="field__error is-visible" id="deal-name-error" role="alert">
                {errors.name}
              </p>
            ) : null}
          </div>
          <SameNameDealsWarning deals={sameName} />
          {pipelineOptions.length > 0 ? (
            <div className="field">
              <label className="field__label">Pipeline *</label>
              <CustomSelect
                placeholder="Pipeline"
                value={activePipeline?.id ?? ''}
                options={pipelineOptions}
                onChange={(v) => {
                  setDirty(true);
                  clearError('stageId');
                  setPipelineId(v);
                  const next = pipelineList.find((p) => p.id === v);
                  const first =
                    next?.stages
                      .filter((s) => !s.archived)
                      .slice()
                      .sort((a, b) => a.displayOrder - b.displayOrder)[0]?.id ?? '';
                  setForm((f) => ({ ...f, stageId: first }));
                }}
              />
            </div>
          ) : null}
          <div className={cn('field', errors.stageId && 'is-invalid')}>
            <label className="field__label" htmlFor="deal-stage">
              Stage *
            </label>
            <CustomSelect
              id="deal-stage"
              placeholder="Stage"
              value={form.stageId}
              options={stageOptions}
              onChange={(v) => {
                edit((f) => ({ ...f, stageId: v }));
                clearError('stageId');
              }}
            />
            {errors.stageId ? (
              <p className="field__error is-visible" role="alert">
                {errors.stageId}
              </p>
            ) : null}
          </div>
          {access.locked('amount') ? null : (
            <div className={cn('field', amountMsg && 'is-invalid')}>
              <label className="field__label" htmlFor="deal-amount">
                Amount
              </label>
              <input
                className="input"
                id="deal-amount"
                inputMode="decimal"
                value={form.amount}
                aria-invalid={amountMsg ? true : undefined}
                aria-describedby={amountMsg ? 'deal-amount-error' : undefined}
                onChange={(e) => {
                  const amount = e.target.value;
                  edit((f) => ({ ...f, amount }));
                  setAmountMsg(null);
                }}
                onBlur={(e) => setAmountMsg(amountError(e.target.value))}
                placeholder="1500.00"
              />
              {amountMsg ? (
                <p className="field__error is-visible" id="deal-amount-error" role="alert">
                  {amountMsg}
                </p>
              ) : null}
            </div>
          )}
          {access.locked('currency') ? null : (
            <div className="field">
              <label className="field__label" htmlFor="deal-currency">
                Currency
              </label>
              <select
                className="input"
                id="deal-currency"
                value={form.currency}
                onChange={(e) => {
                  const currency = e.target.value;
                  edit((f) => ({ ...f, currency }));
                }}
              >
                {currencies.map((code) => (
                  <option key={code} value={code}>
                    {code}
                  </option>
                ))}
              </select>
            </div>
          )}
          {access.locked('closeDate') ? null : (
            <div className={cn('field', errors.closeDate && 'is-invalid')}>
              <label className="field__label" htmlFor="deal-close-date">
                Close date
              </label>
              <input
                className="input"
                id="deal-close-date"
                type="date"
                value={form.closeDate}
                aria-invalid={errors.closeDate ? true : undefined}
                onChange={(e) => {
                  const closeDate = e.target.value;
                  edit((f) => ({ ...f, closeDate }));
                  clearError('closeDate');
                }}
              />
              {errors.closeDate ? (
                <p className="field__error is-visible" role="alert">
                  {errors.closeDate}
                </p>
              ) : null}
            </div>
          )}
          {access.locked('priority') ? null : (
            <div className="field">
              <label className="field__label">Priority</label>
              <CustomSelect
                placeholder="Priority"
                searchable={false}
                value={form.priority}
                options={PRIORITY_OPTIONS}
                onChange={(v) => edit((f) => ({ ...f, priority: parsePriority(v) }))}
              />
            </div>
          )}
          {access.locked('dealType') ? null : (
            <div className="field">
              <label className="field__label">Deal type</label>
              <CustomSelect
                placeholder="Deal type"
                value={form.dealType}
                options={dealTypeOptions}
                onChange={(v) => edit((f) => ({ ...f, dealType: v }))}
              />
            </div>
          )}
          <div className="field">
            <label className="field__label">Owner</label>
            <CustomSelect
              placeholder="Owner"
              value={form.ownerId}
              options={ownerOptions}
              onChange={(v) => edit((f) => ({ ...f, ownerId: v }))}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="deal-create-contacts">
              Contacts (optional)
            </label>
            <RecordMultiPicker
              key={`contacts-${session}`}
              id="deal-create-contacts"
              type="contact"
              value={contacts}
              onChange={pickContacts}
            />
          </div>
          <div className="field">
            <label className="field__label" htmlFor="deal-create-companies">
              Companies (optional)
            </label>
            <RecordMultiPicker
              key={`companies-${session}`}
              id="deal-create-companies"
              type="company"
              value={companies}
              onChange={pickCompanies}
            />
            {companies.length > 1 ? (
              <p className="crm-fs-8 crm-text-muted crm-mt-2">
                The first company becomes the primary one.
              </p>
            ) : null}
          </div>
          <div className="drawer-actions crm-d-flex crm-gap-2 crm-mt-3">
            <button type="button" className="btn-crm btn-crm--outline" onClick={close}>
              Cancel
            </button>
            <button
              type="submit"
              className={cn('btn-crm btn-crm--primary', saving && 'is-loading')}
              disabled={saving}
            >
              Create
            </button>
          </div>
        </form>
      </aside>
    </>
  );
}
