'use client';

import Link from 'next/link';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { htmlIsEmpty } from '@/components/crm/ComposeRichText';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { RichNotes } from '@/components/crm/RichNotes';
import { useCurrentUser } from '@/features/auth/CurrentUser';
import { newIdempotencyKey } from '@/features/inbox/format';
import { searchContacts } from '@/features/inbox/api.client';
import type { SearchContact } from '@/features/inbox/types';
import { errorText } from '@/lib/api/errors';
import { fromZoned, toZoned } from '@/lib/utils/timezone';
import { createMeeting, listCalendarEvents, updateMeeting } from '../../api.client';
import { fmtMinutes, loadRange, rangeLabel, stepAnchor, visibleDays } from '../../calendarView';
import type { CalendarEvent, Meeting } from '../../types';
import { COMING_SOON, SsDropdown } from '../scheduler/parts';
import { placeEvents, TimeGrid } from './CalendarGrid';
import { SnippetTextarea } from '@/features/snippets/ui/SnippetTextarea';

/**
 * "Schedule a meeting" (sales-calender.html `data-ss-modal="schedule"`, sales-schedule.js
 * openSchedule): the form on the left, the week with the new meeting drawn on it on the right.
 * Creates a CRM meeting in the user's Google Calendar (POST /meetings).
 */

const MEETING_TYPES: [string, number][] = [
  ['15 min meeting', 15],
  ['30 min meeting', 30],
  ['60 min meeting', 60],
  ['Sales call', 30],
  ['Product demo', 60],
];

const LOCATIONS: [string, string][] = [
  ['Google Meet', 'Add a Google Meet video link'],
  ['Phone call', 'Have your attendee call you'],
  ['In-person', 'Set an address'],
  ['Custom', 'Set customized location details'],
];

const TIMES = Array.from({ length: 96 }, (_, i) => i * 15);

export function ScheduleMeetingDialog({
  open,
  start,
  timeZone,
  today,
  onClose,
  onCreated,
  toast,
}: {
  open: boolean;
  /** The slot clicked, or null for the next half hour. */
  start: { day: string; minutes: number } | null;
  timeZone: string;
  today: string;
  onClose: () => void;
  onCreated: (meeting: Meeting) => void;
  toast: (message: string, tone?: 'danger') => void;
}) {
  const me = useCurrentUser();
  const [title, setTitle] = useState('');
  const [date, setDate] = useState(today);
  const [from, setFrom] = useState(540);
  const [to, setTo] = useState(570);
  const [mtype, setMtype] = useState('');
  const [attendees, setAttendees] = useState<SearchContact[]>([]);
  const [linked, setLinked] = useState<Set<string>>(new Set());
  const [query, setQuery] = useState('');
  const [found, setFound] = useState<SearchContact[]>([]);
  const [location, setLocation] = useState('Google Meet');
  const [locationDetail, setLocationDetail] = useState('');
  const [description, setDescription] = useState('');
  const [noteOpen, setNoteOpen] = useState(false);
  const [note, setNote] = useState('');
  const [busy, setBusy] = useState(false);
  const [key, setKey] = useState(newIdempotencyKey);
  const [miniAnchor, setMiniAnchor] = useState(today);
  const [miniWeekends, setMiniWeekends] = useState(true);
  const [miniEvents, setMiniEvents] = useState<CalendarEvent[]>([]);
  const searchSeq = useRef(0);
  const titleRef = useRef<HTMLInputElement>(null);

  // A fresh form each time it opens (sales-schedule.js openSchedule).
  useEffect(() => {
    if (!open) return;
    let day = start?.day ?? today;
    let min = start?.minutes;
    if (min === undefined) {
      const z = toZoned(new Date(), timeZone);
      min = Math.ceil((z.hours * 60 + 1) / 30) * 30;
      if (min > 1410) {
        min = 540;
        const d = new Date(`${today}T00:00:00Z`);
        d.setUTCDate(d.getUTCDate() + 1);
        day = d.toISOString().slice(0, 10);
      }
    }
    setTitle(`Meet with ${me.user.name}`);
    setDate(day);
    setFrom(min);
    setTo(Math.min(1439, min + 30));
    setMtype('');
    setAttendees([]);
    setLinked(new Set());
    setQuery('');
    setFound([]);
    setLocation('Google Meet');
    setLocationDetail('');
    setDescription('');
    setNote('');
    setNoteOpen(false);
    setBusy(false);
    setKey(newIdempotencyKey());
    setMiniAnchor(day);
    window.setTimeout(() => titleRef.current?.select(), 30);
  }, [open, start, today, timeZone, me.user.name]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape' && !document.querySelector('.ss-menu')) onClose();
    };
    document.addEventListener('keydown', onKey);
    document.body.classList.add('ss-lock');
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.classList.remove('ss-lock');
    };
  }, [open, onClose]);

  // The mini calendar's week of events.
  useEffect(() => {
    if (!open) return;
    const [a, b] = loadRange('week', miniAnchor);
    let gone = false;
    listCalendarEvents(fromZoned(a, 0, timeZone), fromZoned(b, 0, timeZone)).then(
      (r) => {
        if (!gone) setMiniEvents(r.data);
      },
      () => {
        if (!gone) setMiniEvents([]);
      },
    );
    return () => {
      gone = true;
    };
  }, [open, miniAnchor, timeZone]);

  const onQuery = useCallback((value: string) => {
    setQuery(value);
    const q = value.trim();
    if (q.length < 2) {
      setFound([]);
      return;
    }
    const seq = ++searchSeq.current;
    window.setTimeout(async () => {
      if (seq !== searchSeq.current) return;
      try {
        const res = await searchContacts(q, 10);
        if (seq === searchSeq.current) setFound(res.contacts.filter((c) => c.email));
      } catch {
        // suggestions are optional
      }
    }, 250);
  }, []);

  const toggleAttendee = (c: SearchContact, on: boolean) => {
    setAttendees((list) => (on ? [...list, c] : list.filter((x) => x.id !== c.id)));
    setLinked((s) => {
      const next = new Set(s);
      if (on) next.add(c.id);
      else next.delete(c.id);
      return next;
    });
  };

  const placed = useMemo(() => placeEvents(miniEvents, timeZone), [miniEvents, timeZone]);
  const nowZ = toZoned(new Date(), timeZone);

  if (!open) return null;

  const records = attendees.filter((a) => linked.has(a.id));
  // #217: a meeting is scheduled in the future, and ends after it starts.
  const dateOk = /^\d{4}-\d{2}-\d{2}$/.test(date);
  const inPast = dateOk && fromZoned(date, from / 60, timeZone).getTime() < Date.now() - 60_000;
  const timeProblem = !dateOk
    ? null
    : inPast
      ? 'The meeting starts in the past. Choose a date and time from now on.'
      : to <= from
        ? 'The end time must be after the start time.'
        : null;
  const valid =
    Boolean(title.trim()) &&
    dateOk &&
    !timeProblem &&
    to > from &&
    attendees.length > 0 &&
    records.length > 0;
  const attendeeLabel = !attendees.length
    ? 'Select attendees'
    : attendees.length <= 2
      ? attendees.map((a) => a.displayName).join(', ')
      : `${attendees.length} attendees`;

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!valid || busy) return;
    setBusy(true);
    const startAt = fromZoned(date, from / 60, timeZone);
    const endAt = fromZoned(date, to / 60, timeZone);
    const where =
      location === 'Google Meet'
        ? undefined
        : location === 'Phone call'
          ? 'Phone call'
          : locationDetail.trim() || location;
    try {
      let meeting = await createMeeting({
        title: title.trim(),
        start: startAt.toISOString(),
        end: endAt.toISOString(),
        timezone: timeZone,
        attendees: attendees.map((a) => a.email!).filter(Boolean),
        description: description.trim() || undefined,
        location: where,
        addMeet: location === 'Google Meet',
        links: records.map((c) => ({ type: 'contact', id: c.id })),
        idempotencyKey: key,
      });
      // QA #648: the note is rich text (HTML), as the meeting page's notes.
      if (!htmlIsEmpty(note)) {
        try {
          meeting = await updateMeeting(meeting.id, { notes: note });
        } catch (err) {
          toast(
            `The meeting was scheduled, but the note was not saved: ${errorText(err)}`,
            'danger',
          );
        }
      }
      const d = new Date(`${date}T00:00:00Z`);
      toast(
        `Meeting scheduled for ${d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })} at ${fmtMinutes(from)}`,
      );
      if (meeting.googleStatus === 'failed' && meeting.googleError) {
        toast(`Google Calendar: ${meeting.googleError}`, 'danger');
      }
      onCreated(meeting);
    } catch (err) {
      toast(errorText(err), 'danger');
      setBusy(false);
    }
  };

  return (
    <div className="ss-modal" data-ss-modal="schedule">
      <div className="ss-modal__bd" onClick={onClose} />
      <form
        className="ss-dialog ss-dialog--lg"
        role="dialog"
        aria-modal="true"
        aria-labelledby="ss-sched-title"
        noValidate
        onSubmit={(e) => void submit(e)}
      >
        <header className="ss-dialog__head">
          <h2 id="ss-sched-title">Schedule a meeting</h2>
          <button type="button" className="ss-iconbtn" aria-label="Close" onClick={onClose}>
            <CrmIcon name="x" className="iconSize-16" />
          </button>
        </header>
        <div className="ss-dialog__body ss-split">
          <div className="ss-formcol">
            <fieldset className="ss-field">
              <legend>Host</legend>
              <div className="ss-radios">
                <label>
                  <input type="radio" name="hostMode" value="user" checked readOnly /> User
                </label>
                <label data-tooltip={`${COMING_SOON}: meeting rotations`}>
                  <input type="radio" name="hostMode" value="rotation" disabled /> Meeting rotation
                </label>
              </div>
              <div className="ss-dd ss-dd--block">
                <button
                  type="button"
                  className="ss-select"
                  disabled
                  data-tooltip="Meetings are scheduled in your own calendar."
                >
                  <span>
                    {me.user.name} &lt;{me.user.email}&gt;
                  </span>
                  <CrmIcon name="chevron-down" className="iconSize-14" />
                </button>
              </div>
            </fieldset>

            <label className="ss-field">
              <span className="ss-lbl">Title</span>
              <input
                className="ss-input"
                name="title"
                maxLength={120}
                ref={titleRef}
                value={title}
                onChange={(e) => setTitle(e.target.value)}
              />
            </label>

            <div className="ss-grid3">
              <label className="ss-field">
                <span className="ss-lbl">Start date</span>
                <input
                  className="ss-input"
                  type="date"
                  name="date"
                  min={today}
                  value={date}
                  onChange={(e) => {
                    setDate(e.target.value);
                    if (/^\d{4}-\d{2}-\d{2}$/.test(e.target.value)) setMiniAnchor(e.target.value);
                  }}
                />
              </label>
              <label className="ss-field">
                <span className="ss-lbl">Start time</span>
                <select
                  className="ss-input"
                  name="start"
                  value={from}
                  onChange={(e) => {
                    const v = Number(e.target.value);
                    setFrom(v);
                    if (to <= v) setTo(Math.min(1439, v + 30));
                  }}
                >
                  {TIMES.map((m) => (
                    <option key={m} value={m}>
                      {fmtMinutes(m)}
                    </option>
                  ))}
                </select>
              </label>
              <label className="ss-field">
                <span className="ss-lbl">End time</span>
                <select
                  className="ss-input"
                  name="end"
                  value={to}
                  onChange={(e) => setTo(Number(e.target.value))}
                >
                  {[...TIMES.slice(1), 1439]
                    .filter((m) => m > from)
                    .map((m) => (
                      <option key={m} value={m}>
                        {fmtMinutes(m)}
                      </option>
                    ))}
                </select>
              </label>
            </div>
            {timeProblem ? (
              <p className="ss-error" role="alert">
                {timeProblem}
              </p>
            ) : null}

            <div className="ss-field">
              <span className="ss-lbl">Meeting type</span>
              <SsDropdown
                toggleClassName="ss-link ss-link--bold"
                toggle={
                  <>
                    <span>{mtype || 'Select meeting type'}</span>{' '}
                    <CrmIcon name="chevron-down" className="iconSize-12" />
                  </>
                }
              >
                {(close) =>
                  MEETING_TYPES.map(([label, min]) => (
                    <button
                      type="button"
                      key={label}
                      data-ss-opt={label}
                      className={mtype === label ? 'is-selected' : undefined}
                      onClick={() => {
                        setMtype(label);
                        setTo(Math.min(1439, from + min));
                        close();
                      }}
                    >
                      {label}
                    </button>
                  ))
                }
              </SsDropdown>
            </div>

            <div className="ss-field">
              <span className="ss-lbl">Attendees</span>
              <SsDropdown
                toggleClassName="ss-link ss-link--bold"
                toggle={
                  <>
                    <span>{attendeeLabel}</span>{' '}
                    <CrmIcon name="chevron-down" className="iconSize-12" />
                  </>
                }
              >
                {() => (
                  <>
                    <div className="ss-search">
                      <input
                        type="search"
                        placeholder="Search contacts"
                        aria-label="Search attendees"
                        value={query}
                        onChange={(e) => onQuery(e.target.value)}
                      />
                      <CrmIcon name="search" className="iconSize-14" />
                    </div>
                    <div className="ss-list">
                      {[
                        ...attendees,
                        ...found.filter((c) => !attendees.some((a) => a.id === c.id)),
                      ].map((c) => (
                        <label className="ss-multi" key={c.id}>
                          <input
                            type="checkbox"
                            checked={attendees.some((a) => a.id === c.id)}
                            onChange={(e) => toggleAttendee(c, e.target.checked)}
                          />
                          <span>
                            {c.displayName}
                            <small className="ss-muted"> {c.email}</small>
                          </span>
                        </label>
                      ))}
                      {!attendees.length && !found.length ? (
                        <p className="ss-menu__empty">
                          {query.trim().length < 2
                            ? 'Type 2 letters of a contact’s name or email'
                            : 'No contacts with an email found'}
                        </p>
                      ) : null}
                    </div>
                  </>
                )}
              </SsDropdown>
            </div>

            <div className="ss-field">
              <span className="ss-lbl">Location</span>
              <SsDropdown
                toggleClassName="ss-link ss-link--muted"
                menuClassName="ss-menu--loc"
                toggle={
                  <>
                    <span>{location || 'Select location'}</span>{' '}
                    <CrmIcon name="chevron-down" className="iconSize-12" />
                  </>
                }
              >
                {(close) =>
                  LOCATIONS.map(([label, help]) => (
                    <button
                      type="button"
                      key={label}
                      data-ss-opt={label}
                      className={location === label ? 'is-selected' : undefined}
                      onClick={() => {
                        setLocation(label);
                        setLocationDetail('');
                        close();
                      }}
                    >
                      <span>
                        <strong>{label}</strong>
                        <small>{help}</small>
                      </span>
                    </button>
                  ))
                }
              </SsDropdown>
              {location === 'In-person' || location === 'Custom' ? (
                <input
                  className="ss-input"
                  placeholder={
                    location === 'In-person' ? 'Enter an address' : 'Enter location details'
                  }
                  value={locationDetail}
                  onChange={(e) => setLocationDetail(e.target.value)}
                  style={{ marginTop: 8 }}
                />
              ) : null}
            </div>

            <hr className="ss-rule" />
            <div className="ss-field">
              <span className="ss-lbl">Notetaker bot</span>
              <p className="ss-text">Automate your conversations from prep to follow-up</p>
              <p className="ss-text">
                Get prep briefs before you join, plus transcripts and follow-ups when you&apos;re
                done. <Link href="/settings/meetings">Enable transcripts</Link>
              </p>
            </div>
            <hr className="ss-rule" />

            <div className="ss-field">
              <span className="ss-lbl">Scheduled reminder email</span>
              <button
                type="button"
                className="ss-link ss-link--brand"
                disabled
                data-tooltip={`${COMING_SOON}: Google Calendar reminds attendees as their calendar is set up.`}
              >
                <CrmIcon name="plus" className="iconSize-14" />
                Add reminder
              </button>
              <label className="ss-check ss-check--top">
                <input type="checkbox" name="includeDesc" disabled />{' '}
                <span>Include the attendee description in the reminder email body</span>
              </label>
            </div>

            <hr className="ss-rule" />
            <div className="ss-field">
              <span className="ss-lbl">Attendee description</span>
              <SnippetTextarea
                className="ss-input ss-input--area"
                rows={2}
                name="description"
                placeholder="Send a description to your attendees…"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                snippetTarget={{ contactId: attendees[0]?.id }}
              />
              <div className="ss-right">
                <SsDropdown
                  toggleClassName="ss-link ss-link--bold"
                  menuClassName="ss-menu--up"
                  toggle={
                    <>
                      <span>
                        Associated with {records.length} record{records.length === 1 ? '' : 's'}
                      </span>{' '}
                      <CrmIcon name="chevron-down" className="iconSize-12" />
                    </>
                  }
                >
                  {() => (
                    <div className="ss-list">
                      {attendees.length ? (
                        attendees.map((c) => (
                          <label className="ss-multi" key={c.id}>
                            <input
                              type="checkbox"
                              checked={linked.has(c.id)}
                              onChange={(e) =>
                                setLinked((s) => {
                                  const next = new Set(s);
                                  if (e.target.checked) next.add(c.id);
                                  else next.delete(c.id);
                                  return next;
                                })
                              }
                            />
                            <span>{c.displayName}</span>
                          </label>
                        ))
                      ) : (
                        <p className="ss-menu__empty">Add an attendee from your contacts first</p>
                      )}
                    </div>
                  )}
                </SsDropdown>
              </div>
              <button
                type="button"
                className="ss-link ss-link--brand"
                onClick={() => setNoteOpen((o) => !o)}
              >
                <CrmIcon name="plus" className="iconSize-14" />
                Add internal note
              </button>
              {noteOpen ? (
                <div style={{ marginTop: 8 }}>
                  <RichNotes
                    openKey="note"
                    value={note}
                    onChange={setNote}
                    label="Internal note"
                    placeholder="Internal note (only visible to your team)"
                    minHeight={56}
                    snippetTarget={{ contactId: attendees[0]?.id }}
                  />
                </div>
              ) : null}
            </div>
          </div>

          <div className="ss-calcol">
            <div className="ss-minihead">
              <button type="button" className="ss-pillbtn" onClick={() => setMiniAnchor(today)}>
                Today
              </button>
              <h3>{rangeLabel('week', miniAnchor, miniWeekends)}</h3>
              <div className="ss-arrows">
                <button
                  type="button"
                  aria-label="Previous week"
                  onClick={() => setMiniAnchor((a) => stepAnchor('week', a, -1, miniWeekends))}
                >
                  <CrmIcon name="chevron-left" className="iconSize-16" />
                </button>
                <button
                  type="button"
                  aria-label="Next week"
                  onClick={() => setMiniAnchor((a) => stepAnchor('week', a, 1, miniWeekends))}
                >
                  <CrmIcon name="chevron-right" className="iconSize-16" />
                </button>
              </div>
            </div>
            <div className="ss-minictl">
              <label className="ss-check">
                <input
                  type="checkbox"
                  checked={miniWeekends}
                  onChange={(e) => setMiniWeekends(e.target.checked)}
                />{' '}
                <span>Hide weekends</span>
              </label>
              <span className="ss-tz">{timeZone.replace(/_/g, ' ')}</span>
            </div>
            <div className="ss-cal ss-cal--mini">
              <TimeGrid
                mini
                days={visibleDays('week', miniAnchor, miniWeekends)}
                today={today}
                nowMin={Math.round(nowZ.hours * 60)}
                events={placed}
                draft={{ day: date, start: from, end: to, title }}
                scrollTo={from}
                onSlot={(day, min) => {
                  setDate(day);
                  setFrom(min);
                  setTo(Math.min(1439, min + 30));
                }}
              />
            </div>
          </div>
        </div>
        <footer className="ss-dialog__foot">
          <button
            type="submit"
            className="btn-crm btn-crm--primary btn-crm--sm lp-btn--pill"
            disabled={!valid || busy}
            title={
              valid
                ? undefined
                : (timeProblem ??
                  'Add a title, a time and at least one attendee from your contacts')
            }
          >
            {busy ? 'Scheduling…' : 'Schedule meeting'}
          </button>
          <button
            type="button"
            className="btn-crm btn-crm--outline btn-crm--sm lp-btn--pill"
            onClick={onClose}
          >
            Cancel
          </button>
        </footer>
      </form>
    </div>
  );
}
