'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef, useState } from 'react';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { RichNotes } from '@/components/crm/RichNotes';
import { useToast } from '@/components/crm/ToastProvider';
import { useConfirm } from '@/components/crm/useConfirm';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { AssociatedRecordsPanel } from '@/features/contacts/ui/actions/AssociatedRecordsPanel';
import { sameAssoc, type AssocRecord } from '@/features/contacts/ui/actions/assocTypes';
import { listAllOwners, type Owner } from '@/features/owners/api.client';
import { useUserPrefs } from '@/features/settings/UserPrefs';
import { zoneLabel } from '@/features/settings/ui/accountDefaultsZones';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { browserTimeZone, fromZoned, toZoned } from '@/lib/utils/timezone';
import { useAssignees } from '@/features/contacts/ui/actions/shared';
import { TaskCommentsPanel, useTaskComments } from '@/features/tasks/ui/TaskCommentsPanel';
import {
  addMeetingLink,
  cancelMeeting,
  deleteMeeting,
  getMeeting,
  listMeetingLinks,
  removeMeetingLink,
  updateMeeting,
} from '../../api.client';
import { fmtMinutes } from '../../calendarView';
import { meetingNotesHtml } from '../../notes';
import type { Meeting, MeetingAssociation, UpdateMeetingBody } from '../../types';
import { optionLabel, responseLabel, useMeetingOptions } from '../../useMeetingOptions';
import { useDesignTooltip } from '../scheduler/parts';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';
import { snippetTargetFromLinks } from '@/features/snippets/model';

/**
 * A CRM meeting's page (13 Nov design sales-meeting-details.html), opened from the Calendar:
 * outcome, title, time, attendee description, attendees, associations and notes, on
 * GET / PATCH /meetings/:id. Time, title and description are the organizer's (Google Calendar).
 */

const RECORD_PATH: Record<string, string> = {
  contact: '/contacts',
  company: '/companies',
  deal: '/deals',
  ticket: '/tickets',
};
const GROUPS = [
  ['contact', 'Contacts'],
  ['company', 'Companies'],
  ['deal', 'Deals'],
  ['ticket', 'Tickets'],
] as const;

const hhmm = (hours: number) => {
  const m = Math.round(hours * 60);
  return `${String(Math.floor(m / 60) % 24).padStart(2, '0')}:${String(m % 60).padStart(2, '0')}`;
};
const hoursOf = (value: string) => {
  const [h = 0, m = 0] = value.split(':').map(Number);
  return h + m / 60;
};
const DATE_FMT = (day: string) =>
  new Date(`${day}T00:00:00Z`).toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    timeZone: 'UTC',
  });

const whenOf = (m: Meeting, zone: string) => {
  const s = toZoned(new Date(m.startsAt), zone);
  const e = toZoned(new Date(m.endsAt), zone);
  return { startDay: s.day, start: hhmm(s.hours), endDay: e.day, end: hhmm(e.hours) };
};

type Panel = 'association' | null;

export function MeetingDetailsView({ meetingId }: { meetingId: string }) {
  const me = useCurrentUser();
  const toast = useToast();
  const router = useRouter();
  const { confirm, dialog: confirmDialog } = useConfirm();
  const rootRef = useRef<HTMLDivElement>(null);
  useDesignTooltip(rootRef);

  const [meeting, setMeeting] = useState<Meeting | null>(null);
  const [error, setError] = useState<string | null>(null);
  // MT-6 (M-11): the user's own zone (profile), else the browser's, as /meetings shows it.
  const prefs = useUserPrefs();
  const timeZone = prefs.profileTimeZone || browserTimeZone();
  // MT-6: Back and Delete return where the meeting was opened from: `?from=<path>`, else the
  // previous page of this app, else /meetings.
  const [from] = useState(() => {
    if (typeof window === 'undefined') return null;
    const v = new URLSearchParams(window.location.search).get('from');
    return v && v.startsWith('/') && !v.startsWith('//') ? v : null;
  });
  const backHref = from ?? '/meetings';
  const goBack = useCallback(() => {
    if (from) router.push(from);
    else if (document.referrer.startsWith(window.location.origin) && window.history.length > 1) {
      router.back();
    } else router.push('/meetings');
  }, [from, router]);
  const onBack = (e: React.MouseEvent) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.button !== 0) return;
    e.preventDefault();
    goBack();
  };
  const options = useMeetingOptions();
  // MT-8 (M-03): the meeting's All comments, as the call page's (CL10).
  const commentsState = useTaskComments(meetingId, 'meeting');
  const [commentsOpen, setCommentsOpen] = useState(false);
  const { members } = useAssignees(true);
  const [links, setLinks] = useState<MeetingAssociation[]>([]);
  const [owners, setOwners] = useState<Owner[]>([]);
  const [newGuest, setNewGuest] = useState('');
  const [assocOpen, setAssocOpen] = useState(false);
  const [tab, setTab] = useState<'prep' | 'review'>('review');
  const [banner, setBanner] = useState(true);
  const [menu, setMenu] = useState<
    'outcome' | 'type' | 'attendees' | 'participants' | 'actions' | null
  >(null);
  const [panel, setPanel] = useState<Panel>(null);

  useEffect(() => {
    if (!panel) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setPanel(null);
    };
    document.addEventListener('keydown', onKey);
    return () => document.removeEventListener('keydown', onKey);
  }, [panel]);
  const [attendeeFilter, setAttendeeFilter] = useState<'all' | 'host'>('all');
  const [editingTitle, setEditingTitle] = useState(false);
  const [title, setTitle] = useState('');
  const [editingDesc, setEditingDesc] = useState(false);
  const [description, setDescription] = useState('');
  const [when, setWhen] = useState({ startDay: '', start: '', endDay: '', end: '' });
  const [notes, setNotes] = useState('');
  const [saving, setSaving] = useState(false);

  const [location, setLocation] = useState('');
  const [videoLink, setVideoLink] = useState('');

  /** The form fields that show the time are worked out in `timeZone` (see the effect below). */
  const fill = useCallback((m: Meeting) => {
    setMeeting(m);
    setTitle(m.title ?? '');
    setDescription(m.description ?? '');
    setNotes(m.notes ?? '');
    setLocation(m.location ?? '');
    setVideoLink(m.meetingUrl ?? '');
  }, []);

  // The times shown follow the saved zone, also when the profile arrives after the meeting.
  useEffect(() => {
    if (meeting) setWhen(whenOf(meeting, timeZone));
  }, [meeting, timeZone]);

  const loadLinks = useCallback(
    () =>
      listMeetingLinks(meetingId).then(
        (r) => setLinks(r.data),
        () => {},
      ),
    [meetingId],
  );

  useEffect(() => {
    getMeeting(meetingId).then(fill, (err) =>
      setError(isApiError(err) && err.isNotFound ? 'This meeting was not found.' : errorText(err)),
    );
    void loadLinks();
    listAllOwners(true).then(setOwners, () => {});
  }, [meetingId, fill, loadLinks]);

  useEffect(() => {
    if (!menu) return;
    const close = (e: MouseEvent) => {
      if (!(e.target as Element).closest('.md-dropdown-wrap, .md-attendees-heading')) setMenu(null);
    };
    document.addEventListener('mousedown', close);
    return () => document.removeEventListener('mousedown', close);
  }, [menu]);

  const save = async (body: UpdateMeetingBody, done: string) => {
    if (!meeting || saving) return false;
    setSaving(true);
    try {
      const updated = await updateMeeting(meeting.id, body);
      fill(updated);
      toast(done);
      if (updated.googleStatus === 'failed' && updated.googleError) {
        toast(`Google Calendar: ${updated.googleError}`, 'danger');
      }
      return true;
    } catch (err) {
      toast(errorText(err), 'danger');
      return false;
    } finally {
      setSaving(false);
    }
  };

  if (error || !meeting) {
    return (
      <div className="md-page">
        <Link className="md-back" href={backHref} onClick={onBack}>
          <CrmIcon name="chevron-left" className="iconSize-16" /> <span>Back</span>
        </Link>
        <header className="md-header" style={{ paddingBottom: 16 }}>
          <div className="md-title-wrap">
            <h1>{error ?? 'Loading…'}</h1>
          </div>
        </header>
      </div>
    );
  }

  const organizer = meeting.ownerId === me.user.id;
  const cancelled = meeting.status === 'cancelled';
  // A calendar meeting's time, title, place and guests are its organizer's (Google Calendar).
  const canEdit = !cancelled && (organizer || meeting.origin === 'logged');
  const s = toZoned(new Date(meeting.startsAt), timeZone);
  const e = toZoned(new Date(meeting.endsAt), timeZone);
  const outcomeLabel = meeting.outcome
    ? optionLabel(options.outcomes, meeting.outcome)
    : 'Select outcome';
  const typeLabel = meeting.meetingType
    ? optionLabel(options.types, meeting.meetingType)
    : 'Select call and meeting type';
  const ownerName =
    meeting.ownerId === me.user.id
      ? me.user.name
      : (owners.find((o) => o.userId === meeting.ownerId)?.name ?? 'A teammate');
  const assocRecords: AssocRecord[] = links.map((l) => ({
    type: l.type,
    id: l.id,
    displayName: l.name ?? l.email ?? l.id,
    subtitle: l.email,
  }));
  /** Add and remove records through the picker: each change is saved at once. */
  const changeLinks = async (next: AssocRecord[]) => {
    const added = next.filter((n) => !assocRecords.some((r) => sameAssoc(r, n)));
    const removed = assocRecords.filter((r) => !next.some((n) => sameAssoc(r, n)));
    try {
      for (const r of added) await addMeetingLink(meeting.id, { type: r.type, id: r.id });
      for (const r of removed) await removeMeetingLink(meeting.id, { type: r.type, id: r.id });
    } catch (err) {
      toast(errorText(err), 'danger');
    }
    await loadLinks();
    const fresh = await getMeeting(meeting.id).catch(() => null);
    if (fresh) setMeeting(fresh);
  };
  const addGuest = () => {
    const email = newGuest.trim().toLowerCase();
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      toast('Enter a valid email address', 'danger');
      return;
    }
    if (meeting.attendees.some((a) => a.email.toLowerCase() === email)) return;
    // QA round 3: Google keeps the organizer out of the guest list, so they are never "added".
    if (organizer && email === me.user.email.toLowerCase()) {
      toast("You're the organizer of this meeting");
      return;
    }
    setNewGuest('');
    void save(
      { attendees: [...meeting.attendees.map((a) => a.email), email] },
      'Participant added. Google sends the invitation.',
    );
  };
  const removeAttendee = (email: string) =>
    void save(
      { attendees: meeting.attendees.map((a) => a.email).filter((x) => x !== email) },
      'Participant removed',
    );
  const onDelete = async () => {
    setMenu(null);
    const calendarEvent = meeting.origin === 'calendar' && !cancelled;
    const ok = await confirm({
      title: 'Delete this meeting?',
      message: calendarEvent
        ? 'The meeting and its timeline entries are removed for good. Google Calendar cancels it and tells the attendees.'
        : 'The meeting and its timeline entries are removed for good.',
      confirmLabel: 'Delete',
      danger: true,
    });
    if (!ok) return;
    try {
      await deleteMeeting(meeting.id);
      toast('Meeting deleted');
      goBack();
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  const onCancel = async () => {
    setMenu(null);
    const ok = await confirm({
      title: 'Cancel this meeting?',
      message:
        'Google Calendar tells the attendees. The meeting stays on the timeline as cancelled.',
      confirmLabel: 'Cancel meeting',
      danger: true,
    });
    if (!ok) return;
    try {
      await cancelMeeting(meeting.id);
      toast('Meeting cancelled');
      fill(await getMeeting(meeting.id));
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };
  const hostEmail = organizer ? me.user.email.toLowerCase() : null;
  const attendees = meeting.attendees.filter(
    (a) => attendeeFilter === 'all' || a.email.toLowerCase() === hostEmail,
  );
  const startAt = when.startDay ? fromZoned(when.startDay, hoursOf(when.start), timeZone) : null;
  const endAt = when.endDay ? fromZoned(when.endDay, hoursOf(when.end), timeZone) : null;
  const timeChanged =
    startAt !== null &&
    endAt !== null &&
    (startAt.getTime() !== Date.parse(meeting.startsAt) ||
      endAt.getTime() !== Date.parse(meeting.endsAt));
  const deals = links.filter((l) => l.type === 'deal');

  // QA #648: notes are rich text, as HubSpot's (B / I / List / Link format, they don't type
  // marks). The editor starts from the saved notes (older plain ones escaped); they are saved
  // when focus leaves the card (the toolbar and its link box keep it).
  const saveNotes = () => {
    const next = htmlIsEmpty(notes) ? null : notes;
    if (next !== (meeting.notes || null)) void save({ notes: next }, 'Notes saved');
  };
  const notesCard = (className: string, placeholder: string, tools: boolean) => (
    <article
      className={cn('md-card', className)}
      onBlur={(ev) => {
        if (!ev.currentTarget.contains(ev.relatedTarget as Node | null)) saveNotes();
      }}
    >
      <h2>{tools ? 'Notes' : 'Internal notes'}</h2>
      <RichNotes
        openKey={meeting.id}
        value={meetingNotesHtml(notes)}
        onChange={setNotes}
        label={tools ? 'Meeting notes' : 'Internal notes'}
        placeholder={placeholder}
        snippetTarget={snippetTargetFromLinks(
          meeting.links.map((l) => ({ objectType: l.type, id: l.id })),
        )}
      />
    </article>
  );

  return (
    <div className="md-page" data-meeting-details="" ref={rootRef}>
      {confirmDialog}
      <TaskCommentsPanel
        taskId={meeting.id}
        on="meeting"
        open={commentsOpen}
        onClose={() => setCommentsOpen(false)}
        state={commentsState}
        canComment={me.role !== 'read_only'}
        members={members}
        meName={me.user.name}
        links={links.map((l) => ({ objectType: l.type, id: l.id }))}
      />
      <Link className="md-back" href={backHref} onClick={onBack}>
        <CrmIcon name="chevron-left" className="iconSize-16" /> <span>Back</span>
      </Link>
      <header className="md-header">
        <div className="md-title-wrap">
          {editingTitle ? (
            <input
              className="input"
              aria-label="Meeting title"
              value={title}
              autoFocus
              maxLength={255}
              onChange={(ev) => setTitle(ev.target.value)}
              onKeyDown={(ev) => {
                if (ev.key === 'Escape') {
                  setTitle(meeting.title ?? '');
                  setEditingTitle(false);
                }
                if (ev.key === 'Enter') (ev.target as HTMLInputElement).blur();
              }}
              onBlur={() => {
                setEditingTitle(false);
                if (title.trim() && title.trim() !== (meeting.title ?? ''))
                  void save({ title: title.trim() }, 'Meeting updated');
                else setTitle(meeting.title ?? '');
              }}
            />
          ) : (
            <h1>{meeting.title ?? '(No title)'}</h1>
          )}
          <button
            type="button"
            className="md-icon-action"
            aria-label="Edit meeting title"
            disabled={!canEdit}
            data-tooltip={canEdit ? undefined : 'Only the organizer can change the title'}
            onClick={() => setEditingTitle(true)}
          >
            <CrmIcon name="pencil" className="iconSize-14" />
          </button>
        </div>
        <p className="md-meta crm-d-md-flex crm-align-items-center crm-gap-2">
          <span className="crm-fw-semibold crm-d-flex crm-align-items-center crm-gap-2">
            {DATE_FMT(s.day)} at {fmtMinutes(Math.round(s.hours * 60))} -{' '}
            {e.day !== s.day ? `${DATE_FMT(e.day)} ` : ''}
            {fmtMinutes(Math.round(e.hours * 60))} {zoneLabel(timeZone, new Date(meeting.startsAt))}
          </span>
          <span>·</span>{' '}
          {cancelled ? 'Canceled' : `Organized by ${organizer ? me.user.name : ownerName}`}
        </p>
        <div className="md-toolbar">
          {cancelled ? (
            // One status: a cancelled meeting has no outcome to show next to it.
            <span className="md-select md-outcome" role="status">
              <CrmIcon name="check-circle" className="iconSize-14" />
              <span>Canceled</span>
            </span>
          ) : options.outcomes.length ? (
            <div className="md-dropdown-wrap">
              <button
                type="button"
                className="md-select md-outcome"
                aria-expanded={menu === 'outcome'}
                onClick={() => setMenu((m) => (m === 'outcome' ? null : 'outcome'))}
              >
                <CrmIcon name="check-circle" className="iconSize-14" />
                <span>{outcomeLabel}</span>
                <CrmIcon name="chevron-down" className="iconSize-14" />
              </button>
              {menu === 'outcome' ? (
                <div className="md-menu">
                  {options.outcomes.map((o) => (
                    <button
                      type="button"
                      key={o}
                      onClick={() => {
                        setMenu(null);
                        void save({ outcome: o }, `Outcome updated: ${o}`);
                      }}
                    >
                      {o}
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
          ) : null}
          {options.types.length ? (
            <div className="md-dropdown-wrap">
              <button
                type="button"
                className="md-select"
                aria-expanded={menu === 'type'}
                onClick={() => setMenu((m) => (m === 'type' ? null : 'type'))}
              >
                <span>{typeLabel}</span>
                <CrmIcon name="chevron-down" className="iconSize-14" />
              </button>
              {menu === 'type' ? (
                <div className="md-menu">
                  {options.types.map((o) => (
                    <button
                      type="button"
                      key={o}
                      onClick={() => {
                        setMenu(null);
                        void save({ meetingType: o }, `Call and meeting type updated: ${o}`);
                      }}
                    >
                      {o}
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
          ) : null}
          <button className="md-link-action" type="button" onClick={() => setPanel('association')}>
            <CrmIcon name="paperclip" className="iconSize-14" /> Associations ({links.length})
          </button>
          <div className="md-dropdown-wrap">
            <button
              className="md-link-action"
              type="button"
              aria-expanded={menu === 'participants'}
              onClick={() => setMenu((m) => (m === 'participants' ? null : 'participants'))}
            >
              <CrmIcon name="users" className="iconSize-14" /> {meeting.attendees.length}{' '}
              participant{meeting.attendees.length === 1 ? '' : 's'}
            </button>
            {menu === 'participants' ? (
              <div className="md-menu md-participants-menu">
                {meeting.attendees.map((a) => (
                  <div className="md-attendee" key={a.email}>
                    <span className="md-avatar">{(a.name ?? a.email).charAt(0).toUpperCase()}</span>
                    <div>
                      <strong>{a.name ?? a.email}</strong>
                      <small>{a.email}</small>
                      <small>{responseLabel(a.response)}</small>
                    </div>
                    {canEdit && meeting.origin === 'calendar' ? (
                      <button
                        type="button"
                        className="md-icon-action"
                        aria-label={`Remove ${a.email}`}
                        onClick={() => removeAttendee(a.email)}
                      >
                        <CrmIcon name="x" className="iconSize-14" />
                      </button>
                    ) : null}
                  </div>
                ))}
                {canEdit ? (
                  <form
                    className="crm-d-flex crm-gap-2"
                    onSubmit={(ev) => {
                      ev.preventDefault();
                      addGuest();
                    }}
                  >
                    <input
                      className="input"
                      type="email"
                      aria-label="Add a participant by email"
                      placeholder="Add participant email"
                      value={newGuest}
                      onChange={(ev) => setNewGuest(ev.target.value)}
                    />
                    <button type="submit" className="btn-crm btn-crm--outline btn-crm--sm">
                      Add
                    </button>
                  </form>
                ) : null}
              </div>
            ) : null}
          </div>
          {meeting.meetingUrl ? (
            <a
              className="md-link-action"
              href={meeting.meetingUrl}
              target="_blank"
              rel="noreferrer"
            >
              <CrmIcon name="video" className="iconSize-14" />{' '}
              {meeting.meetingUrl.includes('meet.google.com')
                ? 'Join Google Meet'
                : 'Join video call'}
            </a>
          ) : null}
          <div className="md-dropdown-wrap md-actions">
            <button
              type="button"
              className="md-select"
              aria-expanded={menu === 'actions'}
              onClick={() => setMenu((m) => (m === 'actions' ? null : 'actions'))}
            >
              <span>Actions</span>
              <CrmIcon name="chevron-down" className="iconSize-14" />
            </button>
            {menu === 'actions' ? (
              <div className="md-menu">
                {meeting.origin === 'calendar' && !cancelled && organizer ? (
                  <button type="button" onClick={() => void onCancel()}>
                    Cancel meeting
                  </button>
                ) : null}
                <button type="button" onClick={() => void onDelete()}>
                  Delete
                </button>
              </div>
            ) : null}
          </div>
        </div>
        <nav className="md-tabs" role="tablist" aria-label="Meeting details">
          {(['prep', 'review'] as const).map((t) => (
            <button
              type="button"
              key={t}
              className={cn('md-tab', tab === t && 'is-active')}
              role="tab"
              aria-selected={tab === t}
              onClick={() => setTab(t)}
            >
              {t === 'prep' ? 'Prep' : 'Review'}
            </button>
          ))}
        </nav>
      </header>

      <div className="md-shell">
        <aside className="md-card md-about" aria-label="About this meeting">
          <h2>About this meeting</h2>
          <label className="md-about-field">
            <span>Meeting title</span>
            <input
              className="input"
              value={title}
              maxLength={255}
              disabled={!canEdit}
              onChange={(ev) => setTitle(ev.target.value)}
              onBlur={() => {
                if (title.trim() && title.trim() !== (meeting.title ?? ''))
                  void save({ title: title.trim() }, 'Meeting updated');
                else setTitle(meeting.title ?? '');
              }}
            />
          </label>
          {options.outcomes.length ? (
            <label className="md-about-field">
              <span>Meeting outcome</span>
              <select
                className="input"
                value={
                  cancelled
                    ? 'Canceled'
                    : meeting.outcome
                      ? optionLabel(options.outcomes, meeting.outcome)
                      : ''
                }
                disabled={cancelled}
                onChange={(ev) =>
                  void save(
                    { outcome: ev.target.value || null },
                    `Outcome updated: ${ev.target.value}`,
                  )
                }
              >
                <option value="">--</option>
                {[
                  ...options.outcomes,
                  ...(meeting.outcome &&
                  !options.outcomes.includes(optionLabel(options.outcomes, meeting.outcome))
                    ? [optionLabel(options.outcomes, meeting.outcome)]
                    : []),
                ].map((o) => (
                  <option key={o} value={o}>
                    {o}
                  </option>
                ))}
              </select>
            </label>
          ) : null}
          {options.types.length ? (
            <label className="md-about-field">
              <span>Call and meeting type</span>
              <select
                className="input"
                value={meeting.meetingType ? optionLabel(options.types, meeting.meetingType) : ''}
                onChange={(ev) =>
                  void save(
                    { meetingType: ev.target.value || null },
                    'Call and meeting type updated',
                  )
                }
              >
                <option value="">--</option>
                {[
                  ...options.types,
                  ...(meeting.meetingType &&
                  !options.types.includes(optionLabel(options.types, meeting.meetingType))
                    ? [optionLabel(options.types, meeting.meetingType)]
                    : []),
                ].map((o) => (
                  <option key={o} value={o}>
                    {o}
                  </option>
                ))}
              </select>
            </label>
          ) : null}
          <label className="md-about-field">
            <span>Location</span>
            <input
              className="input"
              value={location}
              maxLength={500}
              disabled={!canEdit}
              onChange={(ev) => setLocation(ev.target.value)}
              onBlur={() => {
                if ((location.trim() || null) !== meeting.location)
                  void save({ location: location.trim() || null }, 'Location updated');
              }}
            />
          </label>
          <label className="md-about-field">
            <span>Video link</span>
            <input
              className="input"
              type="url"
              placeholder="https://…"
              value={videoLink}
              maxLength={500}
              disabled={cancelled}
              onChange={(ev) => setVideoLink(ev.target.value)}
              onBlur={() => {
                const next = videoLink.trim() || null;
                if (next === meeting.meetingUrl) return;
                if (next && !/^https?:\/\/\S+$/i.test(next)) {
                  toast('Enter a link that starts with http:// or https://', 'danger');
                  setVideoLink(meeting.meetingUrl ?? '');
                  return;
                }
                void save({ meetingUrl: next }, 'Video link updated');
              }}
            />
          </label>
          <label className="md-about-field">
            <span>Activity assigned to</span>
            {meeting.origin === 'logged' && !cancelled ? (
              <select
                className="input"
                value={meeting.ownerId ?? ''}
                onChange={(ev) =>
                  ev.target.value && void save({ ownerId: ev.target.value }, 'Owner updated')
                }
              >
                {meeting.ownerId && !owners.some((o) => o.userId === meeting.ownerId) ? (
                  <option value={meeting.ownerId}>{ownerName}</option>
                ) : null}
                {owners
                  .filter((o) => o.active || o.userId === meeting.ownerId)
                  .map((o) => (
                    <option key={o.userId} value={o.userId}>
                      {o.name}
                    </option>
                  ))}
              </select>
            ) : (
              <strong>{ownerName}</strong>
            )}
          </label>
          <div className="md-about-field">
            <span>Source</span>
            <strong>
              {meeting.origin === 'calendar' ? 'Google Calendar' : 'Logged in the CRM'}
            </strong>
          </div>
        </aside>
        <div className="md-main">
          {banner ? (
            <div className="md-banner">
              <div>
                <strong>Turn conversations into actionable follow-ups</strong>
                <span>
                  Enable transcripts to generate suggested CRM updates, next steps, and follow-up
                  emails.
                </span>
              </div>
              <Link className="btn-crm btn-crm--outline btn-crm--sm" href="/settings/meetings">
                Enable now
              </Link>
              <button
                type="button"
                className="md-banner-close"
                aria-label="Dismiss banner"
                onClick={() => setBanner(false)}
              >
                ×
              </button>
            </div>
          ) : null}

          {tab === 'prep' ? (
            <section className="md-panel" role="tabpanel">
              <div className="md-columns">
                <div className="md-left-col">
                  <article className="md-card md-meeting-details">
                    <div className="md-card-heading">
                      <h2>Meeting details</h2>
                    </div>
                    <div className="md-detail-field">
                      <span>Meeting title</span>
                      <div className="md-inline-title-row">
                        <strong>{meeting.title ?? '(No title)'}</strong>
                        <button
                          type="button"
                          className="md-icon-action"
                          aria-label="Edit meeting title"
                          disabled={!canEdit}
                          onClick={() => setEditingTitle(true)}
                        >
                          <CrmIcon name="pencil" className="iconSize-14" />
                        </button>
                      </div>
                    </div>
                    <div className="md-detail-field">
                      <span>Attendee description</span>
                      {editingDesc ? (
                        <SnippetTextarea
                          className="md-notes"
                          aria-label="Attendee description"
                          value={description}
                          autoFocus
                          rows={4}
                          maxLength={8000}
                          onChange={(ev) => setDescription(ev.target.value)}
                          onBlur={() => {
                            setEditingDesc(false);
                            if ((description.trim() || null) !== meeting.description)
                              void save(
                                { description: description.trim() || null },
                                'Meeting updated. Google sends the attendees the change.',
                              );
                          }}
                          snippetTarget={snippetTargetFromLinks(
                            meeting.links.map((l) => ({ objectType: l.type, id: l.id })),
                          )}
                          typingOnly
                        />
                      ) : (
                        <div
                          className="md-description"
                          tabIndex={canEdit ? 0 : -1}
                          role="button"
                          aria-label="Edit attendee description"
                          aria-disabled={!canEdit}
                          onClick={() => canEdit && setEditingDesc(true)}
                          onKeyDown={(ev) => {
                            if (canEdit && (ev.key === 'Enter' || ev.key === ' '))
                              setEditingDesc(true);
                          }}
                        >
                          {meeting.description || (
                            <span className="crm-text-muted">
                              {canEdit ? 'Add a description for your attendees' : 'No description'}
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                    <div className="md-date-grid">
                      <label>
                        Start date
                        <div className="md-calendar-date">
                          <input
                            type="date"
                            value={when.startDay}
                            disabled={!canEdit}
                            onChange={(ev) => setWhen((w) => ({ ...w, startDay: ev.target.value }))}
                          />
                        </div>
                      </label>
                      <label>
                        Start time
                        <input
                          type="time"
                          value={when.start}
                          disabled={!canEdit}
                          onChange={(ev) => setWhen((w) => ({ ...w, start: ev.target.value }))}
                        />
                      </label>
                      <label>
                        End date
                        <div className="md-calendar-date">
                          <input
                            type="date"
                            value={when.endDay}
                            disabled={!canEdit}
                            onChange={(ev) => setWhen((w) => ({ ...w, endDay: ev.target.value }))}
                          />
                        </div>
                      </label>
                      <label>
                        End time
                        <input
                          type="time"
                          value={when.end}
                          disabled={!canEdit}
                          onChange={(ev) => setWhen((w) => ({ ...w, end: ev.target.value }))}
                        />
                      </label>
                    </div>
                    {timeChanged ? (
                      <div className="crm-d-flex crm-gap-2 crm-mt-2">
                        <button
                          type="button"
                          className="btn-crm btn-crm--primary btn-crm--sm"
                          disabled={saving || !startAt || !endAt || endAt <= startAt}
                          onClick={() =>
                            startAt &&
                            endAt &&
                            void save(
                              {
                                start: startAt.toISOString(),
                                end: endAt.toISOString(),
                                timezone: timeZone,
                              },
                              'Meeting updated. Google sends the attendees the change.',
                            )
                          }
                        >
                          Save time
                        </button>
                        <button
                          type="button"
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          onClick={() => setWhen(whenOf(meeting, timeZone))}
                        >
                          Cancel
                        </button>
                      </div>
                    ) : null}
                    <div className="md-attendees-heading">
                      <strong>Attendees</strong>
                      <div className="position-relative">
                        <button
                          type="button"
                          className="md-attendees-trigger"
                          aria-expanded={menu === 'attendees'}
                          onClick={() => setMenu((m) => (m === 'attendees' ? null : 'attendees'))}
                        >
                          {attendees.length} attendee{attendees.length === 1 ? '' : 's'}{' '}
                          <CrmIcon name="chevron-down" className="iconSize-12" />
                        </button>
                        {menu === 'attendees' ? (
                          <div className="md-attendees-menu">
                            <button
                              type="button"
                              onClick={() => {
                                setAttendeeFilter('all');
                                setMenu(null);
                              }}
                            >
                              All attendees
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                setAttendeeFilter('host');
                                setMenu(null);
                              }}
                            >
                              Meeting host
                            </button>
                          </div>
                        ) : null}
                      </div>
                    </div>
                    <div className="md-attendees">
                      {attendees.map((a) => (
                        <div className="md-attendee" key={a.email}>
                          <span className="md-avatar">
                            {(a.name ?? a.email).charAt(0).toUpperCase()}
                          </span>
                          <div>
                            <strong>{a.name ?? a.email}</strong>
                            <small>
                              {a.email.toLowerCase() === hostEmail
                                ? 'Host'
                                : responseLabel(a.response)}
                            </small>
                            <small>{a.email}</small>
                          </div>
                        </div>
                      ))}
                    </div>
                  </article>
                  {notesCard('', 'Take notes for internal users in your account...', false)}
                </div>
                <div className="md-right-col">
                  <article className="md-card md-ai-card">
                    <span className="md-suggestion">Suggested for you as an admin</span>
                    <div className="md-ai-content">
                      <div>
                        <h2>Prep in seconds, not minutes</h2>
                        <p>
                          Connect your transcripts to unlock better deal risks, buyer pain points,
                          and open questions before every conversation.
                        </p>
                        <Link
                          className="btn-crm btn-crm--outline btn-crm--sm"
                          href="/settings/meetings"
                        >
                          Connect now
                        </Link>
                      </div>
                      <div className="md-calendar-art" aria-hidden="true">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src="/crm/assets/img/sales-calendar.svg" alt="" />
                      </div>
                    </div>
                  </article>
                  <article className="md-card">
                    <div className="md-card-heading">
                      <h2>Deal brief</h2>
                    </div>
                    {deals.length ? (
                      <ul className="crm-fs-7" style={{ margin: 0, paddingLeft: 18 }}>
                        {deals.map((d) => (
                          <li key={d.id}>
                            <Link href={`/deals/${d.id}`}>
                              {d.name ?? 'Open the associated deal'}
                            </Link>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <div className="md-empty-state">Add a deal to get the latest deal brief.</div>
                    )}
                  </article>
                  <article className="md-card md-web-card">
                    <h2>Web page visits</h2>
                    <p>Last generated unavailable</p>
                    <small>No web page visits found based on the data available.</small>
                  </article>
                </div>
              </div>
            </section>
          ) : (
            <section className="md-panel" role="tabpanel">
              <div className="md-review-grid">
                {notesCard('md-notes-card', 'Take notes on the call...', true)}
                <article className="md-card md-recap-card">
                  <div className="md-recap-icon">✦</div>
                  <h2>This meeting doesn’t have a recap</h2>
                  <p>Connect your transcripts to get:</p>
                  <ul>
                    <li>Full transcripts and summaries ready when your conversation ends.</li>
                    <li>
                      Deal stages, next steps, and CRM properties updated without manual logging.
                    </li>
                    <li>Pre-drafted follow-up emails ready to review and send.</li>
                  </ul>
                  <Link className="btn-crm btn-crm--primary btn-crm--sm" href="/settings/meetings">
                    Learn more
                  </Link>
                  <hr />
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline btn-crm--sm"
                    aria-expanded={commentsOpen}
                    onClick={() => setCommentsOpen((o) => !o)}
                  >
                    {commentsState.comments?.length
                      ? `Comments (${commentsState.comments.length}${commentsState.comments.length >= 100 ? '+' : ''})`
                      : 'Comments'}
                  </button>
                </article>
              </div>
            </section>
          )}
        </div>
        <aside className="md-card md-assoc" aria-label="Associations">
          <div className="md-card-heading">
            <h2>Associations ({links.length})</h2>
          </div>
          <AssociatedRecordsPanel
            value={assocRecords}
            onChange={(next) => void changeLinks(next)}
            open={assocOpen}
            onOpenChange={setAssocOpen}
          />
          {GROUPS.map(([type, label]) => {
            const group = links.filter((l) => l.type === type);
            return group.length ? (
              <div className="md-assoc-group" key={type}>
                <h3>
                  {label} ({group.length})
                </h3>
                {group.map((l) => (
                  <div className="md-assoc-row" key={l.id}>
                    <div>
                      <Link href={`${RECORD_PATH[type]}/${l.id}`}>{l.name ?? l.id}</Link>
                      {l.email ? <small>{l.email}</small> : null}
                    </div>
                    <button
                      type="button"
                      className="md-icon-action"
                      aria-label={`Unlink ${l.name ?? l.id}`}
                      disabled={links.length === 1}
                      data-tooltip={
                        links.length === 1 ? 'A meeting keeps at least one record' : 'Unlink'
                      }
                      onClick={() => void changeLinks(assocRecords.filter((r) => r.id !== l.id))}
                    >
                      <CrmIcon name="x" className="iconSize-14" />
                    </button>
                  </div>
                ))}
              </div>
            ) : null;
          })}
          {links.length === 0 ? (
            <p className="crm-text-muted crm-fs-7">No associated records.</p>
          ) : null}
        </aside>
      </div>

      {panel ? (
        <div
          className="md-modal-backdrop"
          data-mode={panel}
          onMouseDown={(ev) => {
            if (ev.target === ev.currentTarget) setPanel(null);
          }}
        >
          <section
            className="md-modal"
            role="dialog"
            aria-modal="true"
            aria-labelledby="md-modal-title"
          >
            <header>
              <h2 id="md-modal-title">Associations</h2>
              <button type="button" aria-label="Close" onClick={() => setPanel(null)}>
                ×
              </button>
            </header>
            <div className="md-modal-body">
              {links.length ? (
                links.map((l) => (
                  <div className="md-modal-choice" key={`${l.type}-${l.id}`}>
                    <span>
                      <strong>{l.name ?? l.id}</strong>
                      {l.email ? <small> {l.email}</small> : null}
                      <small style={{ textTransform: 'capitalize' }}> {l.type}</small>
                    </span>
                    {RECORD_PATH[l.type] ? (
                      <Link href={`${RECORD_PATH[l.type]}/${l.id}`}>Open record</Link>
                    ) : null}
                  </div>
                ))
              ) : (
                <p className="crm-text-muted crm-fs-7">No associated records.</p>
              )}
            </div>
          </section>
        </div>
      ) : null}
    </div>
  );
}
