'use client';

import { useState } from 'react';
import { Calendar, ChevronDown } from 'lucide-react';

export type DashboardPreset = 'today' | '7d' | '30d' | 'month' | 'year' | 'all' | 'custom';

export interface DashboardDateFilterValue {
  preset: DashboardPreset;
  customStart: string;
  customEnd: string;
}

interface DashboardDateFilterProps {
  value: DashboardDateFilterValue;
  onChange: (value: DashboardDateFilterValue) => void;
  loading?: boolean;
}

const PRESETS: { id: DashboardPreset; label: string }[] = [
  { id: 'today', label: 'Today' },
  { id: '7d', label: 'Last 7 Days' },
  { id: '30d', label: 'Last 30 Days' },
  { id: 'month', label: 'This Month' },
  { id: 'year', label: 'This Year' },
  { id: 'all', label: 'All Time' },
];

// Local calendar date (not UTC) — this is "today" from the admin's own
// browser clock, which is what a preset like "Today"/"This Month" should
// mean. toISOString() would silently shift the date near midnight for
// anyone not in UTC, same class of pitfall as the mysql2 local-timezone
// trap documented in DATA_FETCHING_PATTERN.md, just on the client side.
function toDateInputValue(date: Date): string {
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, '0');
  const d = String(date.getDate()).padStart(2, '0');
  return `${y}-${m}-${d}`;
}

export function resolveDashboardDateRange(value: DashboardDateFilterValue): { startDate: string | null; endDate: string | null } {
  const { preset, customStart, customEnd } = value;
  if (preset === 'all') return { startDate: null, endDate: null };
  if (preset === 'custom') {
    return customStart && customEnd ? { startDate: customStart, endDate: customEnd } : { startDate: null, endDate: null };
  }

  const today = new Date();
  const end = toDateInputValue(today);
  let start = new Date(today);

  switch (preset) {
    case 'today':
      break;
    case '7d':
      start.setDate(start.getDate() - 6);
      break;
    case '30d':
      start.setDate(start.getDate() - 29);
      break;
    case 'month':
      start = new Date(today.getFullYear(), today.getMonth(), 1);
      break;
    case 'year':
      start = new Date(today.getFullYear(), 0, 1);
      break;
  }

  return { startDate: toDateInputValue(start), endDate: end };
}

export default function DashboardDateFilter({ value, onChange, loading }: DashboardDateFilterProps) {
  const [customOpen, setCustomOpen] = useState(value.preset === 'custom');

  const handlePresetClick = (preset: DashboardPreset) => {
    setCustomOpen(false);
    onChange({ preset, customStart: value.customStart, customEnd: value.customEnd });
  };

  const activeLabel = value.preset === 'custom'
    ? (value.customStart && value.customEnd ? `${value.customStart} – ${value.customEnd}` : 'Custom Range')
    : PRESETS.find((p) => p.id === value.preset)?.label;

  return (
    <div className="flex flex-wrap items-center gap-2">
      <div className="flex items-center gap-1.5 mr-1" style={{ color: 'var(--color-text-secondary)' }}>
        <Calendar size={16} />
        <span className="text-sm font-medium">{activeLabel}</span>
        {loading && (
          <span className="w-3 h-3 rounded-full border-2 border-t-transparent animate-spin" style={{ borderColor: 'var(--color-cta)', borderTopColor: 'transparent' }} />
        )}
      </div>

      <div className="flex flex-wrap gap-1.5">
        {PRESETS.map((p) => (
          <button
            key={p.id}
            type="button"
            onClick={() => handlePresetClick(p.id)}
            className="px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
            style={{
              background: value.preset === p.id ? 'var(--color-cta)' : 'var(--color-surface-alt)',
              color: value.preset === p.id ? 'white' : 'var(--color-text-secondary)',
              border: `1px solid ${value.preset === p.id ? 'var(--color-cta)' : 'var(--color-border)'}`,
            }}
          >
            {p.label}
          </button>
        ))}
        <button
          type="button"
          onClick={() => setCustomOpen((v) => !v)}
          className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-xs font-medium transition-all"
          style={{
            background: value.preset === 'custom' ? 'var(--color-cta)' : 'var(--color-surface-alt)',
            color: value.preset === 'custom' ? 'white' : 'var(--color-text-secondary)',
            border: `1px solid ${value.preset === 'custom' ? 'var(--color-cta)' : 'var(--color-border)'}`,
          }}
        >
          Custom <ChevronDown size={12} />
        </button>
      </div>

      {customOpen && (
        <div className="flex items-center gap-2 p-2 rounded-lg" style={{ background: 'var(--color-surface-alt)', border: '1px solid var(--color-border)' }}>
          <input
            type="date"
            value={value.customStart}
            max={value.customEnd || undefined}
            onChange={(e) => onChange({ preset: 'custom', customStart: e.target.value, customEnd: value.customEnd })}
            className="px-2 py-1 rounded text-xs outline-none"
            style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
          />
          <span className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>to</span>
          <input
            type="date"
            value={value.customEnd}
            min={value.customStart || undefined}
            onChange={(e) => onChange({ preset: 'custom', customStart: value.customStart, customEnd: e.target.value })}
            className="px-2 py-1 rounded text-xs outline-none"
            style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
          />
        </div>
      )}
    </div>
  );
}
