'use client';

// Convert to deal (HUB-340 on top of the API's HUB-339): create a new deal from the lead or link
// an existing one. The server's dry run is shown first; Convert sends one idempotency key made
// when the drawer opens, so a double click or a retry after a lost answer makes one deal. Ends on
// the deal's link, or "Already converted" with the link when the lead was converted before.
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmModal, ModalHeader } from '@/components/crm/FormDrawer';
import type { AssociationCandidate } from '@/features/associations/types';
import { RecordSearchInput } from '@/features/associations/ui/RecordSearchInput';
import { listPipelines, type Pipeline } from '@/features/pipelines/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { addDays, toZoned } from '@/lib/utils/timezone';
import { convertLead, listLinkedRecords } from '../../api.client';
import { conflictRecordOf, convertLinksText } from '../../leads';
import type { ConvertLeadBody, ConvertLeadPlan, ObjectRecord } from '../../types';

type Owner = { userId: string; name: string; active: boolean };

/** LD2: one "Associated with" chip (26 Nov design `convertModal`, list-page.js:5131-5139). */
export interface ConvertChip {
  type: 'contact' | 'company';
  id: string;
  name: string;
}

/** LD2: the design's default close date, 30 days from today in the user's zone (:5134). */
export function defaultCloseDate(timeZone: string, now = new Date()): string {
  return addDays(toZoned(now, timeZone).day, 30);
}

/**
 * LD2: the chips the deal would get, as the API's `leadLinksOf`: the primary company first
 * ("Company · Primary"), then every contact. A lead without a primary company shows none.
 */
export function convertChips(
  companies: Array<{ id: string; name: string | null; isPrimary: boolean }>,
  contacts: Array<{ id: string; name: string | null }>,
): ConvertChip[] {
  const company = companies.find((c) => c.isPrimary);
  return [
    ...(company
      ? [{ type: 'company' as const, id: company.id, name: company.name || 'Company' }]
      : []),
    ...contacts.map((c) => ({ type: 'contact' as const, id: c.id, name: c.name || 'Contact' })),
  ];
}
type Step =
  | { kind: 'form' }
  | { kind: 'preview'; plan: ConvertLeadPlan }
  | { kind: 'done'; deal: { id: string; name: string }; already: boolean };

const newKey = () =>
  typeof crypto !== 'undefined' && 'randomUUID' in crypto
    ? crypto.randomUUID()
    : `${Date.now()}-${Math.random().toString(36).slice(2)}`;

export function ConvertLeadDrawer({
  open,
  objectKey,
  lead,
  owners,
  onClose,
  onConverted,
}: {
  open: boolean;
  objectKey: string;
  lead: ObjectRecord;
  owners: Owner[];
  onClose: () => void;
  /** The lead after converting (now in Qualified, with its deal). */
  onConverted: (lead: ObjectRecord | null) => void;
}) {
  const [mode, setMode] = useState<'create' | 'link'>('create');
  const [name, setName] = useState('');
  const [pipelineId, setPipelineId] = useState('');
  const [stageId, setStageId] = useState('');
  const [ownerId, setOwnerId] = useState('');
  const [amount, setAmount] = useState('');
  const [closeDate, setCloseDate] = useState('');
  const [deal, setDeal] = useState<AssociationCandidate | null>(null);
  const [pipelines, setPipelines] = useState<Pipeline[]>([]);
  const [step, setStep] = useState<Step>({ kind: 'form' });
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const prefs = useUserPrefs();
  /** LD2: the lead's company and contacts as chips; null while loading or when they failed. */
  const [chips, setChips] = useState<ConvertChip[] | null>(null);
  /** LD2: chips removed (`type:id`): sent as `skipLinks`. */
  const [removed, setRemoved] = useState<Set<string>>(new Set());
  /** One key per opening: every Convert of this opening is the same request. */
  const keyRef = useRef(newKey());

  const [wasOpen, setWasOpen] = useState(open);
  if (open !== wasOpen) {
    setWasOpen(open);
    if (open) {
      keyRef.current = newKey();
      setMode('create');
      setName(lead.displayName ?? '');
      setOwnerId(lead.owner?.id ?? '');
      setAmount('');
      setCloseDate(defaultCloseDate(prefs.timeZone));
      setRemoved(new Set());
      setDeal(null);
      setError(null);
      setStep(
        lead.convertedDealId
          ? { kind: 'done', deal: { id: lead.convertedDealId, name: 'the deal' }, already: true }
          : { kind: 'form' },
      );
    }
  }

  useEffect(() => {
    if (!open) return;
    let alive = true;
    listPipelines().then(
      (list) => {
        if (!alive) return;
        const live = list.filter((p) => !p.archived);
        setPipelines(live);
        const first = live[0];
        setPipelineId(first?.id ?? '');
        setStageId(first?.stages.find((s) => !s.archived && s.stageType === 'open')?.id ?? '');
      },
      () => alive && setPipelines([]),
    );
    return () => {
      alive = false;
    };
  }, [open]);

  // LD2: the chips. A failed load keeps the sentence below (the API still links them all).
  useEffect(() => {
    if (!open) return;
    let alive = true;
    setChips(null);
    const linked = (toType: string) =>
      listLinkedRecords({ fromType: objectKey, fromId: lead.id, toType, limit: 100 });
    Promise.all([linked('company'), linked('contact')]).then(
      ([companies, contacts]) => alive && setChips(convertChips(companies.data, contacts.data)),
      () => alive && setChips(null),
    );
    return () => {
      alive = false;
    };
  }, [open, objectKey, lead.id]);
  const chipKey = (c: ConvertChip) => `${c.type}:${c.id}`;
  const shownChips = (chips ?? []).filter((c) => !removed.has(chipKey(c)));

  const pipeline = pipelines.find((p) => p.id === pipelineId);
  const stages = (pipeline?.stages ?? []).filter((s) => !s.archived);
  const activeOwners = owners.filter((o) => o.active);
  // A lead owned by someone no longer active (common after the HubSpot import) shows "No owner";
  // send that, since the API refuses an inactive owner for the new deal.
  const shownOwnerId = activeOwners.some((o) => o.userId === ownerId) ? ownerId : '';

  const body = (): ConvertLeadBody | null => {
    if (mode === 'link') return deal ? { mode: 'link', dealId: deal.id } : null;
    return {
      mode: 'create',
      deal: {
        ...(name.trim() ? { name: name.trim() } : {}),
        ...(pipelineId ? { pipelineId } : {}),
        ...(stageId ? { stageId } : {}),
        ownerId: shownOwnerId || null,
        ...(amount.trim() ? { amount: amount.trim() } : {}),
        ...(closeDate ? { closeDate } : {}),
      },
      ...(removed.size
        ? {
            skipLinks: (chips ?? [])
              .filter((c) => removed.has(chipKey(c)))
              .map((c) => ({ type: c.type, id: c.id })),
          }
        : {}),
    };
  };

  /** A 409 for a lead converted meanwhile (or before): show its deal. */
  const handle = (err: unknown) => {
    const conflict = conflictRecordOf(err);
    if (conflict?.record.type === 'deal') {
      setStep({
        kind: 'done',
        deal: { id: conflict.record.id, name: conflict.record.name ?? 'the deal' },
        already: true,
      });
      return;
    }
    setError(errorText(err));
  };

  const preview = async () => {
    const b = body();
    if (!b) {
      setError('Pick the deal to link.');
      return;
    }
    if (busy) return;
    setBusy(true);
    setError(null);
    try {
      const result = await convertLead(objectKey, lead.id, b, { dryRun: true });
      if (result.plan) setStep({ kind: 'preview', plan: result.plan });
    } catch (err) {
      handle(err);
    } finally {
      setBusy(false);
    }
  };

  const convert = async () => {
    const b = body();
    if (!b || busy) return;
    setBusy(true);
    setError(null);
    try {
      const result = await convertLead(objectKey, lead.id, b, {
        idempotencyKey: keyRef.current,
      });
      if (result.deal) setStep({ kind: 'done', deal: result.deal, already: false });
      onConverted(result.lead);
    } catch (err) {
      handle(err);
    } finally {
      setBusy(false);
    }
  };

  const ownerName = (id: string | null) =>
    id ? (owners.find((o) => o.userId === id)?.name ?? 'Unknown owner') : 'No owner';
  const pipelineName = (id: string | null) => pipelines.find((p) => p.id === id)?.name ?? '—';
  const stageName = (pid: string | null, sid: string | null) =>
    pipelines.find((p) => p.id === pid)?.stages.find((s) => s.id === sid)?.name ?? '—';
  const close = busy ? () => {} : onClose;
  const leadName = lead.displayName || 'this lead';

  return (
    <CrmModal id="leadConvertModal" open={open} onClose={close} drawer>
      <ModalHeader id="leadConvertModal" title={`Convert ${leadName} to a deal`} onClose={close} />
      <div className="modal__body">
        {error ? <Alert tone="danger">{error}</Alert> : null}

        {step.kind === 'done' ? (
          <div className="crm-about-contact crm-gap-3" role="status">
            <p className="crm-fw-semibold">
              {step.already ? 'Already converted' : `Converted to ${step.deal.name}`}
            </p>
            <p className="crm-text-body-secondary">
              {step.already
                ? 'This lead was converted to a deal before; a lead converts once.'
                : 'The lead is now qualified and linked to the deal.'}
            </p>
            <Link className="btn-crm btn-crm--primary btn-crm--sm" href={`/deals/${step.deal.id}`}>
              Open deal
            </Link>
          </div>
        ) : step.kind === 'preview' ? (
          <div className="crm-about-contact crm-gap-3">
            <p className="crm-text-body-secondary">
              Nothing is saved yet. Check what happens, then convert.
            </p>
            <dl className="evl-card__meta">
              <div>
                <dt>{step.plan.mode === 'create' ? 'New deal:' : 'Link deal:'}</dt>
                <dd>{step.plan.deal.name}</dd>
              </div>
              <div>
                <dt>Pipeline / stage:</dt>
                <dd>
                  {pipelineName(step.plan.deal.pipelineId)} ·{' '}
                  {stageName(step.plan.deal.pipelineId, step.plan.deal.stageId)}
                </dd>
              </div>
              <div>
                <dt>Owner:</dt>
                <dd>{ownerName(step.plan.deal.ownerId)}</dd>
              </div>
              <div>
                <dt>Amount:</dt>
                <dd>{step.plan.deal.amount ?? '—'}</dd>
              </div>
              <div>
                <dt>Close date:</dt>
                <dd>{step.plan.deal.closeDate ?? '—'}</dd>
              </div>
              <div>
                <dt>Linked to:</dt>
                <dd>{convertLinksText(step.plan.links, objectKey)}</dd>
              </div>
              <div>
                <dt>Lead stage:</dt>
                <dd>
                  {step.plan.leadStage.from?.name ?? '—'} → {step.plan.leadStage.to.name ?? '—'}
                </dd>
              </div>
              {step.plan.copiedFields.length ? (
                <div>
                  <dt>Copied from the lead:</dt>
                  <dd>{step.plan.copiedFields.map((f) => f.to).join(', ')}</dd>
                </div>
              ) : null}
            </dl>
          </div>
        ) : (
          <>
            <div className="field">
              <span className="field__label">Deal</span>
              <div style={{ display: 'flex', gap: 16 }}>
                {(['create', 'link'] as const).map((m) => (
                  <label key={m} className="su-check">
                    <input
                      type="radio"
                      name="leadConvertMode"
                      checked={mode === m}
                      onChange={() => setMode(m)}
                    />
                    <span>{m === 'create' ? 'Create a new deal' : 'Link an existing deal'}</span>
                  </label>
                ))}
              </div>
            </div>
            {mode === 'link' ? (
              <div className="field crm-mt-3">
                <label className="field__label" htmlFor="leadConvertDeal">
                  Deal *
                </label>
                <RecordSearchInput id="leadConvertDeal" type="deal" value={deal} onPick={setDeal} />
              </div>
            ) : (
              <div className="form-grid crm-mt-3">
                <div className="field span-2">
                  <label className="field__label" htmlFor="leadConvertName">
                    Deal name
                  </label>
                  <input
                    className="input"
                    id="leadConvertName"
                    maxLength={191}
                    value={name}
                    placeholder={lead.displayName ?? ''}
                    onChange={(e) => setName(e.target.value)}
                  />
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="leadConvertPipeline">
                    Pipeline
                  </label>
                  <select
                    className="input"
                    id="leadConvertPipeline"
                    value={pipelineId}
                    onChange={(e) => {
                      const next = pipelines.find((p) => p.id === e.target.value);
                      setPipelineId(e.target.value);
                      setStageId(
                        next?.stages.find((s) => !s.archived && s.stageType === 'open')?.id ?? '',
                      );
                    }}
                  >
                    {pipelines.map((p) => (
                      <option key={p.id} value={p.id}>
                        {p.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="leadConvertStage">
                    Deal stage
                  </label>
                  <select
                    className="input"
                    id="leadConvertStage"
                    value={stageId}
                    onChange={(e) => setStageId(e.target.value)}
                  >
                    {stages.map((s) => (
                      <option key={s.id} value={s.id}>
                        {s.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="leadConvertOwner">
                    Deal owner
                  </label>
                  <select
                    className="input"
                    id="leadConvertOwner"
                    value={shownOwnerId}
                    onChange={(e) => setOwnerId(e.target.value)}
                  >
                    <option value="">No owner</option>
                    {activeOwners.map((o) => (
                      <option key={o.userId} value={o.userId}>
                        {o.name}
                      </option>
                    ))}
                  </select>
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="leadConvertAmount">
                    Amount
                  </label>
                  <input
                    className="input"
                    id="leadConvertAmount"
                    inputMode="decimal"
                    placeholder="From the lead's open deal amount"
                    value={amount}
                    onChange={(e) => setAmount(e.target.value)}
                  />
                </div>
                <div className="field">
                  <label className="field__label" htmlFor="leadConvertClose">
                    Close date
                  </label>
                  <input
                    className="input"
                    id="leadConvertClose"
                    type="date"
                    value={closeDate}
                    onChange={(e) => setCloseDate(e.target.value)}
                  />
                </div>
              </div>
            )}
            {mode === 'create' && chips ? (
              // LD2: the design's "Associated with" chips; × leaves one off the deal.
              <div className="field crm-mt-3">
                <span className="field__label">Associated with</span>
                <div className="lp-x-pills">
                  {shownChips.length ? (
                    shownChips.map((c) => (
                      <span key={chipKey(c)} className="lp-x-pill">
                        <span>
                          <span className="lp-x-pill__k">
                            {c.type === 'company' ? 'Company · Primary' : 'Contact'}
                          </span>{' '}
                          {c.name}
                        </span>
                        <button
                          type="button"
                          className="lp-x-pill__x"
                          aria-label={`Remove ${c.name}`}
                          onClick={() => setRemoved((cur) => new Set(cur).add(chipKey(c)))}
                        >
                          ×
                        </button>
                      </span>
                    ))
                  ) : (
                    <span className="crm-text-body-secondary">No associations</span>
                  )}
                </div>
              </div>
            ) : null}
            <p className="crm-text-body-secondary crm-mt-3">
              {mode === 'create' && chips
                ? 'The deal is linked to the lead and the records above, and the lead moves to Qualified.'
                : 'The deal is linked to the lead, its contacts and its company, and the lead moves to Qualified.'}
            </p>
          </>
        )}
      </div>
      <div className="modal__footer">
        {step.kind === 'done' ? (
          <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
            Close
          </button>
        ) : (
          <>
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={busy}
              onClick={step.kind === 'preview' ? () => setStep({ kind: 'form' }) : close}
            >
              {step.kind === 'preview' ? 'Back' : 'Cancel'}
            </button>
            <button
              type="button"
              className={cn('btn-crm btn-crm--primary', busy && 'is-loading')}
              disabled={busy}
              aria-busy={busy}
              onClick={() => void (step.kind === 'preview' ? convert() : preview())}
            >
              {step.kind === 'preview' ? 'Convert' : 'Preview'}
            </button>
          </>
        )}
      </div>
    </CrmModal>
  );
}
