'use client';

import { useEffect, useMemo, useRef, useState, type FormEvent } from 'react';
import { safeRichHtml } from '@/lib/utils/safe-html';
import { answerPublicQuote, loadPublicQuote, publicQuotePdfUrl, type PublicQuote } from '../public';
import { PublicQuoteBody, type AnswerMode } from './PublicQuoteBody';
import '@/styles/crm-public-quote.css';

/** DL10 (HUB-403): the buyer's quote page at /q/:token — view, accept, decline, download PDF. */
export function PublicQuoteView({ token }: { token: string }) {
  const [quote, setQuote] = useState<PublicQuote | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [mode, setMode] = useState<AnswerMode>('none');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [reason, setReason] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const request = useRef(0);

  useEffect(() => {
    const id = ++request.current;
    loadPublicQuote(token).then(
      (data) => {
        if (id === request.current) setQuote(data);
      },
      (err: unknown) => {
        if (id === request.current) {
          setLoadError(err instanceof Error ? err.message : 'Could not load this quote.');
        }
      },
    );
  }, [token]);

  // Terms were sanitized when saved; this also covers anything stored before that.
  const termsHtml = useMemo(() => safeRichHtml(quote?.termsHtml ?? ''), [quote?.termsHtml]);

  const changeMode = (next: AnswerMode) => {
    setMode(next);
    setError(null);
  };

  const onSubmit = (event: FormEvent) => {
    event.preventDefault();
    if (busy || mode === 'none') return;
    setBusy(true);
    setError(null);
    const answer =
      mode === 'accept'
        ? ({ action: 'accept', name, email } as const)
        : ({ action: 'decline', reason } as const);
    answerPublicQuote(token, answer).then(
      (next) => {
        setQuote(next);
        setMode('none');
        setBusy(false);
      },
      (err: unknown) => {
        setError(err instanceof Error ? err.message : 'Could not send your answer.');
        setBusy(false);
      },
    );
  };

  if (!quote) {
    return (
      <main className="crm-public-quote">
        <div className="crm-public-quote__card crm-public-quote__card--narrow">
          {loadError ? (
            <>
              <h1>Quote unavailable</h1>
              <p className="crm-public-quote__error">{loadError}</p>
            </>
          ) : (
            <p className="crm-public-quote__muted">Loading quote…</p>
          )}
        </div>
      </main>
    );
  }

  return (
    <main className="crm-public-quote">
      <PublicQuoteBody
        quote={quote}
        pdfUrl={publicQuotePdfUrl(token)}
        termsHtml={termsHtml}
        mode={mode}
        name={name}
        email={email}
        reason={reason}
        busy={busy}
        error={error}
        onMode={changeMode}
        onName={setName}
        onEmail={setEmail}
        onReason={setReason}
        onSubmit={onSubmit}
      />
    </main>
  );
}
