'use client';

import { useEffect, useMemo, useRef, useState, type FormEvent } from 'react';
import { API_BASE_PATH } from '@/config/constants';
import { dateLocaleOf, groupSlotsByDay, redirectUrlOf } from '@/features/meetings/scheduler';
import type { BookingDateFormat } from '@/features/meetings/types';
import { TimeZonePicker } from '@/features/meetings/ui/calendar/TimeZonePicker';
import {
  MonthCalendar,
  type MonthCalendarClasses,
} from '@/features/meetings/ui/scheduler/MonthCalendar';
import { toZoned } from '@/lib/utils/timezone';
import { guestEmails, isoDay, monthRange, splitName } from '../publicBook';
import { BookAvatar, CaptchaBox, WelcomeArt } from './PublicBookParts';
import '@/styles/crm-public-book.css';

/**
 * QA #385: the public booking page of a scheduling page (/book/:slug, no sign-in). The design has
 * no buyer-facing page, so it is drawn simply in the app's style: pick a meeting length, a day and
 * a time, enter name and email (and the page's questions), confirm. Times are shown in the
 * visitor's time zone.
 *
 * HUB-662: the page's picture, the round robin welcome screen (email first), guests, the consent
 * boxes, CAPTCHA, and the date and time format; `?email=` / `?name=` (or HubSpot's `firstName`,
 * `lastName`) fill in the form.
 */

type MeetingType = { id: string; name: string; durationMinutes: number };
type Question = { id: string; label: string; type?: 'text' | 'textarea'; required?: boolean };
type PublicPage = {
  slug: string;
  title: string;
  description: string | null;
  hostName: string;
  timeZone: string;
  addMeet: boolean;
  questions: Question[];
  meetingTypes: MeetingType[];
  /** After booking, go here instead of the confirmation (an http(s) address). */
  redirectUrl?: string | null;
  slots: string[];
  // HUB-662 (optional: an older API leaves them out)
  companyName?: string;
  image?: { kind: 'organizer' | 'company' | 'custom'; url: string | null };
  welcome?: {
    title: string;
    description: string;
    image: 'default' | 'company' | 'custom';
    imageUrl: string | null;
  } | null;
  language?: 'browser' | 'en';
  dateFormat?: BookingDateFormat;
  allowGuests?: boolean;
  captchaSiteKey?: string | null;
  consent?: {
    communicateText: string;
    communicateCheckbox: string;
    processText: string;
    processCheckbox: string;
    privacyPolicyText: string;
  } | null;
};

const DAY_MS = 86_400_000;
/** MT-13: months a visitor can page ahead, as the editor's preview. */
const MAX_MONTHS_AHEAD = 12;

/** MT-13: the month calendar is the editor preview's (MonthCalendar), in this page's style. */
const CALENDAR: MonthCalendarClasses = {
  row: 'crm-public-book__month',
  nav: 'crm-public-book__month-nav',
  weekdays: 'crm-public-book__weekdays',
  dates: 'crm-public-book__dates',
  empty: 'crm-public-book__date-empty',
};

/** The first day of the month (local midnight) that `at` falls in, in `timeZone`. */
function monthIn(at: Date, timeZone: string): Date {
  const [y, m] = toZoned(at, timeZone).day.split('-').map(Number);
  return new Date(y!, m! - 1, 1);
}

const visitorZone = () => {
  try {
    return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
  } catch {
    return 'UTC';
  }
};

/**
 * Slot and confirmation times carry am/pm with the browser's settings: a 24-hour locale showed
 * "3:45" and "22:30". HUB-662: a page's own date and time format writes them its country's way.
 */
const timeOf = (hour12: boolean | undefined): Intl.DateTimeFormatOptions =>
  hour12
    ? { hour: 'numeric', minute: '2-digit', hour12: true }
    : { hour: 'numeric', minute: '2-digit' };

function fmt(
  iso: string,
  timeZone: string,
  options: Intl.DateTimeFormatOptions,
  locale?: string,
): string {
  try {
    return new Date(iso).toLocaleString(locale, { timeZone, ...options });
  } catch {
    return iso;
  }
}

const newKey = () =>
  `bk-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`.slice(0, 64);

async function fetchPage(
  slug: string,
  type: string | undefined,
  range: { from: Date; to: Date },
  /** HUB-662 (QA round 1 BUG-11): the link's invitee, for the description's {name} / {email}. */
  invitee: { name: string; email: string },
): Promise<PublicPage> {
  const qs = new URLSearchParams();
  if (type) qs.set('type', type);
  if (invitee.name) qs.set('name', invitee.name);
  if (invitee.email) qs.set('email', invitee.email);
  qs.set('from', range.from.toISOString());
  qs.set('to', range.to.toISOString());
  const url = `${API_BASE_PATH}/book/${encodeURIComponent(slug)}?${qs}`;
  const res = await fetch(url, { credentials: 'omit', headers: { Accept: 'application/json' } });
  if (res.status === 404) throw new Error('This booking page is unavailable or was removed.');
  if (res.status === 429) throw new Error('Too many requests. Please try again in a minute.');
  if (!res.ok) throw new Error('Could not load this booking page.');
  return (await res.json()) as PublicPage;
}

export function PublicBookView({
  slug,
  initialStart,
  initialTypeId,
  proposalId,
  initialName = '',
  initialEmail = '',
}: {
  slug: string;
  initialStart?: string;
  initialTypeId?: string;
  /** Prefs from Gmail propose-times (`?proposal=`). */
  proposalId?: string;
  /** HUB-662: known details from the link (`?name=`, `?email=`). */
  initialName?: string;
  initialEmail?: string;
}) {
  // MT-14 (M-08): the visitor's zone, which they may change (kept on this page only).
  const homeZone = useMemo(visitorZone, []);
  const [zone, setZone] = useState(homeZone);
  const [page, setPage] = useState<PublicPage | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [typeId, setTypeId] = useState(initialTypeId || '');
  /** MT-13 (M-06): the month shown (its first day); null until the page loads. */
  const [month, setMonth] = useState<Date | null>(null);
  const [day, setDay] = useState('');
  const [selectedStart, setSelectedStart] = useState('');
  const [details, setDetails] = useState(false);
  // MT-15 (M-15): First and Last name, as HubSpot's booking form.
  const [firstName, setFirstName] = useState(() => splitName(initialName).first);
  const [lastName, setLastName] = useState(() => splitName(initialName).last);
  const [email, setEmail] = useState(initialEmail);
  const [answers, setAnswers] = useState<Record<string, string>>({});
  // HUB-662: the welcome screen passed, guests, consent boxes, CAPTCHA token.
  const [welcomed, setWelcomed] = useState(false);
  const [guestsOpen, setGuestsOpen] = useState(false);
  const [guestsText, setGuestsText] = useState('');
  const [consentProcess, setConsentProcess] = useState(false);
  const [consentCommunicate, setConsentCommunicate] = useState(false);
  const [captchaToken, setCaptchaToken] = useState<string | null>(null);
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState<{
    start: string;
    meetingUrl: string | null;
    hostName: string | null;
    redirectTo: string | null;
  } | null>(null);
  const key = useRef(newKey());
  const request = useRef(0);
  const invitee = useMemo(
    () => ({ name: initialName, email: initialEmail }),
    [initialName, initialEmail],
  );

  // First load: the page, then the free times of its first (or the linked) meeting type.
  useEffect(() => {
    const hint = initialStart ? new Date(initialStart) : null;
    const start =
      hint && !Number.isNaN(hint.getTime())
        ? new Date(Math.max(Date.now(), hint.getTime() - DAY_MS))
        : new Date();
    const shown = monthIn(start, homeZone);
    const range = monthRange(shown, homeZone);
    const id = ++request.current;
    void (async () => {
      try {
        let data = await fetchPage(slug, initialTypeId, range, invitee);
        const first = initialTypeId || data.meetingTypes[0]?.id || '';
        if (first && first !== initialTypeId) data = await fetchPage(slug, first, range, invitee);
        if (id !== request.current) return;
        setPage(data);
        setTypeId(first);
        setMonth(shown);
        // #490: one view per page load (slot paging doesn't count); never blocks the page.
        void fetch(`${API_BASE_PATH}/book/${encodeURIComponent(slug)}/view`, {
          method: 'POST',
          credentials: 'omit',
        }).catch(() => {});
        if (initialStart && data.slots.includes(initialStart)) {
          setSelectedStart(initialStart);
          setDetails(true);
        }
      } catch (err) {
        if (id === request.current) {
          setError(err instanceof Error ? err.message : 'Could not load this booking page.');
        }
      }
    })();
  }, [slug, initialStart, initialTypeId, invitee, homeZone]);

  const load = async (nextType: string, nextMonth: Date, nextZone = zone) => {
    const id = ++request.current;
    setBusy(true);
    setError(null);
    try {
      const data = await fetchPage(slug, nextType, monthRange(nextMonth, nextZone), invitee);
      if (id !== request.current) return;
      setPage(data);
      setTypeId(nextType);
      setMonth(nextMonth);
      setDay('');
      setSelectedStart('');
    } catch (err) {
      if (id === request.current)
        setError(err instanceof Error ? err.message : 'Could not load times.');
    } finally {
      if (id === request.current) setBusy(false);
    }
  };

  const { locale, hour12 } = dateLocaleOf(page?.dateFormat);
  const TIME = timeOf(hour12);
  const guests = guestEmails(guestsText);
  const days = useMemo(() => groupSlotsByDay(page?.slots ?? [], zone), [page, zone]);
  const shownDay = days.find((d) => d.day === day) ?? days[0];
  const type = page?.meetingTypes.find((t) => t.id === typeId);

  async function onBook(e: FormEvent) {
    e.preventDefault();
    if (!page || !typeId || !selectedStart) return;
    setBusy(true);
    setError(null);
    try {
      const res = await fetch(`${API_BASE_PATH}/book/${encodeURIComponent(slug)}`, {
        method: 'POST',
        credentials: 'omit',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
          'Idempotency-Key': key.current,
        },
        body: JSON.stringify({
          typeId,
          start: selectedStart,
          firstName: firstName.trim(),
          ...(lastName.trim() && { lastName: lastName.trim() }),
          email: email.trim().toLowerCase(),
          answers: Object.fromEntries(Object.entries(answers).filter(([, v]) => v.trim() !== '')),
          ...(page.allowGuests && guests.emails.length ? { guests: guests.emails } : {}),
          ...(page.consent
            ? { consent: { process: consentProcess, communicate: consentCommunicate } }
            : {}),
          ...(captchaToken ? { captchaToken } : {}),
          ...(proposalId ? { proposalId } : {}),
          context: {
            pageUrl: window.location.href,
            ...(document.referrer ? { referrer: document.referrer } : {}),
          },
        }),
      });
      const body = (await res.json().catch(() => ({}))) as {
        start?: string;
        meetingUrl?: string | null;
        hostName?: string | null;
        message?: string;
        /** The API's errors are `{ error: { code, message } }`. */
        error?: string | { message?: string };
      };
      if (!res.ok) {
        // A CAPTCHA answer is good for one try.
        if (page.captchaSiteKey) setCaptchaToken(null);
        if (res.status === 409) {
          // the time was taken meanwhile: a new key for the next try, and fresh times
          key.current = newKey();
          setDetails(false);
          if (month) void load(typeId, month);
        }
        const apiMessage = typeof body.error === 'object' ? body.error.message : body.error;
        throw new Error(body.message || apiMessage || 'That time is no longer available.');
      }
      // The page's "Redirect to another page"; the confirmation shows while the browser goes.
      const redirectTo = page.redirectUrl ? redirectUrlOf(page.redirectUrl) : null;
      setDone({
        start: body.start || selectedStart,
        meetingUrl: body.meetingUrl ?? null,
        hostName: body.hostName ?? null,
        redirectTo,
      });
      if (redirectTo) window.location.assign(redirectTo);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Could not book this time.');
    } finally {
      setBusy(false);
    }
  }

  if (error && !page) {
    return (
      <main className="crm-public-book">
        <div className="crm-public-book__card">
          <h1>Booking unavailable</h1>
          <p>{error}</p>
        </div>
      </main>
    );
  }

  if (!page) {
    return (
      <main className="crm-public-book">
        <div className="crm-public-book__card">
          <p>Loading…</p>
        </div>
      </main>
    );
  }

  const lang = page.language === 'en' ? 'en' : undefined;

  if (done) {
    return (
      <main className="crm-public-book" lang={lang}>
        <div className="crm-public-book__card crm-public-book__done">
          <div className="crm-public-book__check" aria-hidden="true">
            ✓
          </div>
          <h1>Booking confirmed</h1>
          <p>
            You’re booked with {done.hostName || page.hostName}.
            <br />
            An invitation has been emailed to you.
          </p>
          <p className="crm-public-book__when">
            {fmt(
              done.start,
              zone,
              {
                weekday: 'long',
                month: 'long',
                day: 'numeric',
                year: 'numeric',
              },
              locale,
            )}
            <br />
            {fmt(done.start, zone, TIME, locale)}
            {type ? ` · ${type.durationMinutes} min` : ''}
          </p>
          {done.meetingUrl ? (
            <p>
              <a href={done.meetingUrl} target="_blank" rel="noreferrer">
                Join with Google Meet
              </a>
            </p>
          ) : page.addMeet ? (
            <p className="crm-public-book__hint">A Google Meet link will be in the invite.</p>
          ) : null}
          {done.redirectTo ? (
            <p className="crm-public-book__hint">
              You’ll be redirected to your selected page. <a href={done.redirectTo}>Continue</a>
            </p>
          ) : null}
        </div>
      </main>
    );
  }

  const thisMonth = monthIn(new Date(), zone);
  const lastMonth = new Date(thisMonth.getFullYear(), thisMonth.getMonth() + MAX_MONTHS_AHEAD, 1);
  const openDays = new Set(days.map((d) => d.day));
  const pickedDay = shownDay ? new Date(`${shownDay.day}T00:00:00`) : null;
  const today = (() => {
    const [y, m, d] = toZoned(new Date(), zone).day.split('-').map(Number);
    return new Date(y!, m! - 1, d!);
  })();
  // MT-15 (M-07): the heading is the visitor-facing scheduling title (the meeting type's name the
  // editor saves), never the page's internal name.
  const heading =
    type?.name || page.meetingTypes[0]?.name || `Find a time to meet with ${page.hostName}`;

  // HUB-662: round robin with Prioritize contact owner asks for the email first.
  if (page.welcome && !welcomed) {
    const welcome = page.welcome;
    return (
      <main className="crm-public-book" lang={lang}>
        <form
          className="crm-public-book__card crm-public-book__welcome"
          onSubmit={(e) => {
            e.preventDefault();
            if (email.trim()) setWelcomed(true);
          }}
        >
          <WelcomeArt
            kind={welcome.image}
            url={welcome.imageUrl}
            companyName={page.companyName ?? ''}
          />
          <h1>{welcome.title}</h1>
          <p className="crm-public-book__desc">{welcome.description}</p>
          <label className="crm-public-book__field">
            <span>Enter email address *</span>
            <input
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
              maxLength={191}
              autoComplete="email"
              autoFocus
            />
          </label>
          <button type="submit" className="crm-public-book__primary" disabled={!email.trim()}>
            Start booking
          </button>
        </form>
      </main>
    );
  }

  return (
    <main className="crm-public-book" lang={lang}>
      <div className="crm-public-book__card crm-public-book__card--wide">
        {page.image ? (
          <BookAvatar
            kind={page.image.kind}
            url={page.image.url}
            name={page.image.kind === 'company' ? (page.companyName ?? '') : page.hostName}
          />
        ) : null}
        <h1>{heading}</h1>
        {page.description ? <p className="crm-public-book__desc">{page.description}</p> : null}

        {details && selectedStart ? (
          <form className="crm-public-book__form" onSubmit={(e) => void onBook(e)}>
            <p className="crm-public-book__picked">
              <strong>
                {fmt(
                  selectedStart,
                  zone,
                  { weekday: 'long', month: 'long', day: 'numeric' },
                  locale,
                )}
                , {fmt(selectedStart, zone, TIME, locale)}
              </strong>
              {type ? ` · ${type.durationMinutes} min` : ''}{' '}
              <button
                type="button"
                className="crm-public-book__link"
                onClick={() => setDetails(false)}
              >
                Change
              </button>
            </p>
            <h2 className="crm-public-book__step">Your information</h2>
            <div className="crm-public-book__names">
              <label className="crm-public-book__field">
                <span>First name *</span>
                <input
                  value={firstName}
                  onChange={(e) => setFirstName(e.target.value)}
                  required
                  maxLength={191}
                  autoComplete="given-name"
                  autoFocus
                />
              </label>
              <label className="crm-public-book__field">
                <span>Last name *</span>
                <input
                  value={lastName}
                  onChange={(e) => setLastName(e.target.value)}
                  required
                  maxLength={191}
                  autoComplete="family-name"
                />
              </label>
            </div>
            <label className="crm-public-book__field">
              <span>Email *</span>
              <input
                type="email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                required
                maxLength={191}
                autoComplete="email"
              />
            </label>
            {page.questions.map((q) => (
              <label key={q.id} className="crm-public-book__field">
                <span>
                  {q.label}
                  {q.required ? ' *' : ''}
                </span>
                {q.type === 'textarea' ? (
                  <textarea
                    rows={3}
                    value={answers[q.id] || ''}
                    required={Boolean(q.required)}
                    maxLength={5000}
                    onChange={(e) => setAnswers((prev) => ({ ...prev, [q.id]: e.target.value }))}
                  />
                ) : (
                  <input
                    value={answers[q.id] || ''}
                    required={Boolean(q.required)}
                    maxLength={5000}
                    onChange={(e) => setAnswers((prev) => ({ ...prev, [q.id]: e.target.value }))}
                  />
                )}
              </label>
            ))}
            {page.allowGuests ? (
              guestsOpen ? (
                <label className="crm-public-book__field">
                  <span>Guest email addresses</span>
                  <textarea
                    rows={2}
                    value={guestsText}
                    placeholder="name@company.com, other@company.com"
                    onChange={(e) => setGuestsText(e.target.value)}
                  />
                  {guests.error ? (
                    <small className="crm-public-book__error">{guests.error}</small>
                  ) : (
                    <small className="crm-public-book__hint">
                      Up to 10 people; they get the invitation too.
                    </small>
                  )}
                </label>
              ) : (
                <p>
                  <button
                    type="button"
                    className="crm-public-book__link"
                    onClick={() => setGuestsOpen(true)}
                  >
                    + Add guests
                  </button>
                </p>
              )
            ) : null}
            {page.consent ? (
              <div className="crm-public-book__consent">
                <p>{page.consent.communicateText}</p>
                <label>
                  <input
                    type="checkbox"
                    checked={consentCommunicate}
                    onChange={(e) => setConsentCommunicate(e.target.checked)}
                  />{' '}
                  {page.consent.communicateCheckbox}
                </label>
                <p>{page.consent.processText}</p>
                <label>
                  <input
                    type="checkbox"
                    required
                    checked={consentProcess}
                    onChange={(e) => setConsentProcess(e.target.checked)}
                  />{' '}
                  {page.consent.processCheckbox} *
                </label>
                <p className="crm-public-book__hint">{page.consent.privacyPolicyText}</p>
              </div>
            ) : null}
            {page.captchaSiteKey ? (
              <CaptchaBox siteKey={page.captchaSiteKey} onToken={setCaptchaToken} />
            ) : null}
            {error ? <p className="crm-public-book__error">{error}</p> : null}
            <button
              type="submit"
              disabled={
                busy ||
                !firstName.trim() ||
                !lastName.trim() ||
                !email.trim() ||
                Boolean(guests.error) ||
                (page.consent ? !consentProcess : false) ||
                (page.captchaSiteKey ? !captchaToken : false)
              }
            >
              {busy ? 'Booking…' : 'Confirm'}
            </button>
          </form>
        ) : (
          <div className="crm-public-book__cal">
            <div className="crm-public-book__cal-left">
              {month ? (
                <MonthCalendar
                  month={month}
                  onMonth={(m) => void load(typeId, m)}
                  canPrev={!busy && month > thisMonth}
                  canNext={!busy && month < lastMonth}
                  selected={pickedDay}
                  today={today}
                  isOpen={(date) => openDays.has(isoDay(date))}
                  onPick={(date) => setDay(isoDay(date))}
                  classes={CALENDAR}
                  prevIcon="‹"
                  nextIcon="›"
                />
              ) : null}
            </div>
            <div className="crm-public-book__cal-right">
              <h2 className="crm-public-book__step">How long do you need?</h2>
              {page.meetingTypes.length > 1 ? (
                <div
                  className="crm-public-book__chips"
                  role="radiogroup"
                  aria-label="Meeting length"
                >
                  {page.meetingTypes.map((t) => (
                    <button
                      key={t.id}
                      type="button"
                      role="radio"
                      aria-checked={t.id === typeId}
                      className={t.id === typeId ? 'is-selected' : undefined}
                      disabled={busy}
                      onClick={() => t.id !== typeId && month && void load(t.id, month)}
                    >
                      {t.durationMinutes} mins
                    </button>
                  ))}
                </div>
              ) : type ? (
                <p className="crm-public-book__hint">{type.durationMinutes} mins</p>
              ) : null}
              {/* MT-14 (M-08, M-14): the visitor's time zone, HubSpot's names; nothing is saved. */}
              <div className="crm-public-book__zone">
                <TimeZonePicker
                  timeZone={zone}
                  homeZone={homeZone}
                  title="Select your time zone"
                  places
                  onChoose={(z) => {
                    setZone(z);
                    if (month) void load(typeId, month, z);
                  }}
                />
              </div>
              <h2 className="crm-public-book__step">What time works best?</h2>
              {error ? <p className="crm-public-book__error">{error}</p> : null}
              {busy ? (
                <p className="crm-public-book__hint">Loading times…</p>
              ) : !shownDay ? (
                <p className="crm-public-book__hint">
                  No open times this month. Try the next month.
                </p>
              ) : (
                <>
                  <p className="crm-public-book__hint">
                    Showing times for{' '}
                    {new Date(`${shownDay.day}T12:00:00Z`).toLocaleDateString(locale, {
                      month: 'long',
                      day: 'numeric',
                      year: 'numeric',
                      timeZone: 'UTC',
                    })}
                  </p>
                  <div
                    className="crm-public-book__slots"
                    role="listbox"
                    aria-label="Available times"
                  >
                    {shownDay.slots.map((slot) => (
                      <button
                        key={slot}
                        type="button"
                        role="option"
                        aria-selected={slot === selectedStart}
                        className={slot === selectedStart ? 'is-selected' : undefined}
                        onClick={() => {
                          setSelectedStart(slot);
                          setDetails(true);
                          setError(null);
                        }}
                      >
                        {fmt(slot, zone, TIME, locale)}
                      </button>
                    ))}
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </div>
    </main>
  );
}
