'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { API_BASE_PATH } from '@/config/constants';
import { dateLocaleOf, groupSlotsByDay } from '@/features/meetings/scheduler';
import type { BookingDateFormat } from '@/features/meetings/types';
import '@/styles/crm-public-book.css';

/**
 * HUB-662: the invitee's cancel and reschedule pages (/book/:slug/cancel/:token and
 * /book/:slug/reschedule/:token), opened from the links in the calendar invitation and the
 * booking emails. No sign-in: the signed token names the meeting. Drawn like the booking page.
 */

type Managed = {
  bookingId: string;
  status: 'scheduled' | 'cancelled';
  slug: string;
  pageTitle: string;
  meetingTitle: string;
  hostName: string | null;
  start: string;
  end: string;
  timeZone: string;
  durationMinutes: number;
  canCancel: boolean;
  canReschedule: boolean;
  dateFormat: BookingDateFormat;
  language: 'browser' | 'en';
  slots: string[];
};

/** Days of free times asked for at once, as the booking page does. */
const RANGE_DAYS = 14;
const DAY_MS = 86_400_000;

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

const base = (token: string) => `${API_BASE_PATH}/book/bookings/${encodeURIComponent(token)}`;

async function readError(res: Response, fallback: string): Promise<string> {
  const body = (await res.json().catch(() => ({}))) as {
    error?: { message?: string } | string;
    message?: string;
  };
  const message = typeof body.error === 'object' ? body.error.message : body.error;
  return message || body.message || fallback;
}

async function fetchBooking(token: string, from: Date): Promise<Managed> {
  const qs = new URLSearchParams({
    from: from.toISOString(),
    to: new Date(from.getTime() + RANGE_DAYS * DAY_MS).toISOString(),
  });
  const res = await fetch(`${base(token)}?${qs}`, {
    credentials: 'omit',
    headers: { Accept: 'application/json' },
  });
  if (res.status === 404 || res.status === 400) {
    throw new Error('This link is not valid, or the meeting 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 meeting.');
  return (await res.json()) as Managed;
}

export function ManageBookingView({
  slug,
  token,
  mode,
}: {
  slug: string;
  token: string;
  mode: 'cancel' | 'reschedule';
}) {
  const zone = useMemo(visitorZone, []);
  const [booking, setBooking] = useState<Managed | null>(null);
  const [loadError, setLoadError] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [from, setFrom] = useState(() => new Date());
  const [day, setDay] = useState('');
  const [picked, setPicked] = useState('');
  const [busy, setBusy] = useState(false);
  const [done, setDone] = useState<'cancelled' | 'rescheduled' | null>(null);
  const request = useRef(0);

  const load = useCallback(
    async (nextFrom: Date) => {
      const id = ++request.current;
      setBusy(true);
      try {
        const data = await fetchBooking(token, nextFrom);
        if (id !== request.current) return;
        setBooking(data);
        setFrom(nextFrom);
        setDay('');
        setPicked('');
      } catch (err) {
        if (id === request.current) {
          setLoadError(err instanceof Error ? err.message : 'Could not load this meeting.');
        }
      } finally {
        if (id === request.current) setBusy(false);
      }
    },
    [token],
  );

  useEffect(() => {
    void load(new Date());
  }, [load]);

  const { locale, hour12 } = dateLocaleOf(booking?.dateFormat);
  const time: Intl.DateTimeFormatOptions = hour12
    ? { hour: 'numeric', minute: '2-digit', hour12: true }
    : { hour: 'numeric', minute: '2-digit' };
  const when = (iso: string) => {
    const d = new Date(iso);
    return `${d.toLocaleDateString(locale, {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric',
      timeZone: zone,
    })}, ${d.toLocaleTimeString(locale, { ...time, timeZone: zone })}`;
  };
  const days = useMemo(() => groupSlotsByDay(booking?.slots ?? [], zone), [booking, zone]);
  const shownDay = days.find((d) => d.day === day) ?? days[0];
  const lang = booking?.language === 'en' ? 'en' : undefined;
  // The page's own link: the slug the booking has now (the link may be older).
  const pageSlug = booking?.slug ?? slug;

  const act = async (action: 'cancel' | 'reschedule') => {
    setBusy(true);
    setError(null);
    try {
      const res = await fetch(`${base(token)}/${action}`, {
        method: 'POST',
        credentials: 'omit',
        headers: {
          Accept: 'application/json',
          ...(action === 'reschedule' && { 'Content-Type': 'application/json' }),
        },
        ...(action === 'reschedule' && { body: JSON.stringify({ start: picked }) }),
      });
      if (!res.ok) {
        const message = await readError(
          res,
          action === 'cancel' ? 'Could not cancel this meeting.' : 'Could not move this meeting.',
        );
        // The time was taken meanwhile: fresh times.
        if (action === 'reschedule' && res.status === 409) void load(from);
        throw new Error(message);
      }
      setBooking((await res.json()) as Managed);
      setDone(action === 'cancel' ? 'cancelled' : 'rescheduled');
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Something went wrong.');
    } finally {
      setBusy(false);
    }
  };

  if (loadError || !booking) {
    return (
      <main className="crm-public-book">
        <div className="crm-public-book__card">
          {loadError ? (
            <>
              <h1>Meeting unavailable</h1>
              <p>{loadError}</p>
            </>
          ) : (
            <p>Loading…</p>
          )}
        </div>
      </main>
    );
  }

  const header = (
    <>
      <p className="crm-public-book__host">
        {booking.hostName ? `Meeting with ${booking.hostName}` : booking.pageTitle}
      </p>
      <h1>{booking.meetingTitle}</h1>
      <p className="crm-public-book__picked">
        <strong>{when(booking.start)}</strong> · {booking.durationMinutes} min
        <br />
        <small>Times are in {zone.replace(/_/g, ' ')}.</small>
      </p>
    </>
  );

  if (done || booking.status === 'cancelled') {
    const cancelled = booking.status === 'cancelled';
    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>{cancelled ? 'Meeting cancelled' : 'Meeting rescheduled'}</h1>
          <p>
            {cancelled
              ? `${booking.meetingTitle} is cancelled.`
              : `${booking.meetingTitle} is now on ${when(booking.start)}.`}
            {done ? (
              <>
                <br />
                {cancelled
                  ? 'The calendar invitation is cancelled too.'
                  : 'The calendar invitation has the new time.'}
              </>
            ) : null}
          </p>
          {cancelled ? (
            <p>
              <Link href={`/book/${encodeURIComponent(pageSlug)}`}>Book another time</Link>
            </p>
          ) : null}
        </div>
      </main>
    );
  }

  if (mode === 'cancel') {
    return (
      <main className="crm-public-book" lang={lang}>
        <div className="crm-public-book__card">
          {header}
          {booking.canCancel ? (
            <>
              <h2 className="crm-public-book__step">Cancel this meeting?</h2>
              <p className="crm-public-book__hint">
                Everyone invited is told, and the meeting is removed from their calendars.
              </p>
              {error ? <p className="crm-public-book__error">{error}</p> : null}
              <div className="crm-public-book__actions">
                <button
                  type="button"
                  className="crm-public-book__danger"
                  disabled={busy}
                  onClick={() => void act('cancel')}
                >
                  {busy ? 'Cancelling…' : 'Cancel meeting'}
                </button>
                {booking.canReschedule ? (
                  <Link
                    className="crm-public-book__link"
                    href={`/book/${encodeURIComponent(pageSlug)}/reschedule/${encodeURIComponent(token)}`}
                  >
                    Reschedule instead
                  </Link>
                ) : null}
              </div>
            </>
          ) : (
            <p className="crm-public-book__hint">
              This meeting can no longer be cancelled here. Reply to the invitation instead.
            </p>
          )}
        </div>
      </main>
    );
  }

  const earliest = from.getTime() <= Date.now() + 60_000;
  return (
    <main className="crm-public-book" lang={lang}>
      <div className="crm-public-book__card crm-public-book__card--wide">
        {header}
        {!booking.canReschedule ? (
          <p className="crm-public-book__hint">
            This meeting can no longer be rescheduled here. Reply to the invitation instead.
            {booking.canCancel ? (
              <>
                {' '}
                <Link
                  className="crm-public-book__link"
                  href={`/book/${encodeURIComponent(pageSlug)}/cancel/${encodeURIComponent(token)}`}
                >
                  Cancel the meeting
                </Link>
              </>
            ) : null}
          </p>
        ) : (
          <div className="crm-public-book__section">
            <div className="crm-public-book__row">
              <h2 className="crm-public-book__step">Pick a new time</h2>
              <div className="crm-public-book__nav">
                <button
                  type="button"
                  aria-label="Earlier dates"
                  disabled={busy || earliest}
                  onClick={() =>
                    void load(new Date(Math.max(Date.now(), from.getTime() - RANGE_DAYS * DAY_MS)))
                  }
                >
                  ‹
                </button>
                <button
                  type="button"
                  aria-label="Later dates"
                  disabled={busy}
                  onClick={() => void load(new Date(from.getTime() + RANGE_DAYS * DAY_MS))}
                >
                  ›
                </button>
              </div>
            </div>
            {busy && !picked ? (
              <p className="crm-public-book__hint">Loading times…</p>
            ) : !days.length ? (
              <p className="crm-public-book__hint">
                No open times in these two weeks. Try later dates.
              </p>
            ) : (
              <div className="crm-public-book__picker">
                <div className="crm-public-book__days" role="listbox" aria-label="Days">
                  {days.map((d) => (
                    <button
                      key={d.day}
                      type="button"
                      role="option"
                      aria-selected={d.day === shownDay?.day}
                      className={d.day === shownDay?.day ? 'is-selected' : undefined}
                      onClick={() => setDay(d.day)}
                    >
                      <strong>
                        {new Date(`${d.day}T12:00:00Z`).toLocaleDateString(locale, {
                          weekday: 'short',
                          month: 'short',
                          day: 'numeric',
                          timeZone: 'UTC',
                        })}
                      </strong>
                      <small>
                        {d.slots.length} time{d.slots.length === 1 ? '' : 's'}
                      </small>
                    </button>
                  ))}
                </div>
                <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 === picked}
                      className={slot === picked ? 'is-selected' : undefined}
                      onClick={() => {
                        setPicked(slot);
                        setError(null);
                      }}
                    >
                      {new Date(slot).toLocaleTimeString(locale, { ...time, timeZone: zone })}
                    </button>
                  ))}
                </div>
              </div>
            )}
            {error ? <p className="crm-public-book__error">{error}</p> : null}
            <div className="crm-public-book__actions">
              <button
                type="button"
                className="crm-public-book__primary"
                disabled={busy || !picked}
                onClick={() => void act('reschedule')}
              >
                {busy && picked
                  ? 'Rescheduling…'
                  : picked
                    ? `Move to ${when(picked)}`
                    : 'Reschedule'}
              </button>
              {booking.canCancel ? (
                <Link
                  className="crm-public-book__link"
                  href={`/book/${encodeURIComponent(pageSlug)}/cancel/${encodeURIComponent(token)}`}
                >
                  Cancel instead
                </Link>
              ) : null}
            </div>
          </div>
        )}
      </div>
    </main>
  );
}
