'use client';

import Link from 'next/link';
import { useEffect, useRef } from 'react';
import { CrmIcon } from '@/components/crm/CrmIcon';
import { optionLabel } from '../../useMeetingOptions';
import { cn } from '@/lib/utils/cn';
import { dayParts, toZoned, weekdayOf } from '@/lib/utils/timezone';
import { overlapLanes } from '../../calendarLayout';
import {
  DOW_SHORT,
  eventStatus,
  fmtMinutes,
  HOUR_PX,
  STATUS_CLASS,
  type EvStatus,
} from '../../calendarView';
import type { CalendarEvent } from '../../types';
import { SsDropdown } from '../scheduler/parts';

/**
 * The Calendar page's week / day time grid and month grid (sales-schedule.js Calendar:
 * renderTimeGrid, renderMonth), on synced Google Calendar events.
 */

/** A calendar entry placed in the viewer's time zone. */
export interface PlacedEvent {
  key: string;
  title: string;
  startDay: string;
  startMin: number;
  endDay: string;
  endMin: number;
  allDay: boolean;
  event: CalendarEvent;
}

export function placeEvents(events: readonly CalendarEvent[], timeZone: string): PlacedEvent[] {
  return events
    .filter((e) => e.status !== 'cancelled' && e.crmMeeting?.status !== 'cancelled')
    .map((e) => {
      if (e.allDay && e.startDate) {
        return {
          key: e.id,
          title: e.title ?? '(No title)',
          startDay: e.startDate,
          startMin: 0,
          endDay: e.endDate ?? e.startDate,
          endMin: 0,
          allDay: true,
          event: e,
        };
      }
      const s = toZoned(new Date(e.startsAt), timeZone);
      const en = toZoned(new Date(e.endsAt), timeZone);
      return {
        key: e.id,
        title: e.title ?? '(No title)',
        startDay: s.day,
        startMin: Math.round(s.hours * 60),
        endDay: en.day,
        endMin: Math.round(en.hours * 60),
        allDay: false,
        event: e,
      };
    });
}

/** The part of a timed event on `day`, in minutes of that day; null when it is not on it. */
function onDay(p: PlacedEvent, day: string): { start: number; end: number } | null {
  if (p.allDay || day < p.startDay || day > p.endDay) return null;
  if (day === p.endDay && p.endMin === 0 && p.endDay !== p.startDay) return null;
  const start = day === p.startDay ? p.startMin : 0;
  const end = day === p.endDay ? p.endMin : 24 * 60;
  return { start, end: Math.max(end, start + 15) };
}

/** All-day events covering `day` (Google's end date is exclusive). */
export const allDayOn = (list: readonly PlacedEvent[], day: string) =>
  list.filter((p) => p.allDay && p.startDay <= day && (day < p.endDay || p.startDay === p.endDay));

export const meetingHref = (e: CalendarEvent) =>
  e.crmMeeting ? `/meetings/${e.crmMeeting.id}?from=/sales-workspace/schedule` : null;

export interface Draft {
  day: string;
  start: number;
  end: number;
  title: string;
}

export function TimeGrid({
  days,
  today,
  nowMin,
  events,
  mini,
  draft,
  collapsed,
  onToggleAllDay,
  tasksDue,
  outcomes,
  onOutcome,
  onSlot,
  onOpen,
  scrollTo,
}: {
  days: readonly string[];
  today: string;
  nowMin: number;
  events: readonly PlacedEvent[];
  mini?: boolean;
  draft?: Draft | null;
  collapsed?: boolean;
  onToggleAllDay?: () => void;
  tasksDue?: Record<string, number>;
  /** Settings > Meetings outcomes. */
  outcomes?: readonly string[];
  onOutcome?: (event: CalendarEvent, value: string) => void;
  onSlot: (day: string, minutes: number) => void;
  onOpen?: (event: CalendarEvent) => void;
  /** Minutes of the day to scroll to when it changes. */
  scrollTo: number;
}) {
  const scrollRef = useRef<HTMLDivElement>(null);
  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = Math.max(0, (scrollTo / 60 - 1) * HOUR_PX);
  }, [scrollTo]);

  const now = Date.now();
  const cols = { '--cols': days.length } as React.CSSProperties;

  const block = (
    p: PlacedEvent,
    span: { start: number; end: number },
    lane: number,
    lanes: number,
  ) => {
    const status: EvStatus = eventStatus(p.event.crmMeeting, Date.parse(p.event.endsAt), now);
    // Beyond 3 side-by-side meetings a column share is a sliver: cascade them instead, each
    // wide enough to read and click, the later one on top.
    const cascade = lanes > 3;
    const w = cascade ? 70 : 100 / lanes;
    const leftPct = cascade ? lane * (30 / (lanes - 1)) : lane * w;
    const h = Math.max(20, ((span.end - span.start) / 60) * HOUR_PX - 2);
    const label = p.event.crmMeeting?.outcome
      ? optionLabel(outcomes ?? [], p.event.crmMeeting.outcome)
      : null;
    return (
      <div
        key={`${p.key}-${span.start}`}
        className={`ss-ev ss-ev--${STATUS_CLASS[status]}${h <= 34 ? 'ss-ev--short' : ''}`}
        {...(mini
          ? {}
          : {
              tabIndex: 0,
              role: 'link',
              onClick: (e: React.MouseEvent) => {
                e.stopPropagation();
                onOpen?.(p.event);
              },
              onKeyDown: (e: React.KeyboardEvent) => {
                if (e.key === 'Enter' && e.target === e.currentTarget) onOpen?.(p.event);
              },
            })}
        title={`${p.title} · ${fmtMinutes(span.start)} - ${fmtMinutes(span.end)}`}
        style={{
          top: (span.start / 60) * HOUR_PX,
          height: h,
          left: `calc(${leftPct}% + 1px)`,
          width: `calc(${w}% - 3px)`,
          zIndex: lane + 1,
        }}
      >
        <span className="ss-ev__t">{p.title}</span>
        {/* #220: a short tile keeps its time, on the title's line (the title gives way). */}
        <span className="ss-ev__time">
          {h > 34 ? `${fmtMinutes(span.start)} - ${fmtMinutes(span.end)}` : fmtMinutes(span.start)}
        </span>
        {!mini && status === 'needs' && outcomes?.length ? (
          <span onClick={(e) => e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()}>
            <SsDropdown
              className="ss-ev__out"
              toggleClassName="ss-ev__outbtn"
              toggle={
                <>
                  Update outcome <CrmIcon name="chevron-down" className="iconSize-12" />
                </>
              }
            >
              {(close) =>
                outcomes.map((o) => (
                  <button
                    type="button"
                    key={o}
                    data-ss-opt={o}
                    onClick={() => {
                      close();
                      onOutcome?.(p.event, o);
                    }}
                  >
                    {o}
                  </button>
                ))
              }
            </SsDropdown>
          </span>
        ) : !mini && label ? (
          <span className="ss-ev__badge">{label}</span>
        ) : null}
      </div>
    );
  };

  return (
    <>
      <div className="ss-cal__head" style={cols}>
        <span />
        {days.map((d) => (
          <div className="ss-dh" key={d}>
            <span>{DOW_SHORT[weekdayOf(d)]}</span>
            <b className={d === today ? 'is-today' : undefined}>{dayParts(d).date}</b>
          </div>
        ))}
      </div>
      {mini ? null : (
        <div className={cn('ss-cal__allday', collapsed && 'is-collapsed')} style={cols}>
          <button
            type="button"
            className="ss-allday-toggle"
            aria-label={`${collapsed ? 'Expand' : 'Collapse'} all-day row`}
            onClick={onToggleAllDay}
          >
            <svg
              className="icon iconSize-12"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.8"
              strokeLinecap="round"
              strokeLinejoin="round"
              aria-hidden
            >
              <path d={collapsed ? 'm6 9 6 6 6-6' : 'm18 15-6-6-6 6'} />
            </svg>
          </button>
          {days.map((d) => {
            const n = tasksDue?.[d] ?? 0;
            const allDay = allDayOn(events, d);
            return (
              <div className="ss-allday-cell" key={d}>
                {collapsed ? null : (
                  <>
                    {n ? (
                      <Link className="ss-taskchip" href="/tasks">
                        <CrmIcon name="list" className="iconSize-14" />
                        {n} task{n > 1 ? 's' : ''} due
                      </Link>
                    ) : null}
                    {allDay.map((p) => (
                      <button
                        type="button"
                        key={p.key}
                        className="ss-mchip ss-mchip--blue"
                        style={{ border: 0, width: '100%', textAlign: 'left', marginTop: 2 }}
                        onClick={() => onOpen?.(p.event)}
                        title={p.title}
                      >
                        {p.title}
                      </button>
                    ))}
                  </>
                )}
              </div>
            );
          })}
        </div>
      )}
      <div className="ss-cal__scroll" ref={scrollRef}>
        <div
          className="ss-cal__body"
          style={{ ...cols, '--h': `${24 * HOUR_PX}px` } as React.CSSProperties}
        >
          <div className="ss-hours">
            {Array.from({ length: 24 }, (_, h) => (
              <div className="ss-hour" style={{ top: h * HOUR_PX }} key={h}>
                <span>{fmtMinutes(h * 60)}</span>
              </div>
            ))}
          </div>
          {days.map((d) => {
            const spans = events
              .map((p) => ({ p, span: onDay(p, d) }))
              .filter((x): x is { p: PlacedEvent; span: { start: number; end: number } } =>
                Boolean(x.span),
              );
            const lanes = overlapLanes(
              spans.map(({ p, span }) => ({
                key: p.key,
                start: span.start / 60,
                end: span.end / 60,
              })),
            );
            return (
              <div
                className="ss-col"
                key={d}
                data-date={d}
                onClick={(e) => {
                  if ((e.target as HTMLElement).closest('.ss-ev:not(.ss-ev--draft)')) return;
                  const y = e.clientY - e.currentTarget.getBoundingClientRect().top;
                  const min = Math.min(
                    23 * 60 + 45,
                    Math.max(0, Math.floor((y / HOUR_PX) * 4) * 15),
                  );
                  onSlot(d, min);
                }}
              >
                {spans.map(({ p, span }) => {
                  const l = lanes.get(p.key) ?? { lane: 0, lanes: 1 };
                  return block(p, span, l.lane, l.lanes);
                })}
                {draft && draft.day === d ? (
                  <div
                    className="ss-ev ss-ev--draft"
                    style={{
                      top: (draft.start / 60) * HOUR_PX,
                      height: Math.max(20, ((draft.end - draft.start) / 60) * HOUR_PX - 2),
                    }}
                  >
                    <span className="ss-ev__t">{draft.title || '(No title)'}</span>
                  </div>
                ) : null}
                {d === today ? (
                  <div className="ss-now" style={{ top: (nowMin / 60) * HOUR_PX }} />
                ) : null}
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
}

export function MonthGrid({
  days,
  month,
  today,
  events,
  tasksDue,
  onDay,
  onMore,
  onOpen,
}: {
  days: readonly string[];
  /** 0-based month shown. */
  month: number;
  today: string;
  events: readonly PlacedEvent[];
  tasksDue?: Record<string, number>;
  onDay: (day: string) => void;
  onMore: (day: string) => void;
  onOpen: (event: CalendarEvent) => void;
}) {
  const cols = days.length > 35 ? 7 : 5;
  const now = Date.now();
  return (
    <div className="ss-month" style={{ '--cols': cols } as React.CSSProperties}>
      <div className="ss-month__head">
        {DOW_SHORT.slice(0, cols).map((d) => (
          <span key={d}>{d}</span>
        ))}
      </div>
      <div className="ss-month__grid">
        {days.map((d) => {
          const list = events
            .filter((p) => (p.allDay ? allDayOn([p], d).length > 0 : p.startDay === d))
            .sort((a, b) => a.startMin - b.startMin);
          const n = tasksDue?.[d] ?? 0;
          return (
            <div
              key={d}
              className={cn('ss-mcell', dayParts(d).month !== month && 'is-out')}
              data-date={d}
              onClick={(e) => {
                if ((e.target as HTMLElement).closest('a,button')) return;
                onDay(d);
              }}
            >
              <b className={d === today ? 'is-today' : undefined}>{dayParts(d).date}</b>
              {n ? (
                <Link className="ss-mchip ss-mchip--purple" href="/tasks">
                  {n} task{n > 1 ? 's' : ''} due
                </Link>
              ) : null}
              {list.slice(0, 3).map((p) => {
                const status = eventStatus(p.event.crmMeeting, Date.parse(p.event.endsAt), now);
                return (
                  <a
                    key={p.key}
                    className={`ss-mchip ss-mchip--${STATUS_CLASS[status]}`}
                    href={meetingHref(p.event) ?? p.event.htmlLink ?? '#'}
                    onClick={(e) => {
                      e.preventDefault();
                      onOpen(p.event);
                    }}
                  >
                    {p.allDay ? '' : `${fmtMinutes(p.startMin)} `}
                    {p.title}
                  </a>
                );
              })}
              {list.length > 3 ? (
                <button type="button" className="ss-more" onClick={() => onMore(d)}>
                  +{list.length - 3} more
                </button>
              ) : null}
            </div>
          );
        })}
      </div>
    </div>
  );
}
