'use client';

import * as React from 'react';

const DAYS_OF_WEEK = [
  { key: 'sun', label: 'S', long: 'Sunday' },
  { key: 'mon', label: 'M', long: 'Monday' },
  { key: 'tue', label: 'T', long: 'Tuesday' },
  { key: 'wed', label: 'W', long: 'Wednesday' },
  { key: 'thu', label: 'T', long: 'Thursday' },
  { key: 'fri', label: 'F', long: 'Friday' },
  { key: 'sat', label: 'S', long: 'Saturday' },
];

const FREQUENCIES = [
  { value: 'on-demand', label: 'On demand only' },
  { value: 'hourly', label: 'Every few hours' },
  { value: 'daily', label: 'Daily' },
  { value: 'weekly', label: 'Weekly' },
  { value: 'monthly', label: 'Monthly' },
  { value: 'every-n-months', label: 'Every few months' },
  { value: 'once', label: 'Run once on a date' },
];

// Parse an existing schedule string back into the picker's structured state.
function parseSpec(spec) {
  const s = String(spec || '').trim().toLowerCase();
  if (!s || s === 'on demand' || s === 'manual' || s === 'live' || s === 'event based') {
    return { frequency: 'on-demand' };
  }
  let m;
  if ((m = s.match(/^every\s+(\d{1,3})\s*h$/))) {
    return { frequency: 'hourly', interval: Number(m[1]) };
  }
  if ((m = s.match(/^daily\s+(\d{1,2}):(\d{2})$/))) {
    return { frequency: 'daily', time: `${m[1].padStart(2, '0')}:${m[2]}` };
  }
  if ((m = s.match(/^weekly\s+(\w+)\s+(\d{1,2}):(\d{2})$/))) {
    return { frequency: 'weekly', day: m[1].slice(0, 3), time: `${m[2].padStart(2, '0')}:${m[3]}` };
  }
  if ((m = s.match(/^monthly\s+(last|\d{1,2})\s+(\d{1,2}):(\d{2})$/))) {
    return { frequency: 'monthly', dom: m[1], time: `${m[2].padStart(2, '0')}:${m[3]}` };
  }
  if ((m = s.match(/^every\s+(\d{1,3})\s*mo$/))) {
    return { frequency: 'every-n-months', months: Number(m[1]) };
  }
  if ((m = s.match(/^at\s+(.+)$/))) {
    return { frequency: 'once', datetime: m[1] };
  }
  return { frequency: 'on-demand' };
}

function buildSpec(state) {
  switch (state.frequency) {
    case 'on-demand':
      return 'on demand';
    case 'hourly':
      return `every ${state.interval || 1}h`;
    case 'daily':
      return `daily ${state.time || '09:00'}`;
    case 'weekly':
      return `weekly ${state.day || 'mon'} ${state.time || '09:00'}`;
    case 'monthly':
      return `monthly ${state.dom || '1'} ${state.time || '09:00'}`;
    case 'every-n-months':
      return `every ${state.months || 3}mo`;
    case 'once':
      return state.datetime ? `at ${state.datetime}` : 'on demand';
    default:
      return 'on demand';
  }
}

export default function SchedulePicker({ defaultValue = 'on demand', name = 'schedule' }) {
  const [state, setState] = React.useState(() => {
    const parsed = parseSpec(defaultValue);
    return {
      frequency: parsed.frequency,
      interval: parsed.interval || 6,
      time: parsed.time || '09:00',
      day: parsed.day || 'mon',
      dom: parsed.dom || '1',
      months: parsed.months || 3,
      datetime: parsed.datetime || '',
    };
  });

  const set = (patch) => setState((prev) => ({ ...prev, ...patch }));
  const value = buildSpec(state);

  // datetime-local needs YYYY-MM-DDTHH:mm (local), not full ISO.
  const datetimeLocalValue = React.useMemo(() => {
    if (!state.datetime) return '';
    const d = new Date(state.datetime);
    if (Number.isNaN(d.getTime())) return '';
    const pad = (n) => String(n).padStart(2, '0');
    return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
  }, [state.datetime]);

  return (
    <div className="schedule-picker">
      <input type="hidden" name={name} value={value} />

      <label className="agents-modal-field wide">
        <select
          value={state.frequency}
          onChange={(e) => set({ frequency: e.target.value })}
          aria-label="How often this agent runs"
        >
          {FREQUENCIES.map((f) => (
            <option key={f.value} value={f.value}>
              {f.label}
            </option>
          ))}
        </select>
      </label>

      {state.frequency === 'hourly' && (
        <div className="schedule-picker-row">
          <span className="schedule-picker-prefix">Every</span>
          <select
            className="schedule-picker-select"
            value={state.interval}
            onChange={(e) => set({ interval: Number(e.target.value) })}
            aria-label="Interval in hours"
          >
            {[1, 2, 3, 4, 6, 8, 12].map((n) => (
              <option key={n} value={n}>
                {n}
              </option>
            ))}
          </select>
          <span className="schedule-picker-suffix">{state.interval === 1 ? 'hour' : 'hours'}</span>
        </div>
      )}

      {state.frequency === 'daily' && (
        <div className="schedule-picker-row">
          <span className="schedule-picker-prefix">At</span>
          <input
            className="schedule-picker-time"
            type="time"
            value={state.time}
            onChange={(e) => set({ time: e.target.value })}
            aria-label="Time of day"
          />
        </div>
      )}

      {state.frequency === 'weekly' && (
        <div className="schedule-picker-stack">
          <div className="schedule-picker-day-row" role="radiogroup" aria-label="Day of week">
            {DAYS_OF_WEEK.map((d) => (
              <label
                key={d.key}
                className={`schedule-picker-day-chip${state.day === d.key ? ' on' : ''}`}
                title={d.long}
              >
                <input
                  type="radio"
                  name="schedule-day"
                  value={d.key}
                  checked={state.day === d.key}
                  onChange={() => set({ day: d.key })}
                  aria-label={d.long}
                />
                <span>{d.label}</span>
              </label>
            ))}
          </div>
          <div className="schedule-picker-row">
            <span className="schedule-picker-prefix">At</span>
            <input
              className="schedule-picker-time"
              type="time"
              value={state.time}
              onChange={(e) => set({ time: e.target.value })}
              aria-label="Time of day"
            />
          </div>
        </div>
      )}

      {state.frequency === 'monthly' && (
        <div className="schedule-picker-row">
          <span className="schedule-picker-prefix">On day</span>
          <select
            className="schedule-picker-select"
            value={state.dom}
            onChange={(e) => set({ dom: e.target.value })}
            aria-label="Day of month"
          >
            {Array.from({ length: 28 }, (_, i) => i + 1).map((n) => (
              <option key={n} value={String(n)}>
                {n}
              </option>
            ))}
            <option value="last">Last day</option>
          </select>
          <span className="schedule-picker-prefix">at</span>
          <input
            className="schedule-picker-time"
            type="time"
            value={state.time}
            onChange={(e) => set({ time: e.target.value })}
            aria-label="Time of day"
          />
        </div>
      )}

      {state.frequency === 'every-n-months' && (
        <div className="schedule-picker-row">
          <span className="schedule-picker-prefix">Every</span>
          <select
            className="schedule-picker-select"
            value={state.months}
            onChange={(e) => set({ months: Number(e.target.value) })}
            aria-label="Number of months"
          >
            <option value={2}>2 months</option>
            <option value={3}>3 months · quarterly</option>
            <option value={4}>4 months</option>
            <option value={6}>6 months · biannually</option>
            <option value={12}>12 months · yearly</option>
          </select>
        </div>
      )}

      {state.frequency === 'once' && (
        <div className="schedule-picker-row">
          <span className="schedule-picker-prefix">On</span>
          <input
            className="schedule-picker-datetime"
            type="datetime-local"
            value={datetimeLocalValue}
            onChange={(e) => {
              const v = e.target.value;
              set({ datetime: v ? new Date(v).toISOString() : '' });
            }}
            aria-label="Date and time"
          />
        </div>
      )}
    </div>
  );
}
