'use client';

import Link from 'next/link';
import { useRouter, useSearchParams } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert } from '@/components/crm/Alert';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { CustomSelect, type CustomSelectOption } from '@/components/crm/CustomSelect';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { getCompany } from '@/features/companies/api.client';
import type { Company } from '@/features/companies/types';
import { getDeal, listDeals } from '@/features/deals/api.client';
import type { Deal } from '@/features/deals/types';
import { ProductSearch } from '@/features/products/ui/ProductSearch';
import { errorText } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import {
  createQuote,
  deleteQuote,
  getQuote,
  listQuoteTemplates,
  runQuoteAction,
  updateQuote,
  type QuoteAction,
} from '../api.client';
import {
  QUOTE_STATUS_META,
  cleanNumber,
  dateInputInDays,
  dateInputToIso,
  emptyLine,
  formatQuoteDate,
  formatQuoteMoney,
  isQuoteEditable,
  isoToDateInput,
  lineFromApi,
  lineFromProduct,
  lineMath,
  lineToInput,
  quoteActions,
  termsToText,
  textToTerms,
  totalsOf,
  type LineDraft,
} from '../format';
import type { CreateQuoteBody, Quote, QuoteTemplate } from '../types';
import { QuoteStatusBadge } from './QuoteStatusBadge';
import { useRecordNames } from './useRecordNames';

interface FormState {
  title: string;
  dealId: string | null;
  contactId: string | null;
  companyId: string | null;
  templateId: string | null;
  expires: string;
  terms: string;
  buyerMessage: string;
}

const EMPTY_FORM: FormState = {
  title: '',
  dealId: null,
  contactId: null,
  companyId: null,
  templateId: null,
  expires: '',
  terms: '',
  buyerMessage: '',
};

function formFromQuote(q: Quote): FormState {
  return {
    title: q.title,
    dealId: q.dealId,
    contactId: q.contactId,
    companyId: q.companyId,
    templateId: q.templateId,
    expires: isoToDateInput(q.expiresAt),
    terms: termsToText(q.termsHtml),
    buyerMessage: q.buyerMessage ?? '',
  };
}

function XIcon() {
  return (
    <svg
      className="icon iconSize-16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      aria-hidden
    >
      <path d="M6 6l12 12M18 6 6 18" />
    </svg>
  );
}

function DownloadIcon() {
  return (
    <svg
      className="icon iconSize-16"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.8"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden
    >
      <path d="M12 4v11m-5-5 5 5 5-5M5 20h14" />
    </svg>
  );
}

/**
 * Quote editor (design quote-editor.php, PDF p.20): details and line items on the left with live
 * totals, a live PDF preview on the right. `quoteId` undefined = a new quote; `?dealId`,
 * `?companyId` and `?contactId` prefill it (Quotes card on Deal / Company records).
 */
export function QuoteEditorView({ quoteId }: { quoteId?: string }) {
  const me = useCurrentUser();
  const router = useRouter();
  const params = useSearchParams();
  const toast = useToast();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const isNew = !quoteId;
  const canWrite = me.role !== 'read_only';

  const [quote, setQuote] = useState<Quote | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [form, setForm] = useState<FormState>(EMPTY_FORM);
  const [lines, setLines] = useState<LineDraft[]>([]);
  /** HUB-398: the "Add from product library" search is open. */
  const [libraryOpen, setLibraryOpen] = useState(false);
  const [termsDirty, setTermsDirty] = useState(false);
  const [dealChanged, setDealChanged] = useState(false);
  const [dirty, setDirty] = useState(false);
  const [busy, setBusy] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [titleInvalid, setTitleInvalid] = useState(false);
  const [templates, setTemplates] = useState<QuoteTemplate[]>([]);
  const [deal, setDeal] = useState<Deal | null>(null);
  const [company, setCompany] = useState<Company | null>(null);
  const [dealText, setDealText] = useState('');
  const [dealOptions, setDealOptions] = useState<Deal[]>([]);
  const prefilled = useRef(false);

  // --- load ---------------------------------------------------------------------------------
  useEffect(() => {
    listQuoteTemplates().then(
      (res) => setTemplates(res.data),
      () => setTemplates([]),
    );
  }, []);

  useEffect(() => {
    if (!quoteId) return;
    let alive = true;
    getQuote(quoteId).then(
      (q) => {
        if (!alive) return;
        setQuote(q);
        setForm(formFromQuote(q));
        setLines(q.lineItems.map(lineFromApi));
        setDirty(false);
        setTermsDirty(false);
        setDealChanged(false);
      },
      (err: unknown) => alive && setLoadError(errorText(err)),
    );
    return () => {
      alive = false;
    };
  }, [quoteId]);

  // New quote: prefill from the record it was started on.
  useEffect(() => {
    if (!isNew || prefilled.current) return;
    prefilled.current = true;
    setForm({
      ...EMPTY_FORM,
      dealId: params.get('dealId'),
      companyId: params.get('companyId'),
      contactId: params.get('contactId'),
      expires: dateInputInDays(30),
    });
  }, [isNew, params]);

  // The selected deal: its name, contacts, companies and currency.
  useEffect(() => {
    if (!form.dealId) {
      setDeal(null);
      return;
    }
    if (deal?.id === form.dealId) return;
    let alive = true;
    getDeal(form.dealId).then(
      (d) => {
        if (!alive) return;
        setDeal(d);
        setDealText(d.name);
        if (isNew) {
          setForm((f) => ({
            ...f,
            title: f.title || d.name,
            companyId:
              f.companyId ?? d.companies.find((c) => c.isPrimary)?.id ?? d.companies[0]?.id ?? null,
            contactId: f.contactId ?? d.contacts[0]?.id ?? null,
          }));
          // The API seeds one line from the deal amount when none are sent; show it here too.
          setLines((ls) =>
            ls.length === 0 && d.amount != null
              ? [{ ...emptyLine(), name: d.name, unitPrice: d.amount }]
              : ls,
          );
        }
      },
      () => alive && setDeal(null),
    );
    return () => {
      alive = false;
    };
  }, [form.dealId, deal?.id, isNew]);

  useEffect(() => {
    if (!form.companyId) {
      setCompany(null);
      return;
    }
    if (company?.id === form.companyId) return;
    let alive = true;
    getCompany(form.companyId).then(
      (c) => alive && setCompany(c),
      () => alive && setCompany(null),
    );
    return () => {
      alive = false;
    };
  }, [form.companyId, company?.id]);

  // Deal search for the Deal field (design: `<input list="dealList">`).
  useEffect(() => {
    const text = dealText.trim();
    if (deal && text === deal.name) return;
    let alive = true;
    const controller = new AbortController();
    const t = setTimeout(() => {
      listDeals({ limit: 20, search: text || undefined }, { signal: controller.signal }).then(
        (res) => alive && setDealOptions(res.data),
        () => undefined,
      );
    }, 250);
    return () => {
      alive = false;
      clearTimeout(t);
      controller.abort();
    };
  }, [dealText, deal]);

  const { contacts: contactNames } = useRecordNames([], form.contactId ? [form.contactId] : []);

  // --- derived ------------------------------------------------------------------------------
  const status = quote?.status ?? 'draft';
  const editable = canWrite && isQuoteEditable(status);
  const actions = quoteActions(status, {
    canWrite,
    isAdmin: me.role === 'admin',
    isOwner: quote ? quote.ownerId === me.user.id : true,
  });
  const totals = useMemo(() => totalsOf(lines), [lines]);
  const currency =
    quote && !dealChanged
      ? quote.currency
      : (deal?.currency ?? quote?.currency ?? me.business.currency ?? 'USD');
  const money = (n: number | string) => formatQuoteMoney(n, currency);

  const contactOptions = useMemo<CustomSelectOption[]>(() => {
    const seen = new Map<string, CustomSelectOption>();
    for (const c of deal?.contacts ?? []) {
      seen.set(c.id, {
        value: c.id,
        label: c.name || c.email || 'Unnamed contact',
        sub: c.email ?? undefined,
      });
    }
    for (const c of company?.contacts ?? []) {
      if (!seen.has(c.id))
        seen.set(c.id, { value: c.id, label: c.name, sub: c.email ?? undefined });
    }
    if (form.contactId && !seen.has(form.contactId)) {
      seen.set(form.contactId, {
        value: form.contactId,
        label: contactNames[form.contactId] ?? 'Loading…',
      });
    }
    return [...seen.values()];
  }, [deal, company, form.contactId, contactNames]);

  const contactLabel = form.contactId
    ? (contactOptions.find((o) => o.value === form.contactId)?.label ?? '')
    : '';
  const companyName = company?.name ?? deal?.companies.find((c) => c.id === form.companyId)?.name;
  const template = templates.find((t) => t.id === form.templateId) ?? null;

  // --- edits --------------------------------------------------------------------------------
  const patch = (next: Partial<FormState>) => {
    setForm((f) => ({ ...f, ...next }));
    setDirty(true);
  };

  const pickDealText = (text: string) => {
    setDealText(text);
    if (!text.trim()) {
      if (form.dealId) {
        patch({ dealId: null });
        setDealChanged(true);
      }
      return;
    }
    const match = dealOptions.find((d) => d.name === text);
    if (match && match.id !== form.dealId) {
      setDeal(match);
      setDealChanged(true);
      setForm((f) => ({
        ...f,
        dealId: match.id,
        title: f.title || match.name,
        companyId:
          match.companies.find((c) => c.isPrimary)?.id ?? match.companies[0]?.id ?? f.companyId,
        contactId:
          f.contactId && match.contacts.some((c) => c.id === f.contactId)
            ? f.contactId
            : (match.contacts[0]?.id ?? f.contactId),
      }));
      if (isNew && match.amount != null) {
        const amount = match.amount;
        setLines((ls) =>
          ls.length === 0 ? [{ ...emptyLine(), name: match.name, unitPrice: amount }] : ls,
        );
      }
      setDirty(true);
    }
  };

  const pickTemplate = (id: string) => {
    const t = templates.find((x) => x.id === id) ?? null;
    setForm((f) => ({
      ...f,
      templateId: t?.id ?? null,
      title: f.title || t?.title || '',
      terms: t?.termsHtml && !f.terms ? termsToText(t.termsHtml) : f.terms,
      expires:
        t?.defaultExpiryDays && !f.expires ? dateInputInDays(t.defaultExpiryDays) : f.expires,
    }));
    if (t?.termsHtml) setTermsDirty(true);
    setDirty(true);
  };

  const setLine = (key: string, next: Partial<LineDraft>) => {
    setLines((ls) => ls.map((l) => (l.key === key ? { ...l, ...next } : l)));
    setDirty(true);
  };
  const removeLine = (key: string) => {
    setLines((ls) => ls.filter((l) => l.key !== key));
    setDirty(true);
  };
  const addLine = () => {
    setLines((ls) => [...ls, emptyLine()]);
    setDirty(true);
  };

  // --- save / actions -----------------------------------------------------------------------
  const body = useCallback((): CreateQuoteBody => {
    const out: CreateQuoteBody = {
      title: form.title.trim(),
      dealId: form.dealId,
      contactId: form.contactId,
      companyId: form.companyId,
      templateId: form.templateId,
      expiresAt: dateInputToIso(form.expires),
      buyerMessage: form.buyerMessage.trim() || null,
      lineItems: lines.map(lineToInput),
    };
    if (termsDirty || isNew) {
      const html = textToTerms(form.terms);
      if (html !== null || !isNew) out.termsHtml = html;
    }
    if (dealChanged && deal) out.currency = deal.currency;
    return out;
  }, [form, lines, termsDirty, isNew, dealChanged, deal]);

  const validate = (): boolean => {
    if (!form.title.trim()) {
      setTitleInvalid(true);
      setError('Add a quote title.');
      return false;
    }
    setTitleInvalid(false);
    return true;
  };

  /** Saves the form; returns the saved quote (or null on error). */
  const save = async (): Promise<Quote | null> => {
    if (!validate()) return null;
    setError(null);
    try {
      if (isNew) {
        const created = await createQuote(body());
        setDirty(false);
        toast(`Quote ${created.numberDisplay} created`, 'success');
        router.replace(`/quotes/${created.id}`);
        return created;
      }
      const updated = await updateQuote(quote!.id, body());
      setQuote(updated);
      setLines(updated.lineItems.map(lineFromApi));
      setDirty(false);
      setTermsDirty(false);
      setDealChanged(false);
      return updated;
    } catch (err) {
      setError(errorText(err));
      return null;
    }
  };

  const onSave = async () => {
    setBusy('save');
    const saved = await save();
    if (saved && !isNew) toast('Quote saved', 'success');
    setBusy(null);
  };

  const ACTION_DONE: Record<QuoteAction, string> = {
    'submit-approval': 'Quote submitted for approval',
    approve: 'Quote approved. It can be published now.',
    publish: 'Quote published',
    'mark-paid': 'Quote marked as paid',
  };

  const onAction = async (action: QuoteAction) => {
    if (!quote) return;
    if (action === 'publish') {
      const ok = await confirm({
        title: 'Publish quote?',
        message:
          'Publishing locks the quote and creates a public link the buyer can open, accept or decline.',
        confirmLabel: 'Publish',
      });
      if (!ok) return;
    }
    setBusy(action);
    setError(null);
    try {
      if (dirty && isQuoteEditable(quote.status)) {
        const saved = await save();
        if (!saved) return;
      }
      const next = await runQuoteAction(quote.id, action);
      setQuote(next);
      setForm(formFromQuote(next));
      setLines(next.lineItems.map(lineFromApi));
      setDirty(false);
      toast(ACTION_DONE[action], 'success');
    } catch (err) {
      setError(errorText(err));
    } finally {
      setBusy(null);
    }
  };

  const onDelete = async () => {
    if (!quote) return;
    const ok = await confirm({
      title: 'Delete quote?',
      message: `${quote.numberDisplay} will be deleted${quote.publicUrl ? ' and its public link will stop working' : ''}.`,
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    setBusy('delete');
    try {
      await deleteQuote(quote.id);
      toast('Quote deleted', 'success');
      router.push('/quotes');
    } catch (err) {
      setError(errorText(err));
      setBusy(null);
    }
  };

  const copyLink = () => {
    if (!quote?.publicUrl) return;
    void navigator.clipboard?.writeText(quote.publicUrl).then(
      () => toast('Public link copied', 'success'),
      () => toast('Could not copy the link', 'danger'),
    );
  };

  /** Design: Download PDF prints only the preview (sales.css `body.is-printing-quote`). */
  const printPreview = () => {
    document.body.classList.add('is-printing-quote');
    const done = () => {
      document.body.classList.remove('is-printing-quote');
      window.removeEventListener('afterprint', done);
    };
    window.addEventListener('afterprint', done);
    window.print();
  };

  // --- render -------------------------------------------------------------------------------
  if (loadError) {
    return (
      <>
        <div className="editor-bar">
          <Link className="btn-crm btn-crm--outline btn-crm--sm" href="/quotes">
            <CrmIcon name="chevron-left" className="iconSize-16" />
            Back to quotes
          </Link>
          <h1 className="editor-bar__title">Quote</h1>
        </div>
        <Alert tone="danger">{loadError}</Alert>
      </>
    );
  }
  if (!isNew && !quote) {
    return <p className="crm-text-muted">Loading quote…</p>;
  }

  const anyBusy = busy !== null;
  const noLines = lines.length === 0;
  const primaryAction = actions.publish
    ? 'publish'
    : actions.approve
      ? 'approve'
      : actions.markPaid
        ? 'mark-paid'
        : null;

  return (
    <>
      <div className="editor-bar">
        <Link className="btn-crm btn-crm--outline btn-crm--sm" href="/quotes">
          <CrmIcon name="chevron-left" className="iconSize-16" />
          Back to quotes
        </Link>
        <h1 className="editor-bar__title">
          {quote ? `Quote ${quote.numberDisplay}` : 'New quote'}
        </h1>
        <span data-quote-status>
          <QuoteStatusBadge status={status} />
        </span>
        <div className="editor-bar__actions">
          {quote?.publicUrl ? (
            <button type="button" className="btn-crm btn-crm--outline" onClick={copyLink}>
              <CrmIcon name="copy" className="iconSize-16" />
              Copy public link
            </button>
          ) : null}
          {quote?.publicUrl ? (
            <a
              className="btn-crm btn-crm--outline"
              href={`${quote.publicUrl}/pdf`}
              target="_blank"
              rel="noreferrer"
            >
              <DownloadIcon />
              Download PDF
            </a>
          ) : (
            <button type="button" className="btn-crm btn-crm--outline" onClick={printPreview}>
              <DownloadIcon />
              Download PDF
            </button>
          )}
          {actions.remove && quote ? (
            <button
              type="button"
              className="btn-crm btn-crm--outline"
              disabled={anyBusy}
              onClick={() => void onDelete()}
            >
              Delete
            </button>
          ) : null}
          {isNew ? (
            canWrite ? (
              <button
                type="button"
                className="btn-crm btn-crm--primary"
                disabled={anyBusy}
                onClick={() => void onSave()}
              >
                {busy === 'save' ? 'Saving…' : 'Save draft'}
              </button>
            ) : null
          ) : (
            <>
              {actions.save ? (
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  disabled={anyBusy || !dirty}
                  onClick={() => void onSave()}
                >
                  {busy === 'save' ? 'Saving…' : 'Save draft'}
                </button>
              ) : null}
              {actions.submitApproval ? (
                <button
                  type="button"
                  className="btn-crm btn-crm--outline"
                  disabled={anyBusy || noLines}
                  title={noLines ? 'Add at least one line item first' : undefined}
                  onClick={() => void onAction('submit-approval')}
                >
                  {busy === 'submit-approval' ? 'Submitting…' : 'Request approval'}
                </button>
              ) : null}
              {actions.awaitingApproval ? (
                <button type="button" className="btn-crm btn-crm--primary" disabled>
                  Approval requested
                </button>
              ) : null}
              {primaryAction ? (
                <button
                  type="button"
                  className="btn-crm btn-crm--primary"
                  disabled={anyBusy || (primaryAction === 'publish' && noLines)}
                  title={
                    primaryAction === 'publish' && noLines
                      ? 'Add at least one line item first'
                      : undefined
                  }
                  onClick={() => void onAction(primaryAction)}
                >
                  {busy === primaryAction
                    ? 'Working…'
                    : primaryAction === 'publish'
                      ? 'Publish quote'
                      : primaryAction === 'approve'
                        ? 'Approve'
                        : 'Mark paid'}
                </button>
              ) : !actions.awaitingApproval && quote ? (
                <button type="button" className="btn-crm btn-crm--primary" disabled>
                  {QUOTE_STATUS_META[status].label}
                </button>
              ) : null}
            </>
          )}
        </div>
      </div>

      {error ? <Alert tone="danger">{error}</Alert> : null}
      {quote?.status === 'pending_approval' ? (
        <Alert tone="warning">
          {actions.approve
            ? 'This quote is waiting for your approval. Once approved it returns to draft and can be published.'
            : 'This quote is waiting for approval from an admin. It can be published once approved.'}
        </Alert>
      ) : null}
      {quote?.publicUrl && (quote.status === 'published' || quote.status === 'expired') ? (
        <Alert tone="info">
          Public link:{' '}
          <a href={quote.publicUrl} target="_blank" rel="noreferrer">
            {quote.publicUrl}
          </a>
          {quote.publishedAt ? ` · published ${formatQuoteDate(quote.publishedAt)}` : ''}
        </Alert>
      ) : null}
      {quote?.signedAt ? (
        <Alert tone="success">
          Signed by {quote.signedName ?? 'the buyer'}
          {quote.signedEmail ? ` (${quote.signedEmail})` : ''} on {formatQuoteDate(quote.signedAt)}.
        </Alert>
      ) : null}
      {quote?.status === 'declined' ? (
        <Alert tone="danger">
          Declined {formatQuoteDate(quote.declinedAt)}
          {quote.declineReason ? `: ${quote.declineReason}` : '.'}
        </Alert>
      ) : null}

      <div className="quote-layout">
        <form
          className="quote-form"
          noValidate
          onSubmit={(e) => {
            e.preventDefault();
            if (editable) void onSave();
          }}
        >
          <section className="sales-card sales-card--pad">
            <div className="form-grid">
              <div className={cn('field span-2', titleInvalid && 'is-invalid')}>
                <label className="field__label" htmlFor="quoteTitle">
                  Quote title
                </label>
                <input
                  id="quoteTitle"
                  className="input"
                  name="title"
                  value={form.title}
                  placeholder="e.g. Northwind Logistics – Routing pilot"
                  required
                  maxLength={191}
                  disabled={!editable}
                  onChange={(e) => {
                    patch({ title: e.target.value });
                    if (e.target.value.trim()) setTitleInvalid(false);
                  }}
                />
                <span className="field__error">This field is required.</span>
              </div>
              <div className="field">
                <label className="field__label" htmlFor="quoteDeal">
                  Deal
                </label>
                <input
                  id="quoteDeal"
                  className="input"
                  name="deal"
                  list="dealList"
                  placeholder="Search deals"
                  autoComplete="off"
                  value={dealText}
                  disabled={!editable}
                  onChange={(e) => pickDealText(e.target.value)}
                />
                <datalist id="dealList">
                  {dealOptions.map((d) => (
                    <option key={d.id} value={d.name}>
                      {d.stage?.name ?? ''}
                    </option>
                  ))}
                </datalist>
              </div>
              <div className="field">
                <label className="field__label">Send to</label>
                <CustomSelect
                  placeholder={contactOptions.length ? 'Select contact' : 'Pick a deal first'}
                  value={form.contactId ?? ''}
                  options={contactOptions}
                  disabled={!editable || contactOptions.length === 0}
                  onChange={(v) => patch({ contactId: v || null })}
                />
              </div>
              <div className="field">
                <label className="field__label" htmlFor="quoteExpires">
                  Valid until
                </label>
                <input
                  id="quoteExpires"
                  className="input"
                  type="date"
                  name="valid_until"
                  value={form.expires}
                  disabled={!editable}
                  onChange={(e) => patch({ expires: e.target.value })}
                />
              </div>
              <div className="field">
                <label className="field__label">Template</label>
                <CustomSelect
                  placeholder={templates.length ? 'No template' : 'No templates yet'}
                  value={form.templateId ?? ''}
                  options={templates.map((t) => ({ value: t.id, label: t.name }))}
                  searchable={templates.length > 8}
                  disabled={!editable || templates.length === 0}
                  onChange={pickTemplate}
                />
              </div>
              <div className="field span-2">
                <label className="field__label" htmlFor="quoteTerms">
                  Terms
                </label>
                <textarea
                  id="quoteTerms"
                  className="input"
                  rows={3}
                  value={form.terms}
                  placeholder="Payment terms and conditions shown on the quote"
                  disabled={!editable}
                  onChange={(e) => {
                    patch({ terms: e.target.value });
                    setTermsDirty(true);
                  }}
                />
              </div>
              <div className="field span-2">
                <label className="field__label" htmlFor="quoteMessage">
                  Comments to buyer
                </label>
                <textarea
                  id="quoteMessage"
                  className="input"
                  rows={2}
                  maxLength={5000}
                  value={form.buyerMessage}
                  disabled={!editable}
                  onChange={(e) => patch({ buyerMessage: e.target.value })}
                />
              </div>
            </div>
          </section>

          <section className="sales-card sales-card--pad" aria-labelledby="linesTitle">
            <div className="crm-d-flex crm-flex-wrap crm-align-items-center crm-justify-content-between crm-gap-2 crm-mb-3">
              <h2 className="sales-card__title" id="linesTitle">
                Line items
              </h2>
              <div className="crm-d-flex crm-gap-2 crm-flex-wrap">
                <button
                  type="button"
                  className="btn-crm btn-crm--ghost btn-crm--sm"
                  disabled={!editable || lines.length >= 100}
                  onClick={addLine}
                >
                  <CrmIcon name="plus" className="iconSize-16" />
                  Custom line
                </button>
                <button
                  type="button"
                  className="btn-crm btn-crm--outline btn-crm--sm"
                  disabled={!editable || lines.length >= 100}
                  aria-expanded={libraryOpen}
                  onClick={() => setLibraryOpen((v) => !v)}
                >
                  <CrmIcon name="plus" className="iconSize-16" />
                  Add from product library
                </button>
              </div>
            </div>
            {libraryOpen && editable ? (
              <div className="crm-mb-3">
                <ProductSearch
                  autoFocus
                  onPick={(product) => {
                    setLines((ls) => [...ls, lineFromProduct(product)]);
                    setDirty(true);
                    setLibraryOpen(false);
                  }}
                />
              </div>
            ) : null}
            {lines.length ? (
              <div className="lines-wrap">
                <table className="lines">
                  <thead>
                    <tr>
                      <th>Product</th>
                      <th>Qty</th>
                      <th>Unit price</th>
                      <th>Discount %</th>
                      <th>Tax %</th>
                      <th>Amount</th>
                      <th>
                        <span className="crm-visually-hidden">Remove</span>
                      </th>
                    </tr>
                  </thead>
                  <tbody>
                    {lines.map((l) => (
                      <tr key={l.key}>
                        <td data-label="Product">
                          <input
                            className="input"
                            value={l.name}
                            aria-label="Product"
                            placeholder="Product or service"
                            maxLength={191}
                            disabled={!editable}
                            onChange={(e) => setLine(l.key, { name: e.target.value })}
                          />
                          {l.sku ? (
                            <span className="crm-fs-8 crm-text-muted">SKU {l.sku}</span>
                          ) : null}
                        </td>
                        <td className="lines__qty" data-label="Qty">
                          <input
                            className="input"
                            inputMode="decimal"
                            value={l.quantity}
                            aria-label="Quantity"
                            disabled={!editable}
                            onChange={(e) =>
                              setLine(l.key, { quantity: cleanNumber(e.target.value) })
                            }
                          />
                        </td>
                        <td className="lines__price" data-label="Unit price">
                          <input
                            className="input"
                            inputMode="decimal"
                            value={l.unitPrice}
                            aria-label="Unit price"
                            disabled={!editable}
                            onChange={(e) =>
                              setLine(l.key, { unitPrice: cleanNumber(e.target.value) })
                            }
                          />
                        </td>
                        <td className="lines__disc" data-label="Discount %">
                          <input
                            className="input"
                            inputMode="decimal"
                            value={l.discountPercent}
                            placeholder={l.discountAmount != null ? money(l.discountAmount) : '0'}
                            aria-label="Discount percent"
                            disabled={!editable}
                            onChange={(e) =>
                              setLine(l.key, { discountPercent: cleanNumber(e.target.value) })
                            }
                          />
                        </td>
                        <td className="lines__disc" data-label="Tax %">
                          <input
                            className="input"
                            inputMode="decimal"
                            value={l.taxPercent}
                            placeholder="0"
                            aria-label="Tax percent"
                            disabled={!editable}
                            onChange={(e) =>
                              setLine(l.key, { taxPercent: cleanNumber(e.target.value) })
                            }
                          />
                        </td>
                        <td className="lines__amount" data-label="Amount">
                          {money(lineMath(l).total)}
                        </td>
                        <td className="lines__rm">
                          {editable ? (
                            <button
                              type="button"
                              className="icon-btn icon-btn--ghost"
                              aria-label={`Remove ${l.name || 'line'}`}
                              onClick={() => removeLine(l.key)}
                            >
                              <XIcon />
                            </button>
                          ) : null}
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <p className="crm-text-muted crm-fs-7 crm-py-3">
                No line items yet. Add products from the library or a custom line.
              </p>
            )}
            <div className="totals">
              <div className="totals__row">
                <span>Subtotal</span>
                <span>{money(totals.subtotal)}</span>
              </div>
              {totals.discount > 0 ? (
                <div className="totals__row">
                  <span>Discounts</span>
                  <span>−{money(totals.discount)}</span>
                </div>
              ) : null}
              {totals.tax > 0 ? (
                <div className="totals__row">
                  <span>Tax</span>
                  <span>{money(totals.tax)}</span>
                </div>
              ) : null}
              <div className="totals__row totals__row--grand">
                <span>Total</span>
                <span>{money(totals.total)}</span>
              </div>
            </div>
          </section>
        </form>

        <aside className="pdf" aria-label="PDF preview">
          <p className="eyebrow-label crm-mb-2">PDF preview</p>
          <div className="pdf__paper">
            <div className="pdf__top">
              <div>
                <p className="pdf__company">{me.business.name}</p>
              </div>
              <div>
                <p className="pdf__word">QUOTE</p>
                <p className="pdf__muted">
                  {quote?.numberDisplay ?? 'New quote'} &middot; valid until{' '}
                  {form.expires ? formatQuoteDate(dateInputToIso(form.expires)) : '—'}
                </p>
              </div>
            </div>
            <div className="pdf__for">
              <p className="crm-fw-bold">Prepared for</p>
              <p>{[contactLabel, companyName].filter(Boolean).join(', ') || '—'}</p>
              {form.title ? <p>{form.title}</p> : null}
            </div>
            <table className="pdf__table">
              <thead>
                <tr>
                  <th>Item</th>
                  <th>Amount</th>
                </tr>
              </thead>
              <tbody>
                {lines.length ? (
                  lines.map((l) => {
                    const m = lineMath(l);
                    return (
                      <tr key={l.key}>
                        <td>
                          {l.name || 'Item'} × {l.quantity || 0}
                          {m.discount > 0 ? (
                            <span className="pdf__muted">
                              {' '}
                              (
                              {l.discountPercent
                                ? `${l.discountPercent}% off`
                                : `${money(m.discount)} off`}
                              )
                            </span>
                          ) : null}
                        </td>
                        <td>{money(m.total)}</td>
                      </tr>
                    );
                  })
                ) : (
                  <tr>
                    <td className="pdf__muted">No items yet</td>
                    <td />
                  </tr>
                )}
              </tbody>
              <tbody>
                <tr className="pdf__sum">
                  <td>Subtotal</td>
                  <td>{money(totals.subtotal)}</td>
                </tr>
                {totals.discount > 0 ? (
                  <tr>
                    <td>Discounts</td>
                    <td>−{money(totals.discount)}</td>
                  </tr>
                ) : null}
                {totals.tax > 0 ? (
                  <tr>
                    <td>Tax</td>
                    <td>{money(totals.tax)}</td>
                  </tr>
                ) : null}
                <tr className="pdf__grand">
                  <td>Total</td>
                  <td>{money(totals.total)}</td>
                </tr>
              </tbody>
            </table>
            {form.buyerMessage.trim() ? (
              <p className="pdf__terms" style={{ whiteSpace: 'pre-line' }}>
                {form.buyerMessage}
              </p>
            ) : null}
            <p className="pdf__terms" style={{ whiteSpace: 'pre-line' }}>
              {form.terms.trim() || (template ? '' : 'No terms added.')}
            </p>
            <div className="pdf__sign">
              <span>Signature</span>
              <span>Date</span>
            </div>
          </div>
        </aside>
      </div>
      {confirmDialog}
    </>
  );
}
