import { useEffect, useState } from 'react';
import type { ScheduleConfig } from '../../lib/types';
import { useScheduleSettings, useUpdateScheduleSettings } from '../../hooks/useAdmin';
import { SkeletonTable } from '../ui/Skeleton';

const DEFAULTS: ScheduleConfig = {
  schedule_timezone: 'America/New_York',
  schedule_daily_pipeline_cron: '0 2 * * *',
  schedule_near_close_pipeline_cron: '30 15 * * 1-5',
  schedule_after_close_pipeline_cron: '45 16 * * 1-5',
  schedule_intraday_pipeline_cron: '0 10-15 * * 1-5',
  schedule_fundamentals_cron: '0 1 * * 1',
};

const FIELDS: { key: keyof ScheduleConfig; label: string; hint: string; mono?: boolean }[] = [
  {
    key: 'schedule_timezone',
    label: 'Timezone',
    hint: 'IANA name. Prefer America/New_York so the near-close scan tracks the US cash close through DST.',
  },
  {
    key: 'schedule_daily_pipeline_cron',
    label: 'Morning pipeline',
    hint: 'OHLCV → benchmark → sentiment → regime → alerts (no R:R scan). Default 02:00 ET so regime-quadrant changes hit Telegram in the morning.',
    mono: true,
  },
  {
    key: 'schedule_near_close_pipeline_cron',
    label: 'Near-close pipeline (scan + alert)',
    hint: 'OHLCV fetch → R:R scan → Telegram. Default 15:30 ET Mon–Fri so manual MOC fills can still hit ~15:50/15:55.',
    mono: true,
  },
  {
    key: 'schedule_after_close_pipeline_cron',
    label: 'After-close pipeline (outcome)',
    hint: 'OHLCV fetch (final bar) → outcome eval. Default 16:45 ET Mon–Fri — not chained to the partial near-close bar.',
    mono: true,
  },
  {
    key: 'schedule_intraday_pipeline_cron',
    label: 'Intraday pipeline (light)',
    hint: 'Refresh prices + resolve outcomes mid-session. Default hourly 10:00–15:00 ET weekdays.',
    mono: true,
  },
  {
    key: 'schedule_fundamentals_cron',
    label: 'Fundamentals (weekly)',
    hint: 'Slow, rate-limited. Default early Monday ET.',
    mono: true,
  },
];

export function ScheduleSettings() {
  const { data, isLoading, isError, error } = useScheduleSettings();
  const update = useUpdateScheduleSettings();

  const [form, setForm] = useState<ScheduleConfig>(DEFAULTS);

  useEffect(() => {
    if (data) setForm({ ...DEFAULTS, ...data });
  }, [data]);

  if (isLoading) return <SkeletonTable rows={2} cols={2} />;
  if (isError) return <p className="text-sm text-red-400">{(error as Error)?.message || 'Failed to load schedule'}</p>;

  return (
    <div className="glass p-5 space-y-4">
      <div>
        <h3 className="text-sm font-semibold text-gray-200">Pipeline Schedule</h3>
        <p className="mt-1 text-xs text-gray-500">
          When the jobs run, as 5-field cron (<span className="num">min hour day month weekday</span>).
          Saved changes apply to the running scheduler immediately — no redeploy.
          One qualifying R:R scan per day is the near-close job; alerts fire immediately after that scan.
        </p>
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {FIELDS.map((f) => (
          <label key={f.key} className="block space-y-1">
            <span className="text-xs text-gray-400">{f.label}</span>
            <input
              type="text"
              value={form[f.key] ?? ''}
              spellCheck={false}
              onChange={(e) => setForm((prev) => ({ ...prev, [f.key]: e.target.value }))}
              className={`w-full input-glass px-3 py-2 text-sm ${f.mono ? 'num' : ''}`}
            />
            <span className="block text-[11px] text-gray-600">{f.hint}</span>
          </label>
        ))}
      </div>

      <div className="flex items-center gap-2">
        <button
          className="btn-primary px-4 py-2 text-sm"
          onClick={() => update.mutate(form)}
          disabled={update.isPending}
        >
          {update.isPending ? 'Saving…' : 'Save Schedule'}
        </button>
        <button
          className="px-4 py-2 text-sm rounded border border-white/[0.1] text-gray-300 hover:text-white"
          onClick={() => {
            setForm(DEFAULTS);
            update.mutate(DEFAULTS);
          }}
          disabled={update.isPending}
        >
          Reset to Defaults
        </button>
      </div>
    </div>
  );
}
