'use client';

import { useMemo, useRef, useState } from 'react';
import { AnchoredPopover } from '@/components/crm/AnchoredPopover';
import { cn } from '@/lib/utils/cn';
import { addDays, toZoned, weekdayOf } from '@/lib/utils/timezone';

const DOW = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];

export type FollowUpDueKey =
  | 'today'
  | 'tomorrow'
  | 'biz2'
  | 'biz3'
  | 'week1'
  | 'week2'
  | 'month1'
  | 'month3'
  | 'month6'
  | 'custom';

/** Skip Sat/Sun; `n` business days after `fromDay`. */
export function addBusinessDays(fromDay: string, n: number): string {
  let day = fromDay;
  let left = n;
  while (left > 0) {
    day = addDays(day, 1);
    if (weekdayOf(day) < 5) left -= 1;
  }
  return day;
}

function weekdayName(day: string): string {
  const parts = day.split('-').map(Number);
  const utc = new Date(Date.UTC(parts[0]!, parts[1]! - 1, parts[2]!));
  return DOW[utc.getUTCDay()] ?? '';
}

function shortDate(day: string): string {
  const parts = day.split('-').map(Number);
  const months = [
    'Jan',
    'Feb',
    'Mar',
    'Apr',
    'May',
    'Jun',
    'Jul',
    'Aug',
    'Sep',
    'Oct',
    'Nov',
    'Dec',
  ];
  return `${months[parts[1]! - 1]} ${parts[2]}`;
}

/** `n` months after `day`; a day the month lacks lands on its last day (31 Jan + 1 = 28 Feb). */
export function addMonths(day: string, n: number): string {
  const [year, month, date] = day.split('-').map(Number) as [number, number, number];
  const lastDate = new Date(Date.UTC(year, month - 1 + n + 1, 0)).getUTCDate();
  const target = new Date(Date.UTC(year, month - 1 + n, Math.min(date, lastDate)));
  return target.toISOString().slice(0, 10);
}

export function followUpDueDate(
  key: FollowUpDueKey,
  timeZone: string,
  customDate?: string,
): string {
  const today = toZoned(new Date(), timeZone).day;
  switch (key) {
    case 'today':
      return today;
    case 'tomorrow':
      return addDays(today, 1);
    case 'biz2':
      return addBusinessDays(today, 2);
    case 'biz3':
      return addBusinessDays(today, 3);
    case 'week1':
      return addDays(today, 7);
    case 'week2':
      return addDays(today, 14);
    case 'month1':
      return addMonths(today, 1);
    case 'month3':
      return addMonths(today, 3);
    case 'month6':
      return addMonths(today, 6);
    case 'custom':
      return customDate && /^\d{4}-\d{2}-\d{2}$/.test(customDate) ? customDate : today;
  }
}

export function dueOptions(timeZone: string, { months = false }: { months?: boolean } = {}) {
  const today = toZoned(new Date(), timeZone).day;
  const biz2 = addBusinessDays(today, 2);
  const biz3 = addBusinessDays(today, 3);
  const week1 = addDays(today, 7);
  const week2 = addDays(today, 14);
  const inMonths = (n: number) =>
    `In ${n} month${n === 1 ? '' : 's'} (${shortDate(addMonths(today, n))})`;
  return [
    { key: 'today' as const, label: 'Today' },
    { key: 'tomorrow' as const, label: 'Tomorrow' },
    { key: 'biz2' as const, label: `In 2 business days (${weekdayName(biz2)})` },
    { key: 'biz3' as const, label: `In 3 business days (${weekdayName(biz3)})` },
    { key: 'week1' as const, label: `In 1 week (${shortDate(week1)})` },
    { key: 'week2' as const, label: `In 2 weeks (${shortDate(week2)})` },
    ...(months
      ? [
          { key: 'month1' as const, label: inMonths(1) },
          { key: 'month3' as const, label: inMonths(3) },
          { key: 'month6' as const, label: inMonths(6) },
        ]
      : []),
    { key: 'custom' as const, label: 'Custom date' },
  ];
}

/**
 * "Create a To-do task to follow up In 3 business days (Tuesday)" with portal menus.
 */
export function FollowUpTaskControls({
  enabled,
  onEnabledChange,
  taskType,
  onTaskTypeChange,
  dueKey,
  onDueKeyChange,
  customDate,
  onCustomDateChange,
  timeZone,
  composer = false,
}: {
  enabled: boolean;
  onEnabledChange: (v: boolean) => void;
  taskType: string;
  onTaskTypeChange: (v: string) => void;
  dueKey: FollowUpDueKey;
  onDueKeyChange: (v: FollowUpDueKey) => void;
  customDate: string;
  onCustomDateChange: (v: string) => void;
  timeZone: string;
  /** Contacts composer: the design's row, with carets and the month presets. */
  composer?: boolean;
}) {
  const [typeOpen, setTypeOpen] = useState(false);
  const [dueOpen, setDueOpen] = useState(false);
  const typeRef = useRef<HTMLButtonElement>(null);
  const dueRef = useRef<HTMLButtonElement>(null);
  const today = toZoned(new Date(), timeZone).day;
  const options = useMemo(() => dueOptions(timeZone, { months: composer }), [timeZone, composer]);
  const canPick = enabled || composer;
  const caret = composer ? (
    <svg viewBox="0 0 24 24" aria-hidden className="acx-caret">
      <path d="M7 10l5 5 5-5z" fill="currentColor" />
    </svg>
  ) : null;
  const dueLabel =
    dueKey === 'custom'
      ? customDate
        ? `Custom (${shortDate(customDate)})`
        : 'Custom date'
      : (options.find((o) => o.key === dueKey)?.label ?? 'In 3 business days');
  const typeLabel = taskType === 'call' ? 'Call' : taskType === 'email' ? 'Email' : 'To-do';

  return (
    <div className={cn('activity-followup', composer && 'acx-row acx-follow')}>
      <label className="activity-followup__row">
        <input
          type="checkbox"
          checked={enabled}
          onChange={(e) => onEnabledChange(e.target.checked)}
        />
        <span className="activity-followup__text">
          Create a{' '}
          <span className="activity-followup__dd">
            <button
              ref={typeRef}
              type="button"
              className="activity-followup__trigger"
              disabled={!canPick}
              aria-expanded={typeOpen}
              onClick={() => {
                setTypeOpen((o) => !o);
                setDueOpen(false);
              }}
            >
              {typeLabel}
              {caret}
            </button>
            <AnchoredPopover
              open={typeOpen && canPick}
              anchorRef={typeRef}
              onClose={() => setTypeOpen(false)}
              className="activity-followup__menu"
              label="Task type"
              width={148}
              maxHeight={220}
              preferred="up"
            >
              <ul role="listbox">
                {[
                  { value: 'todo', label: 'To-do' },
                  { value: 'call', label: 'Call' },
                  { value: 'email', label: 'Email' },
                ].map((o) => (
                  <li key={o.value}>
                    <button
                      type="button"
                      className={cn(taskType === o.value && 'is-active')}
                      onClick={() => {
                        onTaskTypeChange(o.value);
                        setTypeOpen(false);
                        if (composer) onEnabledChange(true);
                      }}
                    >
                      {o.label}
                    </button>
                  </li>
                ))}
              </ul>
            </AnchoredPopover>
          </span>{' '}
          task to follow up{' '}
          <span className="activity-followup__dd">
            <button
              ref={dueRef}
              type="button"
              className="activity-followup__trigger"
              disabled={!canPick}
              aria-expanded={dueOpen}
              onClick={() => {
                setDueOpen((o) => !o);
                setTypeOpen(false);
              }}
            >
              {dueLabel}
              {caret}
            </button>
            <AnchoredPopover
              open={dueOpen && canPick}
              anchorRef={dueRef}
              onClose={() => setDueOpen(false)}
              className="activity-followup__menu activity-followup__menu--wide"
              label="Due date"
              width={260}
              maxHeight={340}
              preferred="up"
            >
              <ul role="listbox">
                {options.map((o) => (
                  <li key={o.key}>
                    <button
                      type="button"
                      className={cn(dueKey === o.key && 'is-active')}
                      onClick={() => {
                        onDueKeyChange(o.key);
                        if (composer) onEnabledChange(true);
                        if (o.key === 'custom') {
                          if (!customDate) onCustomDateChange(today);
                        } else {
                          setDueOpen(false);
                        }
                      }}
                    >
                      {o.label}
                    </button>
                  </li>
                ))}
              </ul>
              {dueKey === 'custom' ? (
                <div className="activity-followup__custom">
                  <input
                    type="date"
                    className="input"
                    value={customDate || today}
                    min={today}
                    aria-label="Custom follow-up date"
                    onChange={(e) => {
                      onCustomDateChange(e.target.value);
                      if (e.target.value) setDueOpen(false);
                    }}
                  />
                </div>
              ) : null}
            </AnchoredPopover>
          </span>
        </span>
      </label>
    </div>
  );
}
