import type { FormEvent, ReactNode } from 'react';
import { formatQuoteDate, formatQuoteMoney } from '../format';
import { formatPublicQty, publicQuoteNotice, type PublicQuote } from '../public';

/**
 * DL10 (HUB-403): what the buyer sees on /q/:token. The design has no buyer page, so it is drawn
 * in the public booking page's style. Stateless, so it renders in tests; PublicQuoteView owns
 * loading and the answers.
 */

export type AnswerMode = 'none' | 'accept' | 'decline';

export interface PublicQuoteBodyProps {
  quote: PublicQuote;
  pdfUrl: string;
  /** Terms HTML already made safe for the page ('' renders nothing). */
  termsHtml: string;
  mode: AnswerMode;
  name: string;
  email: string;
  reason: string;
  busy: boolean;
  error: string | null;
  onMode: (mode: AnswerMode) => void;
  onName: (value: string) => void;
  onEmail: (value: string) => void;
  onReason: (value: string) => void;
  onSubmit: (event: FormEvent) => void;
}

function Money({ value, currency }: { value: string; currency: string }) {
  return <>{formatQuoteMoney(value, currency)}</>;
}

export function PublicQuoteBody(props: PublicQuoteBodyProps) {
  const { quote, mode } = props;
  const notice = publicQuoteNotice(quote);
  const canAnswer = quote.canAccept || quote.canDecline;
  const lines = [...quote.lineItems].sort((a, b) => a.position - b.position);

  let answer: ReactNode = null;
  if (canAnswer && mode === 'accept') {
    answer = (
      <form className="crm-public-quote__form" onSubmit={props.onSubmit}>
        <h2 className="crm-public-quote__step">Accept this quote</h2>
        <label className="crm-public-quote__field">
          Your full name
          <input
            value={props.name}
            onChange={(e) => props.onName(e.target.value)}
            maxLength={191}
            autoComplete="name"
            required
            autoFocus
          />
        </label>
        <label className="crm-public-quote__field">
          Email (optional)
          <input
            type="email"
            value={props.email}
            onChange={(e) => props.onEmail(e.target.value)}
            maxLength={191}
            autoComplete="email"
          />
        </label>
        {props.error ? <p className="crm-public-quote__error">{props.error}</p> : null}
        <div className="crm-public-quote__buttons">
          <button type="button" className="is-secondary" onClick={() => props.onMode('none')}>
            Cancel
          </button>
          <button type="submit" disabled={props.busy || !props.name.trim()}>
            {props.busy ? 'Accepting…' : 'Accept quote'}
          </button>
        </div>
      </form>
    );
  } else if (canAnswer && mode === 'decline') {
    answer = (
      <form className="crm-public-quote__form" onSubmit={props.onSubmit}>
        <h2 className="crm-public-quote__step">Decline this quote</h2>
        <label className="crm-public-quote__field">
          Reason (optional)
          <textarea
            value={props.reason}
            onChange={(e) => props.onReason(e.target.value)}
            maxLength={500}
            rows={3}
            autoFocus
          />
        </label>
        {props.error ? <p className="crm-public-quote__error">{props.error}</p> : null}
        <div className="crm-public-quote__buttons">
          <button type="button" className="is-secondary" onClick={() => props.onMode('none')}>
            Cancel
          </button>
          <button type="submit" className="is-danger" disabled={props.busy}>
            {props.busy ? 'Declining…' : 'Decline quote'}
          </button>
        </div>
      </form>
    );
  } else if (canAnswer) {
    answer = (
      <div className="crm-public-quote__buttons">
        {quote.canDecline ? (
          <button type="button" className="is-secondary" onClick={() => props.onMode('decline')}>
            Decline
          </button>
        ) : null}
        {quote.canAccept ? (
          <button type="button" onClick={() => props.onMode('accept')}>
            Accept
          </button>
        ) : null}
      </div>
    );
  }

  return (
    <div className="crm-public-quote__card">
      <header className="crm-public-quote__head">
        <div>
          {quote.seller ? (
            <>
              <p className="crm-public-quote__seller">{quote.seller.businessName}</p>
              <p className="crm-public-quote__muted">
                {quote.seller.ownerName} ·{' '}
                <a href={`mailto:${quote.seller.ownerEmail}`}>{quote.seller.ownerEmail}</a>
              </p>
            </>
          ) : null}
        </div>
        <div className="crm-public-quote__meta">
          <p>{quote.numberDisplay}</p>
          {quote.expiresAt ? (
            <p className="crm-public-quote__muted">Expires {formatQuoteDate(quote.expiresAt)}</p>
          ) : null}
        </div>
      </header>

      <h1>{quote.title}</h1>
      {notice ? (
        <p className={`crm-public-quote__notice is-${notice.tone}`} role="status">
          {notice.text}
        </p>
      ) : null}
      {quote.buyerMessage ? (
        <p className="crm-public-quote__message">{quote.buyerMessage}</p>
      ) : null}

      <div className="crm-public-quote__table-wrap">
        <table className="crm-public-quote__table">
          <thead>
            <tr>
              <th scope="col">Item</th>
              <th scope="col" className="is-num">
                Qty
              </th>
              <th scope="col" className="is-num">
                Unit price
              </th>
              <th scope="col" className="is-num">
                Total
              </th>
            </tr>
          </thead>
          <tbody>
            {lines.map((line) => (
              <tr key={line.position}>
                <td>
                  <span className="crm-public-quote__item">{line.name}</span>
                  {line.description ? (
                    <span className="crm-public-quote__muted crm-public-quote__desc">
                      {line.description}
                    </span>
                  ) : null}
                </td>
                <td className="is-num">{formatPublicQty(line.quantity)}</td>
                <td className="is-num">
                  <Money value={line.unitPrice} currency={quote.currency} />
                </td>
                <td className="is-num">
                  <Money value={line.lineTotal} currency={quote.currency} />
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <dl className="crm-public-quote__totals">
        <dt>Subtotal</dt>
        <dd>
          <Money value={quote.subtotal} currency={quote.currency} />
        </dd>
        {Number(quote.discountTotal) ? (
          <>
            <dt>Discount</dt>
            <dd>
              −<Money value={quote.discountTotal} currency={quote.currency} />
            </dd>
          </>
        ) : null}
        {Number(quote.taxTotal) ? (
          <>
            <dt>Tax</dt>
            <dd>
              <Money value={quote.taxTotal} currency={quote.currency} />
            </dd>
          </>
        ) : null}
        <dt className="is-total">Total</dt>
        <dd className="is-total">
          <Money value={quote.total} currency={quote.currency} />
        </dd>
      </dl>

      {props.termsHtml ? (
        <section className="crm-public-quote__terms">
          <h2 className="crm-public-quote__step">Terms</h2>
          <div dangerouslySetInnerHTML={{ __html: props.termsHtml }} />
        </section>
      ) : null}

      <footer className="crm-public-quote__foot">
        <a className="crm-public-quote__pdf" href={props.pdfUrl} download>
          Download PDF
        </a>
        {answer}
      </footer>
    </div>
  );
}
