import { useState, useEffect, useRef } from 'react';
import { useTimingStore } from '@/stores/timingStore';
import { useStudentStore } from '@/stores/studentStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useUIStore } from '@/stores/uiStore';
import { format } from 'date-fns';
import { Play, Square, RotateCcw, Flag, Loader2 } from 'lucide-react';

export default function TimingEntryScreen() {
  const { isRunning, elapsedMs, laps, startTimer, stopTimer, resetTimer, recordLap, saveTiming } = useTimingStore();
  const { students } = useStudentStore();
  const { records: attendanceRecords } = useAttendanceStore();
  const { showToast } = useUIStore();

  // Only show PRESENT students (Feature 2)
  const today = format(new Date(), 'yyyy-MM-dd');
  const presentStudentIds = attendanceRecords
    .filter(r => r.date === today && r.status === 'present')
    .map(r => r.studentId);
  const timingStudents = presentStudentIds.length > 0
    ? students.filter(s => s.isActive && presentStudentIds.includes(s.id))
    : students.filter(s => s.isActive);
  const [mode, setMode] = useState<'stopwatch' | 'manual'>('stopwatch');
  const [studentId, setStudentId] = useState<number | ''>('');
  const [distance, setDistance] = useState('500m');
  const [manualTime, setManualTime] = useState('');
  const [date, setDate] = useState(format(new Date(), 'yyyy-MM-dd'));
  const [notes, setNotes] = useState('');
  const [isSaving, setIsSaving] = useState(false);

  const mins = Math.floor(elapsedMs / 60000);
  const secs = Math.floor((elapsedMs % 60000) / 1000);
  const ms = Math.floor((elapsedMs % 1000) / 10);
  const timeStr = `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}.${String(ms).padStart(2, '0')}`;

  const handleSave = async () => {
    if (!studentId) { showToast({ type: 'error', message: 'Select a student' }); return; }
    const time = mode === 'stopwatch' ? timeStr : manualTime;
    if (!time) { showToast({ type: 'error', message: 'Enter a time' }); return; }
    setIsSaving(true);
    await saveTiming({ studentId: Number(studentId), distance, time, date, notes });
    setIsSaving(false);
    showToast({ type: 'success', message: 'Timing recorded!' });
    if (mode === 'stopwatch') resetTimer();
    setManualTime('');
    setNotes('');
  };

  const distances = ['500m', '1lap', '1000m', '1500m', '3000m'];

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Mode Tabs */}
      <div className="flex bg-white rounded-full p-1 border border-gray-200 mb-5 shadow-sm">
        <button onClick={() => setMode('stopwatch')} className={`flex-1 py-2 text-sm font-medium rounded-full transition-all ${mode === 'stopwatch' ? 'brand-gradient text-white shadow-sm' : 'text-gray-500'}`}>Stopwatch</button>
        <button onClick={() => setMode('manual')} className={`flex-1 py-2 text-sm font-medium rounded-full transition-all ${mode === 'manual' ? 'brand-gradient text-white shadow-sm' : 'text-gray-500'}`}>Manual Entry</button>
      </div>

      {/* Student & Distance */}
      <div className="grid grid-cols-2 gap-3 mb-4">
        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Student *</label>
          <select value={studentId} onChange={e => setStudentId(Number(e.target.value))} className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500">
            <option value="">Select...</option>
            {timingStudents.map(s => <option key={s.id} value={s.id}>{s.fullName}</option>)}
          </select>
        </div>
        <div>
          <label className="text-xs font-semibold text-gray-500 mb-1 block">Distance</label>
          <select value={distance} onChange={e => setDistance(e.target.value)} className="w-full h-11 px-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500">
            {distances.map(d => <option key={d} value={d}>{d}</option>)}
          </select>
        </div>
      </div>

      {mode === 'stopwatch' ? (
        <>
          {/* Timer Display */}
          <div className="bg-gray-900 rounded-2xl p-8 text-center mb-5">
            <div className="font-mono text-5xl font-extrabold text-white tracking-wider">{timeStr}</div>
          </div>

          {/* Controls */}
          <div className="flex items-center justify-center gap-6 mb-5">
            <button onClick={resetTimer} className="w-14 h-14 rounded-full border-2 border-gray-300 flex items-center justify-center active:scale-90 transition-transform">
              <RotateCcw className="w-5 h-5 text-gray-500" />
            </button>
            <button onClick={isRunning ? stopTimer : startTimer}
              className={`w-18 h-18 rounded-full flex items-center justify-center active:scale-90 transition-transform shadow-lg ${isRunning ? 'bg-red-500' : 'brand-gradient'}`}>
              {isRunning ? <Square className="w-6 h-6 text-white" /> : <Play className="w-6 h-6 text-white ml-1" />}
            </button>
            <button onClick={recordLap} disabled={!isRunning}
              className="w-14 h-14 rounded-full border-2 border-orange-200 flex items-center justify-center active:scale-90 transition-transform disabled:opacity-30">
              <Flag className="w-5 h-5 text-orange-500" />
            </button>
          </div>

          {/* Lap List */}
          {laps.length > 0 && (
            <div className="bg-white rounded-xl card-shadow max-h-40 overflow-y-auto no-scrollbar mb-4">
              {laps.map((lap, i) => (
                <div key={i} className="flex items-center justify-between px-4 py-2 border-b border-gray-50 last:border-0">
                  <span className="text-xs text-gray-500">Lap {lap.lapNumber}</span>
                  <span className="text-sm font-mono font-bold text-gray-800">{lap.time}</span>
                  {lap.delta && <span className="text-[10px] text-gray-400">{lap.delta}</span>}
                </div>
              ))}
            </div>
          )}
        </>
      ) : (
        <div className="bg-white rounded-2xl p-4 card-shadow mb-4">
          <label className="text-xs font-semibold text-gray-500 mb-2 block">Time (MM:SS)</label>
          <input type="text" value={manualTime} onChange={e => setManualTime(e.target.value)} placeholder="00:00.00"
            className="w-full h-14 text-center text-3xl font-mono font-bold text-gray-900 border border-gray-200 rounded-xl focus:outline-none focus:border-orange-500 focus:ring-2 focus:ring-orange-500/15" />
        </div>
      )}

      <div className="mb-4">
        <label className="text-xs font-semibold text-gray-500 mb-1 block">Notes</label>
        <textarea value={notes} onChange={e => setNotes(e.target.value)} placeholder="Optional notes..."
          className="w-full h-20 px-4 py-3 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:border-orange-500 resize-none" />
      </div>

      <button onClick={handleSave} disabled={isSaving}
        className="w-full h-12 brand-gradient text-white font-semibold rounded-xl button-shadow flex items-center justify-center gap-2 disabled:opacity-50 active:scale-[0.98] transition-transform">
        {isSaving ? <Loader2 className="w-5 h-5 animate-spin" /> : 'Save Timing'}
      </button>
    </div>
  );
}
