'use client';

import { useEffect, useState } from 'react';

const OPTIONS = [['all', 'All'], ['day', 'Day'], ['week', 'Week'], ['month', 'Month'], ['custom', 'Custom']] as const;
type Scope = typeof OPTIONS[number][0];
export type HistoryDateRange = { scope: Scope; from: string; to: string };
const ghanaDate = new Intl.DateTimeFormat('en-CA', { timeZone: 'Africa/Accra', year: 'numeric', month: '2-digit', day: '2-digit' });
const labelDate = new Intl.DateTimeFormat('en-GB', { timeZone: 'UTC', day: 'numeric', month: 'short', year: 'numeric' });
const isoDate = (date: Date) => date.toISOString().slice(0, 10);
const parseDate = (date: string) => new Date(date + 'T00:00:00Z');
const inputClass = 'block min-h-9 w-full min-w-0 rounded-md border border-slate-200 bg-white px-2 text-sm text-slate-900';

function preset(scope: Exclude<Scope, 'custom'>): HistoryDateRange {
  if (scope === 'all') return { scope, from: '', to: '' };
  const parts = Object.fromEntries(ghanaDate.formatToParts(new Date()).map(part => [part.type, part.value]));
  const start = parseDate(`${parts.year}-${parts.month}-${parts.day}`);
  const end = new Date(start);
  if (scope === 'week') {
    start.setUTCDate(start.getUTCDate() - (start.getUTCDay() + 6) % 7);
    end.setTime(start.getTime());
    end.setUTCDate(end.getUTCDate() + 6);
  } else if (scope === 'month') {
    start.setUTCDate(1);
    end.setUTCMonth(end.getUTCMonth() + 1, 0);
  }
  return { scope, from: isoDate(start), to: isoDate(end) };
}

export function HistoryDateFilter({ range, onChange }: { range: HistoryDateRange; onChange: (value: HistoryDateRange) => void }) {
  const [editingCustom, setEditingCustom] = useState(false);
  const [from, setFrom] = useState('');
  const [to, setTo] = useState('');
  useEffect(() => {
    if (range.scope !== 'all') return;
    setEditingCustom(false);
    setFrom('');
    setTo('');
  }, [range]);
  const invalid = Boolean(from && to && from > to);
  return <div className="space-y-2">
    <div role="group" aria-label="History date range" className="grid grid-cols-3 gap-0.5 rounded-md bg-slate-100 p-1 min-[320px]:grid-cols-5">
      {OPTIONS.map(([scope, text]) => {
        const active = (editingCustom ? 'custom' : range.scope) === scope;
        return <button key={scope} type="button" aria-pressed={active}
          onClick={() => {
            setEditingCustom(scope === 'custom');
            if (scope !== 'custom') onChange(preset(scope));
          }}
          className={`min-h-9 rounded px-0.5 text-[10px] font-semibold focus-visible:outline focus-visible:outline-2 focus-visible:outline-emerald-700 min-[320px]:text-xs ${active ? 'bg-white text-emerald-800 shadow-sm' : 'text-slate-600'}`}>
          {text}
        </button>;
      })}
    </div>
    {editingCustom && <form className="space-y-2" onSubmit={event => {
      event.preventDefault();
      if (from && to && !invalid) onChange({ scope: 'custom', from, to });
    }}>
      <div className="grid gap-2 min-[360px]:grid-cols-2">
        <label className="min-w-0 space-y-1 text-xs font-semibold text-slate-700">
          <span>From</span>
          <input type="date" required value={from} onChange={event => setFrom(event.target.value)} className={inputClass} />
        </label>
        <label className="min-w-0 space-y-1 text-xs font-semibold text-slate-700">
          <span>To</span>
          <input type="date" required value={to} onChange={event => setTo(event.target.value)} className={inputClass} />
        </label>
      </div>
      {invalid && <p role="alert" className="text-xs text-red-700">To must be on or after From.</p>}
      <button type="submit" disabled={!from || !to || invalid} className="min-h-9 w-full rounded-md bg-emerald-700 text-xs font-semibold text-white disabled:bg-slate-200 disabled:text-slate-600">Apply dates</button>
    </form>}
    <p role="status" className="text-xs text-slate-600">
      {range.scope === 'all' ? 'All dates in this period' : range.from === range.to
        ? labelDate.format(parseDate(range.from))
        : `${labelDate.format(parseDate(range.from))} to ${labelDate.format(parseDate(range.to))}`}
    </p>
  </div>;
}
