'use client';

import { useToast } from '@/components/crm/ToastProvider';
import { FORECAST_REMINDERS, FORECAST_REPEATS, type ForecastSchedule } from '../types';
import { ExtSvg } from './parts';

/** The schedule form's state; `teamId` is `all` for "All teams". */
export interface ScheduleDraft {
  on: boolean;
  start: string;
  time: string;
  rep: string;
  teamId: string;
  rem: string;
}

function nextMonday(): string {
  const d = new Date();
  d.setDate(d.getDate() + ((8 - d.getDay()) % 7 || 7));
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
}

export function emptySchedule(existing: ForecastSchedule | null): ScheduleDraft {
  if (existing) {
    return {
      on: true,
      start: existing.start,
      time: existing.time,
      rep: existing.repeats,
      teamId: existing.teamId ?? 'all',
      rem: existing.reminder,
    };
  }
  return {
    on: false,
    start: nextMonday(),
    time: '8:00 AM',
    rep: '',
    teamId: '',
    rem: '1 hour before due time',
  };
}

export const scheduleOk = (s: ScheduleDraft) =>
  Boolean(s.start && s.time && s.rep && s.teamId && s.rem);

function times(): string[] {
  const out: string[] = [];
  for (let h = 0; h < 24; h++) {
    for (const m of ['00', '30']) out.push(`${h % 12 || 12}:${m} ${h < 12 ? 'AM' : 'PM'}`);
  }
  return out;
}

function gmtLabel(): string {
  const o = -new Date().getTimezoneOffset();
  const a = Math.abs(o);
  const h = Math.floor(a / 60);
  const m = a % 60;
  return `GMT${o < 0 ? '-' : '+'}${h}${m ? `:${String(m).padStart(2, '0')}` : ''}`;
}

/** "CST" for America/Chicago: the company's zone, short (design copy). */
export function zoneLabel(timeZone: string): string {
  try {
    const part = new Intl.DateTimeFormat('en-US', { timeZone, timeZoneName: 'short' })
      .formatToParts(new Date())
      .find((p) => p.type === 'timeZoneName');
    return part?.value ?? timeZone;
  } catch {
    return timeZone;
  }
}

/** Design forecast.js `scheduleStep`: the submission schedule fields. */
export function ScheduleFields({
  draft: s,
  onChange,
  teams,
  timeZone,
  intro,
}: {
  draft: ScheduleDraft;
  onChange: (d: ScheduleDraft) => void;
  teams: Array<{ id: string; name: string }>;
  timeZone: string;
  intro?: string;
}) {
  const toast = useToast();
  const dis = !s.on;
  const zone = zoneLabel(timeZone);
  const set = (patch: Partial<ScheduleDraft>) => onChange({ ...s, ...patch });
  const select = (
    id: string,
    label: string,
    value: string,
    items: Array<[string, string]>,
    placeholder: string,
    key: keyof ScheduleDraft,
    extra?: string,
  ) => (
    <div className="field fc-field">
      <label className="field__label" htmlFor={id}>
        {label} <span className="fc-req">*</span>
        {extra ? <small>{extra}</small> : null}
      </label>
      <select
        className="input"
        id={id}
        disabled={dis}
        value={value}
        onChange={(e) => set({ [key]: e.target.value })}
      >
        {placeholder ? (
          <option value="" disabled>
            {placeholder}
          </option>
        ) : null}
        {items.map(([v, l]) => (
          <option key={v} value={v}>
            {l}
          </option>
        ))}
      </select>
    </div>
  );
  return (
    <>
      <p className="fc-intro fc-intro--l">
        {intro ?? 'Optional: Set up a forecast submission schedule with reminders.'}{' '}
        <button
          type="button"
          className="link"
          onClick={() => toast('Help page coming soon', 'info')}
        >
          Learn more
          <ExtSvg />
        </button>
      </p>
      <div className="fc-note">
        <b>Please note:</b> your local time zone is <b>{gmtLabel()}</b>, but this form uses your
        company’s time zone, <b>{zone}</b>.
      </div>
      <div className="fc-schon">
        <label className="check">
          <input type="checkbox" checked={s.on} onChange={(e) => set({ on: e.target.checked })} />
          <span className="check__box" />
          <b>Set a forecast submission schedule</b>
        </label>
        <p>
          Schedule when forecast submissions are due for selected teams and, optionally, send
          reminders.
        </p>
      </div>
      <div className="fc-row2">
        <div className="field fc-field">
          <label className="field__label" htmlFor="fcSsd">
            Submission schedule start date <span className="fc-req">*</span>
          </label>
          <input
            className="input"
            id="fcSsd"
            type="date"
            disabled={dis}
            value={s.start}
            onChange={(e) => set({ start: e.target.value })}
          />
        </div>
        {select(
          'fcSdt',
          `Due time (${zone})`,
          s.time,
          times().map((t) => [t, t]),
          '',
          'time',
        )}
      </div>
      {select(
        'fcSrp',
        'Repeats',
        s.rep,
        FORECAST_REPEATS.map((r) => [r, r]),
        'Select frequency',
        'rep',
      )}
      {select(
        'fcSas',
        'Assigned to',
        s.teamId,
        [['all', 'All teams'], ...teams.map((t): [string, string] => [t.id, t.name])],
        'Select teams',
        'teamId',
        'The forecast submission schedule applies to all users in the selected team(s). Reminders will only be sent to users who have permission to edit forecasts.',
      )}
      {select(
        'fcSrm',
        'Reminder',
        s.rem,
        FORECAST_REMINDERS.map((r) => [r, r]),
        '',
        'rem',
        'Users will receive an email and/or pop-up notification with a direct link to submit their forecast, based on their individual notification settings.',
      )}
    </>
  );
}
