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

type TimerMode = 'pomodoro' | 'countdown' | 'stopwatch';

interface Preset {
  label: string;
  minutes: number;
}

const POMODORO_PRESETS: Preset[] = [
  { label: 'Focus', minutes: 25 },
  { label: 'Short', minutes: 5 },
  { label: 'Long', minutes: 15 },
];

const COUNTDOWN_PRESETS: Preset[] = [
  { label: '5 min', minutes: 5 },
  { label: '10 min', minutes: 10 },
  { label: '30 min', minutes: 30 },
  { label: '1 hr', minutes: 60 },
];

function formatTime(seconds: number): string {
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
}

export default function Timer() {
  const [mode, setMode] = useState<TimerMode>('pomodoro');
  const [presetMinutes, setPresetMinutes] = useState(25);
  const [remaining, setRemaining] = useState(25 * 60);
  const [running, setRunning] = useState(false);
  const [sessions, setSessions] = useState(0);
  const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const stop = useCallback(() => {
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = null;
    setRunning(false);
  }, []);

  const reset = useCallback(() => {
    stop();
    setRemaining(presetMinutes * 60);
  }, [presetMinutes, stop]);

  const startStop = () => {
    if (running) {
      stop();
    } else {
      if (remaining <= 0) reset();
      setRunning(true);
    }
  };

  const selectPreset = (mins: number) => {
    stop();
    setPresetMinutes(mins);
    setRemaining(mins * 60);
  };

  const addTime = (mins: number) => {
    setRemaining((r) => r + mins * 60);
  };

  useEffect(() => {
    if (!running) return;
    intervalRef.current = setInterval(() => {
      setRemaining((r) => {
        if (mode === 'stopwatch') {
          return r + 1;  // count UP for stopwatch
        }
        if (r <= 1) {
          stop();
          if (mode === 'pomodoro') setSessions((s) => s + 1);
          return 0;
        }
        return r - 1;
      });
    }, 1000);
    return stop;
  }, [running, mode, stop]);

  const progress = mode === 'stopwatch' ? 0 : (presetMinutes > 0 ? 1 - remaining / (presetMinutes * 60) : 0);

  return (
    <div className="p-4">
      {/* Mode tabs */}
      <div className="flex gap-1 mb-3 bg-kira-glow rounded-xl p-1">
        {(['pomodoro', 'countdown', 'stopwatch'] as TimerMode[]).map((m) => (
          <button
            key={m}
            onClick={() => { setMode(m); stop(); setRemaining(m === 'pomodoro' ? 25 * 60 : m === 'countdown' ? 5 * 60 : 0); setPresetMinutes(m === 'pomodoro' ? 25 : m === 'countdown' ? 5 : 0); }}
            className={`flex-1 text-xs font-semibold py-1.5 rounded-lg transition-all capitalize ${mode === m ? 'bg-white text-kira-plum shadow-sm' : 'text-kira-plum/50 hover:text-kira-plum'}`}
          >
            {m === 'pomodoro' ? '🍅 Focus' : m === 'countdown' ? '⏳ Timer' : '⏱️ Stopwatch'}
          </button>
        ))}
      </div>

      {/* Presets */}
      <div className="flex gap-2 mb-3 flex-wrap">
        {(mode === 'pomodoro' ? POMODORO_PRESETS : COUNTDOWN_PRESETS).map((p) => (
          <button
            key={p.label}
            onClick={() => selectPreset(p.minutes)}
            className={`text-xs font-medium px-3 py-1 rounded-full transition-all ${presetMinutes === p.minutes && !running ? 'bg-kira-pink text-white' : 'bg-white/60 text-kira-plum/60 hover:bg-kira-glow'}`}
          >
            {p.label}
          </button>
        ))}
      </div>

      {/* Timer display */}
      <div className="text-center py-2">
        <div className="text-5xl font-extrabold tracking-widest text-kira-plum tabular-nums">
          {formatTime(remaining)}
        </div>

        {/* Progress bar */}
        <div className="w-full h-1.5 bg-kira-glow rounded-full mt-3 overflow-hidden">
          <div
            className="h-full bg-gradient-to-r from-kira-pink to-kira-lav rounded-full transition-all duration-1000"
            style={{ width: `${Math.min(100, progress * 100)}%` }}
          />
        </div>

        {mode === 'pomodoro' && sessions > 0 && (
          <div className="text-xs text-kira-violet/50 mt-1">
            {sessions} focus session{sessions > 1 ? 's' : ''} completed
          </div>
        )}
      </div>

      {/* Controls */}
      <div className="flex gap-2 justify-center mt-2">
        <button onClick={startStop} className="btn-kira px-8 py-2 text-sm">
          {running ? '⏸️ Pause' : remaining === 0 && mode !== 'stopwatch' ? '🔄 Restart' : '▶️ Start'}
        </button>
        {running && (
          <button onClick={() => addTime(5)} className="bg-white/60 text-kira-plum/60 px-3 py-2 rounded-xl text-sm font-medium hover:bg-kira-glow transition-all">
            +5m
          </button>
        )}
        {remaining > 0 && !running && (
          <button onClick={reset} className="bg-white/60 text-kira-plum/40 px-3 py-2 rounded-xl text-sm hover:bg-kira-glow transition-all">
            🔄 Reset
          </button>
        )}
      </div>
    </div>
  );
}
