'use client';

import { useEffect, useRef, useState } from 'react';
import { useToast } from '@/components/crm/ToastProvider';
import { callDateNumeric } from '@/features/calls/format';
import {
  ActionsMenu,
  Cards,
  CompanyCard,
  ContactCard,
  DealCard,
  EMPTY_TEXT,
  EmptyArt,
  Ico,
  OTHER_SECTIONS,
  Section,
} from '@/features/calls/ui/CallPreviewPanel';
import { safeRichHtml } from '@/lib/utils/safe-html';
import { getMeeting } from '../api.client';
import { meetingTitle, type MeetingRow } from '../list';
import type { Meeting } from '../types';

/**
 * MT-5 (M-01, M-10): the docked meeting preview on /meetings, opened from a table row's preview
 * button or a Calendar or Gantt event; the page stays where it is. Built from the call preview's
 * parts (CallPreviewPanel): Actions (View meeting details; the history items wait for MT-16),
 * the meeting's date and time with its GMT offset, outcome, type, attendees, notes, About this
 * meeting and the linked contacts, companies and deals.
 */
export function MeetingPreviewPanel({
  meeting,
  timeZone,
  outcomeText,
  onClose,
}: {
  meeting: MeetingRow | null;
  timeZone: string;
  outcomeText: (row: MeetingRow) => string;
  onClose: () => void;
}) {
  const toast = useToast();
  const soon = (what: string) => toast(`${what} is coming soon`, 'info');
  const scrollRef = useRef<HTMLDivElement>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  /** The meeting's attendees and notes (GET /meetings/:id); the list row has neither. */
  const [detail, setDetail] = useState<{ id: string; meeting: Meeting | null } | null>(null);

  const id = meeting?.id ?? null;
  useEffect(() => {
    if (!id) return;
    document.body.classList.add('apv-open');
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
    closeRef.current?.focus({ preventScroll: true });
    let live = true;
    getMeeting(id).then(
      (m) => live && setDetail({ id, meeting: m }),
      () => live && setDetail({ id, meeting: null }),
    );
    return () => {
      live = false;
      document.body.classList.remove('apv-open');
    };
  }, [id]);

  useEffect(() => {
    if (!id) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !document.querySelector('.apv-menu, .lp-modal-ov, .lp-pop')) {
        onClose();
      }
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [id, onClose]);

  if (!meeting) return null;
  const name = meetingTitle(meeting);
  const full = detail?.id === meeting.id ? detail.meeting : undefined;
  const attendees = full?.attendees ?? [];
  const about: Array<[string, string]> = [
    ['Meeting start time', callDateNumeric(meeting.startsAt, timeZone)],
    ['Meeting end time', callDateNumeric(meeting.endsAt, timeZone)],
    ['Activity assigned to', meeting.owner?.name ?? '--'],
    ['Meeting outcome', outcomeText(meeting)],
    ['Call and meeting type', meeting.meetingType ?? '--'],
    ['Meeting location', meeting.location || '--'],
  ];
  const href = `/meetings/${meeting.id}`;

  return (
    <aside className="apv" role="complementary" aria-label={`${name} preview`}>
      <header className="apv__head">
        <h2 className="apv__h">Preview</h2>
        <button
          ref={closeRef}
          type="button"
          className="apv__close"
          aria-label="Close preview"
          onClick={onClose}
        >
          <Ico name="x" />
        </button>
      </header>
      <div ref={scrollRef} className="apv__scroll">
        <div className="apv-top">
          <div className="apv-top__bar">
            <ActionsMenu
              where="top"
              onSoon={soon}
              groups={[
                [
                  { label: 'View meeting details', href },
                  { label: 'Customize preview' },
                  { label: 'View all properties' },
                ],
                [{ label: 'View property history' }, { label: 'View association history' }],
              ]}
            />
          </div>
          <h2 className="apv-title">{name}</h2>
          <p className="apv-meta">
            <b>Meeting start time</b> {callDateNumeric(meeting.startsAt, timeZone)}
          </p>
        </div>

        <Section title="Meeting details" onSoon={soon}>
          <div className="apv-field">
            <span className="apv-field__l">Attendees</span>
            <span className="apv-field__v">
              {full === undefined
                ? 'Loading…'
                : attendees.length
                  ? attendees.map((a) => a.name || a.email).join(', ')
                  : '--'}
            </span>
          </div>
          <div className="apv-notes">
            <div className="apv-notes__pane">
              {full?.notes ? (
                <div dangerouslySetInnerHTML={{ __html: safeRichHtml(full.notes) }} />
              ) : (
                <span className="apv-muted">
                  {full === undefined ? 'Loading…' : 'No notes for this meeting.'}
                </span>
              )}
            </div>
          </div>
        </Section>

        <Section
          title="About this meeting"
          onSoon={soon}
          extra={
            <>
              <span className="apv-sec__spacer" />
              <ActionsMenu
                where="about"
                onSoon={soon}
                groups={[[{ label: 'View all properties' }, { label: 'View property history' }]]}
              />
            </>
          }
        >
          {about.map(([label, value]) => (
            <div key={label} className="apv-field">
              <span className="apv-field__l">{label}</span>
              <span className="apv-field__v">{value}</span>
            </div>
          ))}
        </Section>

        <Cards
          title="Contacts"
          linked={meeting.associations.contacts}
          render={(x) => <ContactCard x={x} onSoon={soon} />}
          onSoon={soon}
        />
        <Cards
          title="Companies"
          linked={meeting.associations.companies}
          render={(x) => <CompanyCard x={x} />}
          onSoon={soon}
        />
        <Cards
          title="Deals"
          linked={meeting.associations.deals}
          render={(x) => <DealCard x={x} />}
          onSoon={soon}
        />
        {OTHER_SECTIONS.filter((title) => title !== 'Meetings').map((title) => (
          <Section key={title} title={`${title} (0)`} tools onSoon={soon}>
            <div className="apv-empty">
              <EmptyArt />
              <p>{EMPTY_TEXT[title] ?? `See the ${title} associated with this record.`}</p>
            </div>
          </Section>
        ))}
      </div>
    </aside>
  );
}
