'use client';

import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { useToast } from '@/components/crm/ToastProvider';
import { useMeetingOptions } from '../../useMeetingOptions';
import { getProfile } from '@/features/settings/api.client';
import { listTasks } from '@/features/tasks/api.client';
import { errorText, isApiError } from '@/lib/api/errors';
import { cn } from '@/lib/utils/cn';
import { isUsable, needsReconnect } from '@/lib/utils/connection';
import { dayParts, fromZoned, toZoned } from '@/lib/utils/timezone';
import {
  connectGoogleCalendar,
  getMyCalendar,
  listCalendarEvents,
  updateMeeting,
} from '../../api.client';
import {
  attendeeInitials,
  loadRange,
  monthDays,
  rangeLabel,
  splitMeetings,
  stepAnchor,
  visibleDays,
  whenLabel,
  type CalView,
} from '../../calendarView';
import type { CalendarEvent, MyCalendar } from '../../types';
import { COMING_SOON, SsDropdown, useDesignTooltip } from '../scheduler/parts';
import { meetingHref, MonthGrid, placeEvents, TimeGrid } from './CalendarGrid';
import { EventPopover } from './EventPopover';
import { ScheduleMeetingDialog } from './ScheduleMeetingDialog';
import { TimeZonePicker, useCalendarZone } from './TimeZonePicker';

/**
 * Calendar (QA #344; 13 Nov design sales-calender.html, sales-schedule.js): upcoming and past
 * CRM meetings, the user's Google Calendar by day, week or month with meeting outcomes, and
 * "Schedule a meeting".
 */

export function CalendarView() {
  const toast = useToast();
  const router = useRouter();
  const rootRef = useRef<HTMLElement>(null);
  useDesignTooltip(rootRef);

  // #215: the user's own zone, then the one they last chose here (shared with /meetings, #647).
  const { timeZone, homeZone, adoptProfile, chooseZone } = useCalendarZone();
  const [clock, setClock] = useState(() => Date.now());
  const nowZ = toZoned(new Date(clock), timeZone);
  const today = nowZ.day;

  const [view, setView] = useState<CalView>('week');
  const [anchor, setAnchor] = useState(today);
  const [hideWeekends, setHideWeekends] = useState(true);
  const [show, setShow] = useState({ meetings: true, calendar: true, tasks: true });
  const [collapsed, setCollapsed] = useState(false);
  const [sideOpen, setSideOpen] = useState(true);
  const [secOpen, setSecOpen] = useState({ upcoming: true, past: true });
  const [banner, setBanner] = useState(true);

  const [calendar, setCalendar] = useState<MyCalendar | null>(null);
  const [events, setEvents] = useState<CalendarEvent[]>([]);
  const [sideEvents, setSideEvents] = useState<CalendarEvent[] | null>(null);
  const [tasksDue, setTasksDue] = useState<Record<string, number>>({});
  const { outcomes } = useMeetingOptions();
  const [loading, setLoading] = useState(false);
  /** #487: the Google event whose details are open. */
  const [popover, setPopover] = useState<CalendarEvent | null>(null);
  const [schedule, setSchedule] = useState<{ day: string; minutes: number } | null | false>(false);
  const request = useRef(0);
  /** Bumped to load the events again (after scheduling a meeting). */
  const [reload, setReload] = useState(0);

  const connected = isUsable(calendar);

  useEffect(() => {
    getMyCalendar().then(setCalendar, (err) => toast(errorText(err), 'danger'));
    getProfile().then(adoptProfile, () => {});
    const timer = window.setInterval(() => setClock(Date.now()), 60_000);
    return () => window.clearInterval(timer);
  }, [toast, adoptProfile]);

  const loadMain = useCallback(async () => {
    const id = ++request.current;
    const [a, b] = loadRange(view, anchor);
    setLoading(true);
    try {
      const res = await listCalendarEvents(fromZoned(a, 0, timeZone), fromZoned(b, 0, timeZone));
      if (id === request.current) setEvents(res.data);
    } catch (err) {
      if (id !== request.current) return;
      if (isApiError(err) && err.isConflict) {
        setCalendar((c) => (c ? { ...c, connected: false } : c));
      } else {
        toast(errorText(err), 'danger');
      }
    } finally {
      if (id === request.current) setLoading(false);
    }
  }, [view, anchor, timeZone, toast]);

  const loadSide = useCallback(async () => {
    const now = Date.now();
    try {
      const res = await listCalendarEvents(
        new Date(now - 14 * 86400000),
        new Date(now + 60 * 86400000),
      );
      setSideEvents(res.data);
    } catch {
      setSideEvents([]);
    }
  }, []);

  useEffect(() => {
    if (connected) void loadMain();
  }, [connected, loadMain, reload]);

  useEffect(() => {
    if (connected) void loadSide();
  }, [connected, loadSide, reload]);

  // Tasks due, for the "N tasks due" chips: my open tasks, by their due day.
  useEffect(() => {
    let gone = false;
    Promise.all(
      (['overdue', 'today', 'upcoming'] as const).map((v) =>
        listTasks({ view: v, assignee: 'me', limit: 100 }).then(
          (r) => r.data,
          () => [],
        ),
      ),
    ).then((lists) => {
      if (gone) return;
      const counts: Record<string, number> = {};
      const seen = new Set<string>();
      for (const t of lists.flat()) {
        if (seen.has(t.id)) continue;
        seen.add(t.id);
        const day = t.dueDate ?? (t.dueAt ? toZoned(new Date(t.dueAt), timeZone).day : null);
        if (day) counts[day] = (counts[day] ?? 0) + 1;
      }
      setTasksDue(counts);
    });
    return () => {
      gone = true;
    };
  }, [timeZone]);

  const placed = useMemo(
    () =>
      placeEvents(events, timeZone).filter((p) =>
        p.event.crmMeeting ? show.meetings : show.calendar,
      ),
    [events, timeZone, show.meetings, show.calendar],
  );
  const due = show.tasks ? tasksDue : {};
  const side = useMemo(() => splitMeetings(sideEvents ?? [], clock), [sideEvents, clock]);

  const openEvent = (e: CalendarEvent) => {
    const href = meetingHref(e);
    if (href) router.push(href);
    else setPopover(e);
  };

  const setOutcome = async (e: CalendarEvent, value: string) => {
    if (!e.crmMeeting) return;
    try {
      const updated = await updateMeeting(e.crmMeeting.id, { outcome: value });
      const patch = (list: CalendarEvent[]) =>
        list.map((x) =>
          x.crmMeeting?.id === updated.id
            ? { ...x, crmMeeting: { ...x.crmMeeting, outcome: updated.outcome } }
            : x,
        );
      setEvents(patch);
      setSideEvents((l) => (l ? patch(l) : l));
      toast(`Outcome updated: ${value}`);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const onConnect = async () => {
    try {
      const { authUrl } = await connectGoogleCalendar();
      window.location.assign(authUrl);
    } catch (err) {
      toast(errorText(err), 'danger');
    }
  };

  const closeSchedule = useCallback(() => setSchedule(false), []);

  const days =
    view === 'month' ? monthDays(anchor, hideWeekends) : visibleDays(view, anchor, hideWeekends);

  const meetingCard = (e: CalendarEvent) => {
    const a = attendeeInitials(e);
    return (
      <Link key={e.id} href={meetingHref(e) ?? '#'} className="ss-meeting">
        <strong>{e.title ?? '(No title)'}</strong>
        <span>{whenLabel(e.startsAt, today, timeZone)}</span>
        <span>
          With {a.count} attendee{a.count === 1 ? '' : 's'}
        </span>
        {a.initials.length ? (
          <span className="ss-avatars">
            {a.initials.map((i, n) => (
              <i className={cn('ss-av', n === 0 && 'ss-av--dark')} key={n}>
                {i}
              </i>
            ))}
            {a.more ? <b>{a.more > 9 ? '9+' : `+${a.more}`}</b> : null}
          </span>
        ) : null}
      </Link>
    );
  };

  return (
    <div className="sw-page" data-sales-workspace="">
      <section className="ss-page" data-ss="" ref={rootRef}>
        <aside className={cn('ss-side', !sideOpen && 'is-collapsed')}>
          <button
            type="button"
            className="ss-side__collapse"
            aria-label={`${sideOpen ? 'Collapse' : 'Expand'} meetings list`}
            onClick={() => setSideOpen((o) => !o)}
          >
            <CrmIcon name={sideOpen ? 'chevron-left' : 'chevron-right'} className="iconSize-14" />
          </button>
          <div className="ss-side__inner">
            <section className="ss-side__sec">
              <button
                type="button"
                className="ss-side__head"
                aria-expanded={secOpen.upcoming}
                onClick={() => setSecOpen((s) => ({ ...s, upcoming: !s.upcoming }))}
              >
                <CrmIcon
                  name={secOpen.upcoming ? 'chevron-down' : 'chevron-right'}
                  className="iconSize-14"
                />
                <strong>Upcoming meetings ({side.upcoming.length})</strong>
              </button>
              {secOpen.upcoming ? (
                <div>
                  {side.upcoming.length ? (
                    <div className="ss-meeting-list">
                      {side.upcoming.slice(0, 20).map(meetingCard)}
                    </div>
                  ) : (
                    <div className="ss-empty">
                      <div className="sw-trophy" aria-hidden="true">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img src="/crm/assets/img/sales-upcoming-events.svg" alt="" />
                      </div>
                      <p>
                        {sideEvents === null && connected
                          ? 'Loading meetings…'
                          : "You're all caught up on meetings."}
                      </p>
                    </div>
                  )}
                </div>
              ) : null}
            </section>
            <section className="ss-side__sec">
              <button
                type="button"
                className="ss-side__head"
                aria-expanded={secOpen.past}
                onClick={() => setSecOpen((s) => ({ ...s, past: !s.past }))}
              >
                <CrmIcon
                  name={secOpen.past ? 'chevron-down' : 'chevron-right'}
                  className="iconSize-14"
                />
                <strong>Past meetings ({side.past.length})</strong>
              </button>
              {secOpen.past ? (
                <div className="ss-meeting-list">
                  {side.past.slice(0, 20).map(meetingCard)}
                  {side.past.length ? null : (
                    <div className="ss-empty">
                      <p>No meetings in the last two weeks.</p>
                    </div>
                  )}
                </div>
              ) : null}
            </section>
          </div>
        </aside>

        <div className="ss-main">
          {calendar && !connected ? (
            <div className="ss-banner" role="status">
              <strong>
                {needsReconnect(calendar)
                  ? 'Reconnect Google Calendar'
                  : 'Connect your Google Calendar'}
              </strong>
              <span>
                See your meetings here and schedule new ones from the CRM.{' '}
                <button
                  type="button"
                  className="ss-link ss-link--brand"
                  onClick={() => void onConnect()}
                >
                  {needsReconnect(calendar) ? 'Reconnect' : 'Connect Google Calendar'}
                </button>
              </span>
            </div>
          ) : null}
          {banner ? (
            <div className="ss-banner" data-ss-banner="" style={{ position: 'relative' }}>
              <strong>Turn conversations into actionable follow-ups</strong>
              <span>
                Enable transcripts to generate suggested CRM updates, next steps, and follow-up
                emails.
              </span>
              <Link className="ss-pillbtn" href="/settings/meetings">
                Enable now <CrmIcon name="external" className="iconSize-14" />
              </Link>
              <button
                type="button"
                className="ss-iconbtn"
                aria-label="Dismiss banner"
                onClick={() => setBanner(false)}
              >
                <CrmIcon name="x" className="iconSize-14" />
              </button>
            </div>
          ) : null}

          <div className="ss-head">
            <h2 aria-live="polite">
              {rangeLabel(view, anchor, hideWeekends)}
              {loading ? <span className="crm-visually-hidden"> loading</span> : null}
            </h2>
            <div className="ss-head__actions">
              {/* Design: the time zone pill sits before "More tools" (Meetings spec 1). */}
              <TimeZonePicker timeZone={timeZone} homeZone={homeZone} onChoose={chooseZone} />
              <SsDropdown
                toggleClassName="btn-crm btn-crm--outline btn-crm--sm lp-btn--pill"
                menuClassName="ss-menu--tools"
                toggle={
                  <>
                    More tools <CrmIcon name="chevron-down" className="iconSize-14" />
                  </>
                }
              >
                {() => (
                  <>
                    <Link href="/meeting-scheduler" className="ss-menu__link">
                      Meetings scheduler <CrmIcon name="chevron-right" className="iconSize-14" />
                    </Link>
                    <button
                      type="button"
                      className="ss-menu__link is-disabled"
                      aria-disabled="true"
                      disabled
                      data-tooltip={COMING_SOON}
                    >
                      Add notetaker bot to live meeting
                    </button>
                  </>
                )}
              </SsDropdown>
              <button
                type="button"
                className="btn-crm btn-crm--primary btn-crm--sm lp-btn--pill"
                disabled={!connected}
                title={connected ? undefined : 'Connect Google Calendar first'}
                onClick={() => setSchedule(null)}
              >
                Schedule a meeting
              </button>
            </div>
          </div>

          <div className="ss-controls">
            <button type="button" className="ss-pillbtn" onClick={() => setAnchor(today)}>
              Today
            </button>
            <SsDropdown
              toggleClassName="ss-pillbtn"
              toggle={
                <>
                  <span>{view.charAt(0).toUpperCase() + view.slice(1)}</span>{' '}
                  <CrmIcon name="chevron-down" className="iconSize-14" />
                </>
              }
            >
              {(close) =>
                (['day', 'week', 'month'] as const).map((v) => (
                  <button
                    type="button"
                    key={v}
                    data-ss-opt={v}
                    className={view === v ? 'is-selected' : undefined}
                    onClick={() => {
                      setView(v);
                      close();
                    }}
                  >
                    {v.charAt(0).toUpperCase() + v.slice(1)}
                  </button>
                ))
              }
            </SsDropdown>
            <SsDropdown
              toggleClassName="ss-pillbtn"
              menuClassName="ss-menu--key"
              toggle={
                <>
                  Key <CrmIcon name="chevron-down" className="iconSize-14" />
                </>
              }
            >
              {() => (
                <>
                  <label className="ss-key">
                    <input
                      type="checkbox"
                      checked={show.meetings}
                      onChange={(e) => setShow((s) => ({ ...s, meetings: e.target.checked }))}
                    />
                    <i className="ss-dot ss-dot--orange" />
                    CRM meetings
                  </label>
                  <label className="ss-key">
                    <input
                      type="checkbox"
                      checked={show.calendar}
                      onChange={(e) => setShow((s) => ({ ...s, calendar: e.target.checked }))}
                    />
                    <i className="ss-dot ss-dot--blue" />
                    Calendar events
                  </label>
                  <label className="ss-key">
                    <input
                      type="checkbox"
                      checked={show.tasks}
                      onChange={(e) => setShow((s) => ({ ...s, tasks: e.target.checked }))}
                    />
                    <i className="ss-dot ss-dot--purple" />
                    All tasks
                  </label>
                </>
              )}
            </SsDropdown>
            <label className="ss-check">
              <input
                type="checkbox"
                checked={hideWeekends}
                onChange={(e) => setHideWeekends(e.target.checked)}
              />{' '}
              <span>Hide weekends</span>
            </label>
            <div className="ss-arrows">
              <button
                type="button"
                aria-label="Previous"
                onClick={() => setAnchor((a) => stepAnchor(view, a, -1, hideWeekends))}
              >
                <CrmIcon name="chevron-left" className="iconSize-16" />
              </button>
              <button
                type="button"
                aria-label="Next"
                onClick={() => setAnchor((a) => stepAnchor(view, a, 1, hideWeekends))}
              >
                <CrmIcon name="chevron-right" className="iconSize-16" />
              </button>
            </div>
          </div>

          <div className={cn('ss-cal', view === 'month' && 'is-month')}>
            {view === 'month' ? (
              <MonthGrid
                days={days}
                month={dayParts(anchor).month}
                today={today}
                events={placed}
                tasksDue={due}
                onDay={(d) => connected && setSchedule({ day: d, minutes: 540 })}
                onMore={(d) => {
                  setAnchor(d);
                  setView('day');
                }}
                onOpen={openEvent}
              />
            ) : (
              <TimeGrid
                days={days}
                today={today}
                nowMin={Math.round(nowZ.hours * 60)}
                events={placed}
                collapsed={collapsed}
                onToggleAllDay={() => setCollapsed((c) => !c)}
                tasksDue={due}
                outcomes={outcomes}
                onOutcome={(e, v) => void setOutcome(e, v)}
                onSlot={(day, minutes) => connected && setSchedule({ day, minutes })}
                onOpen={openEvent}
                scrollTo={8 * 60}
              />
            )}
          </div>
        </div>
      </section>

      <EventPopover event={popover} timeZone={timeZone} onClose={() => setPopover(null)} />
      <ScheduleMeetingDialog
        open={schedule !== false}
        start={schedule === false ? null : schedule}
        timeZone={timeZone}
        today={today}
        onClose={closeSchedule}
        toast={(m, tone) => toast(m, tone)}
        onCreated={(meeting) => {
          setSchedule(false);
          setAnchor(toZoned(new Date(meeting.startsAt), timeZone).day);
          // the calendar sync brings the event in: load again now and once it has had time
          setReload((r) => r + 1);
          window.setTimeout(() => setReload((r) => r + 1), 4000);
        }}
      />
    </div>
  );
}
