import { useState, useRef, useEffect } from 'react';

const PRESETS = [
  { label: '7d',   days: 7   },
  { label: '28d',  days: 28  },
  { label: '3mo',  days: 90  },
  { label: '6mo',  days: 180 },
  { label: '12mo', days: 365 },
];

function toInputDate(daysAgo) {
  const d = new Date();
  d.setDate(d.getDate() - daysAgo);
  return d.toISOString().split('T')[0];
}

function daysBetween(from, to) {
  const a = new Date(from), b = new Date(to);
  return Math.round((b - a) / 86400000);
}

export default function DateRangePicker({ days, onChange }) {
  const [open, setOpen] = useState(false);
  const [customFrom, setCustomFrom] = useState(toInputDate(days));
  const [customTo, setCustomTo]     = useState(toInputDate(0));
  const ref = useRef();

  useEffect(() => {
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', handler);
    return () => document.removeEventListener('mousedown', handler);
  }, []);

  const activePreset = PRESETS.find(p => p.days === days);

  const applyCustom = () => {
    if (!customFrom || !customTo) return;
    const d = daysBetween(customFrom, customTo);
    if (d > 0 && d <= 500) { onChange(d); setOpen(false); }
  };

  return (
    <div ref={ref} style={{ position: 'relative', display: 'inline-block' }}>
      {/* Preset pills */}
      <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
        {PRESETS.map(p => (
          <button key={p.days} onClick={() => onChange(p.days)}
            style={{
              fontSize: 11, padding: '3px 9px', borderRadius: 20, cursor: 'pointer',
              border: '0.5px solid var(--border2)',
              background: days === p.days ? 'var(--blue)' : 'transparent',
              color:      days === p.days ? '#fff'        : 'var(--text2)',
              fontWeight: days === p.days ? 600           : 400,
              transition: 'all .12s',
            }}>
            {p.label}
          </button>
        ))}
        {/* Custom button */}
        <button onClick={() => setOpen(o => !o)}
          style={{
            fontSize: 11, padding: '3px 9px', borderRadius: 20, cursor: 'pointer',
            border: '0.5px solid var(--border2)',
            background: !activePreset ? 'var(--blue)' : 'transparent',
            color:      !activePreset ? '#fff'        : 'var(--text2)',
            transition: 'all .12s',
          }}>
          {!activePreset ? `Custom (${days}d)` : 'Custom…'}
        </button>
      </div>

      {/* Custom date popover */}
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 6px)', right: 0, zIndex: 100,
          background: 'var(--surface)', border: '0.5px solid var(--border)',
          borderRadius: 10, padding: 14, boxShadow: '0 6px 20px rgba(0,0,0,.12)',
          minWidth: 240,
        }}>
          <div style={{ fontSize: 11, fontWeight: 500, color: 'var(--text2)', marginBottom: 10 }}>Custom date range</div>
          <div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 10 }}>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: 'var(--text3)', marginBottom: 3 }}>From</div>
              <input type="date" value={customFrom} onChange={e => setCustomFrom(e.target.value)}
                max={customTo || toInputDate(1)}
                style={{ width: '100%', fontSize: 12, padding: '4px 7px', borderRadius: 6, border: '0.5px solid var(--border2)', background: 'var(--surface2)', color: 'var(--text)', boxSizing: 'border-box' }} />
            </div>
            <span style={{ fontSize: 11, color: 'var(--text3)', marginTop: 14 }}>→</span>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 10, color: 'var(--text3)', marginBottom: 3 }}>To</div>
              <input type="date" value={customTo} onChange={e => setCustomTo(e.target.value)}
                min={customFrom} max={toInputDate(3)}
                style={{ width: '100%', fontSize: 12, padding: '4px 7px', borderRadius: 6, border: '0.5px solid var(--border2)', background: 'var(--surface2)', color: 'var(--text)', boxSizing: 'border-box' }} />
            </div>
          </div>
          {customFrom && customTo && daysBetween(customFrom, customTo) > 0 && (
            <div style={{ fontSize: 11, color: 'var(--text3)', marginBottom: 8 }}>
              {daysBetween(customFrom, customTo)} days selected
            </div>
          )}
          <button onClick={applyCustom}
            style={{ width: '100%', fontSize: 12, fontWeight: 500, padding: '6px 0', borderRadius: 7, border: 'none', background: 'var(--blue)', color: '#fff', cursor: 'pointer' }}>
            Apply
          </button>
        </div>
      )}
    </div>
  );
}
