'use client';
import { useState } from 'react';

export type Preset = 'all' | 'today' | 'week' | 'month' | 'quarter' | 'year' | 'custom';

function iso(d: Date): string { return d.toISOString().slice(0, 10); }

export function presetRange(p: Preset, customFrom: string, customTo: string): { from: string; to: string } | null {
  const now = new Date();
  if (p === 'all') return null;
  if (p === 'custom') return customFrom || customTo ? { from: customFrom, to: customTo } : null;
  const start = new Date(now);
  if (p === 'today') return { from: iso(now), to: iso(now) };
  if (p === 'week') { const d = new Date(now); d.setDate(d.getDate() - d.getDay()); start.setTime(d.getTime()); }
  if (p === 'month') start.setDate(1);
  if (p === 'quarter') start.setMonth(Math.floor(now.getMonth() / 3) * 3, 1);
  if (p === 'year') start.setMonth(0, 1);
  const end = new Date(now);
  if (p === 'week') { const d = new Date(start); d.setDate(d.getDate() + 6); end.setTime(d.getTime()); }
  if (p === 'month') { const d = new Date(now.getFullYear(), now.getMonth() + 1, 0); end.setTime(d.getTime()); }
  if (p === 'quarter') { const d = new Date(start); d.setMonth(d.getMonth() + 3, 0); end.setTime(d.getTime()); }
  if (p === 'year') end.setMonth(11, 31);
  return { from: iso(start), to: iso(end) };
}

export function DatePresets({ preset, setPreset, from, to, setFrom, setTo }: {
  preset: Preset; setPreset: (p: Preset) => void;
  from: string; to: string; setFrom: (v: string) => void; setTo: (v: string) => void;
}) {
  const [p, sp] = [preset, setPreset];
  return (
    <div className="flex flex-wrap gap-2 items-center">
      <select aria-label="Date range preset" className="input max-w-44 text-sm" value={p} onChange={(e) => sp(e.target.value as Preset)}>
        <option value="all">All time</option>
        <option value="today">Today</option>
        <option value="week">This week</option>
        <option value="month">This month</option>
        <option value="quarter">This quarter</option>
        <option value="year">This year</option>
        <option value="custom">Custom range</option>
      </select>
      {p === 'custom' && (
        <>
          <input aria-label="From date" type="date" className="input max-w-44 text-sm" value={from} onChange={(e) => setFrom(e.target.value)} />
          <input aria-label="To date" type="date" className="input max-w-44 text-sm" value={to} onChange={(e) => setTo(e.target.value)} />
        </>
      )}
    </div>
  );
}

export function useDateFilter() {
  const [preset, setPreset] = useState<Preset>('all');
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  const range = presetRange(preset, from, to);
  const qs = range ? `&from=${range.from}&to=${range.to}` : '';
  return { preset, setPreset, from, to, setFrom, setTo, qs };
}
