import { useState } from 'react';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { useUIStore } from '@/stores/uiStore';
import { ChevronLeft, Play, Square, RotateCcw, Flag, Timer, Save, UserX, Plus, Pencil } from 'lucide-react';

interface LapRecord {
  id: number;
  lapNumber: number;
  timeMs: number;
  timeDisplay: string;
  studentId: number | null;
  studentName: string | null;
  position: number | null;
  status: 'finished' | 'dnf' | 'pending';
}

interface DnfRecord {
  studentId: number;
  studentName: string;
}

export default function SprintRaceTimerScreen() {
  const { currentRace, currentRound, elapsedMs, isTimerRunning, startTimer, stopTimer, resetTimer, saveRound, startNewRound } = useSprintRaceStore();
  const { navigateTo, showToast } = useUIStore();

  const [laps, setLaps] = useState<LapRecord[]>([]);
  const [dnfRecords, setDnfRecords] = useState<DnfRecord[]>([]);
  const [lapIdCounter, setLapIdCounter] = useState(1);
  const [assigningLap, setAssigningLap] = useState<number | null>(null);
  const [raceDone, setRaceDone] = useState(false);

  // Edit lap time states
  const [editingLapId, setEditingLapId] = useState<number | null>(null);
  const [editTimeValue, setEditTimeValue] = useState('');

  // Add missed student states
  const [missedStudentMode, setMissedStudentMode] = useState(false);
  const [selectedMissedStudentId, setSelectedMissedStudentId] = useState<number | null>(null);
  const [missedTimeValue, setMissedTimeValue] = useState('');

  if (!currentRace) return null;
  const participants = currentRace.rounds.find(r => r.roundNumber === currentRound)?.participants || [];

  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 handleLap = () => {
    const newLap: LapRecord = {
      id: lapIdCounter,
      lapNumber: laps.length + 1,
      timeMs: elapsedMs,
      timeDisplay: timeStr,
      studentId: null,
      studentName: null,
      position: null,
      status: 'pending',
    };
    setLaps(prev => [...prev, newLap]);
    setLapIdCounter(prev => prev + 1);
  };

  const handleAssignStudent = (lapId: number, studentId: number, studentName: string) => {
    const nextPos = laps.filter(l => l.studentId !== null && l.status === 'finished').length + 1;
    setLaps(prev => prev.map(l =>
      l.id === lapId ? { ...l, studentId, studentName, position: nextPos, status: 'finished' } : l
    ));
    setAssigningLap(null);
  };

  // EDIT LAP TIME
  const startEditLap = (lap: LapRecord) => {
    setEditingLapId(lap.id);
    setEditTimeValue(lap.timeDisplay);
  };

  const saveEditLap = (lapId: number) => {
    const timeMs = parseTimeToMs(editTimeValue);
    if (isNaN(timeMs) || timeMs <= 0) {
      showToast({ type: 'error', message: 'Invalid time format. Use MM:SS.ms or SS.ms' });
      return;
    }
    setLaps(prev => prev.map(l =>
      l.id === lapId ? { ...l, timeMs, timeDisplay: editTimeValue } : l
    ));
    setEditingLapId(null);
    showToast({ type: 'success', message: 'Lap time updated!' });
  };

  const cancelEditLap = () => {
    setEditingLapId(null);
    setEditTimeValue('');
  };

  // ADD MISSED STUDENT
  const openMissedStudent = () => {
    setSelectedMissedStudentId(null);
    setMissedTimeValue('');
    setMissedStudentMode(true);
  };

  const saveMissedStudent = () => {
    if (!selectedMissedStudentId) {
      showToast({ type: 'error', message: 'Select a student first' });
      return;
    }
    if (!missedTimeValue.trim()) {
      showToast({ type: 'error', message: 'Enter the time' });
      return;
    }
    const timeMs = parseTimeToMs(missedTimeValue);
    if (isNaN(timeMs) || timeMs <= 0) {
      showToast({ type: 'error', message: 'Invalid time format. Use MM:SS.ms or SS.ms' });
      return;
    }
    const student = unassignedStudents.find(s => s.studentId === selectedMissedStudentId);
    if (!student) {
      showToast({ type: 'error', message: 'Student not found' });
      return;
    }
    const nextPos = laps.filter(l => l.studentId !== null && l.status === 'finished').length + 1;
    const newLap: LapRecord = {
      id: lapIdCounter,
      lapNumber: laps.length + 1,
      timeMs,
      timeDisplay: missedTimeValue,
      studentId: student.studentId,
      studentName: student.studentName,
      position: nextPos,
      status: 'finished',
    };
    setLaps(prev => [...prev, newLap]);
    setLapIdCounter(prev => prev + 1);
    setMissedStudentMode(false);
    setSelectedMissedStudentId(null);
    setMissedTimeValue('');
    showToast({ type: 'success', message: `${student.studentName} added with time ${missedTimeValue}!` });
  };

  const handleMarkStudentDNF = (studentId: number, studentName: string) => {
    setDnfRecords(prev => [...prev, { studentId, studentName }]);
    showToast({ type: 'info', message: `${studentName} marked as Did Not Finish` });
  };

  const handleUnmarkDNF = (studentId: number) => {
    setDnfRecords(prev => prev.filter(d => d.studentId !== studentId));
  };

  const handleDeleteLap = (lapId: number) => {
    setLaps(prev => {
      const filtered = prev.filter(l => l.id !== lapId);
      return filtered.map((l, i) => ({ ...l, lapNumber: i + 1 }));
    });
  };

  const handleSaveAll = () => {
    const lapData = [
      ...laps
        .filter(l => l.studentId && l.studentId > 0 && l.status === 'finished')
        .map(l => ({
          studentId: l.studentId!,
          position: l.position!,
          timeSeconds: l.timeMs / 1000,
          timeDisplay: l.timeDisplay,
          status: 'finished' as const,
        })),
      ...dnfRecords.map(d => ({
        studentId: d.studentId,
        position: 0,
        timeSeconds: 0,
        timeDisplay: 'DNF',
        status: 'dnf' as const,
      })),
    ];

    saveRound(lapData);
    setRaceDone(true);
    const finishedCount = laps.filter(l => l.status === 'finished' && l.studentId && l.studentId > 0).length;
    showToast({ type: 'success', message: `Round ${currentRound} saved! ${finishedCount} finished, ${dnfRecords.length} DNF` });
  };

  const handleNewRound = () => {
    startNewRound();
    resetTimer();
    setLaps([]);
    setDnfRecords([]);
    setRaceDone(false);
    showToast({ type: 'info', message: `Round ${currentRound + 1} started!` });
  };

  const parseTimeToMs = (t: string) => {
    const parts = t.split(':');
    if (parts.length === 2) return (parseInt(parts[0]) * 60 + parseFloat(parts[1])) * 1000;
    return parseFloat(parts[0]) * 1000;
  };

  // Derrived values
  const assignedStudentIds = laps.filter(l => l.studentId && l.studentId > 0 && l.status === 'finished').map(l => l.studentId);
  const dnfStudentIds = dnfRecords.map(d => d.studentId);
  const unassignedStudents = participants.filter(p => !assignedStudentIds.includes(p.studentId) && !dnfStudentIds.includes(p.studentId));
  const finishedCount = laps.filter(l => l.status === 'finished' && l.studentId && l.studentId > 0).length;
  const totalAccounted = finishedCount + dnfRecords.length;

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* Header */}
      <div className="brand-gradient px-5 pt-6 pb-8 shadow-lg rounded-b-[32px]">
        <button onClick={() => navigateTo('sprintRaceList')} className="flex items-center gap-1 text-white/80 text-sm mb-4">
          <ChevronLeft className="w-4 h-4" /> Sprint Races
        </button>
        <h1 className="text-xl font-extrabold text-white">{currentRace.name}</h1>
        <div className="flex items-center gap-2 mt-1">
          <span className="px-2 py-0.5 bg-white/20 text-white text-[10px] font-bold rounded-md">{currentRace.distance}</span>
          <span className="text-white/60 text-xs">Round {currentRound}</span>
          <span className="text-white/40 text-xs">&bull; {participants.length} students</span>
        </div>
      </div>

      {/* Timer Display */}
      <div className="px-4 -mt-4 mb-3">
        <div className="bg-gray-900 rounded-3xl p-6 text-center shadow-xl relative overflow-hidden">
          <div className="absolute top-2 right-3 text-[10px] text-white/20 font-mono">{participants.length - totalAccounted} remaining</div>
          <p className="text-white/30 text-[10px] font-medium mb-1 uppercase tracking-[3px]">Race Timer</p>
          <p className="font-mono text-6xl font-extrabold text-white tracking-wider">{timeStr}</p>

          {/* Timer Controls */}
          <div className="flex items-center justify-center gap-4 mt-5">
            {!isTimerRunning ? (
              <button onClick={startTimer} className="w-16 h-16 brand-gradient rounded-full flex items-center justify-center text-white shadow-lg active:scale-90 transition-transform">
                <Play className="w-7 h-7 ml-1" />
              </button>
            ) : (
              <button onClick={() => { stopTimer(); setRaceDone(true); }} className="w-16 h-16 bg-red-500 rounded-full flex items-center justify-center text-white shadow-lg active:scale-90 transition-transform">
                <Square className="w-6 h-6" />
              </button>
            )}

            {/* LAP BUTTON */}
            {isTimerRunning && (
              <button onClick={handleLap} className="w-20 h-20 bg-emerald-500 rounded-full flex flex-col items-center justify-center text-white shadow-xl shadow-emerald-500/40 active:scale-90 transition-transform mx-2">
                <Flag className="w-6 h-6" />
                <span className="text-[10px] font-bold mt-0.5">LAP</span>
              </button>
            )}

            <button onClick={() => { resetTimer(); setLaps([]); setDnfRecords([]); setRaceDone(false); }} className="w-12 h-12 bg-gray-700 rounded-full flex items-center justify-center text-gray-300 active:scale-90 transition-transform">
              <RotateCcw className="w-5 h-5" />
            </button>
          </div>
        </div>
      </div>

      {/* Lap Records Section */}
      <div className="px-4 mb-2">
        <div className="flex items-center justify-between">
          <h3 className="text-sm font-bold text-gray-800">Lap Records ({laps.length})</h3>
          {raceDone && unassignedStudents.length > 0 && (
            <button onClick={openMissedStudent} className="flex items-center gap-1 text-xs font-semibold text-orange-500">
              <Plus className="w-3.5 h-3.5" /> Add Missed Student
            </button>
          )}
        </div>
      </div>

      {/* Lap List */}
      <div className="flex-1 px-4 pb-4 overflow-y-auto space-y-2">
        {laps.length === 0 && unassignedStudents.length === participants.length && (
          <div className="text-center py-8">
            <Timer className="w-10 h-10 text-gray-200 mx-auto mb-2" />
            <p className="text-xs text-gray-300">Press START, then tap LAP as students finish</p>
          </div>
        )}

        {laps.map((lap) => (
          <div key={lap.id} className={`bg-white rounded-2xl p-3 card-shadow ${lap.status === 'finished' && lap.studentId ? 'border-l-4 border-emerald-400' : ''}`}>
            <div className="flex items-center gap-3">
              {/* Lap Number */}
              <div className={`w-10 h-10 rounded-xl flex items-center justify-center flex-shrink-0 ${
                lap.status === 'dnf' ? 'bg-red-100' : lap.studentId ? 'bg-emerald-100' : 'bg-gray-100'
              }`}>
                <span className={`text-sm font-extrabold ${
                  lap.status === 'dnf' ? 'text-red-500' : lap.studentId ? 'text-emerald-600' : 'text-gray-500'
                }`}>#{lap.lapNumber}</span>
              </div>

              {/* Time + Student Info */}
              <div className="flex-1">
                {/* Time display - editable when editing */}
                {editingLapId === lap.id ? (
                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      value={editTimeValue}
                      onChange={e => setEditTimeValue(e.target.value)}
                      className="w-28 h-8 px-2 bg-amber-50 border border-amber-200 rounded-lg text-sm font-mono font-bold text-gray-900"
                      autoFocus
                    />
                    <button onClick={() => saveEditLap(lap.id)} className="px-2 py-1 bg-emerald-500 text-white text-[10px] font-bold rounded-lg">Save</button>
                    <button onClick={cancelEditLap} className="px-2 py-1 bg-gray-200 text-gray-500 text-[10px] font-bold rounded-lg">Cancel</button>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <p className="font-mono text-lg font-bold text-gray-900">{lap.timeDisplay}</p>
                    {/* Edit time button */}
                    <button onClick={() => startEditLap(lap)} className="p-1 text-gray-300 hover:text-orange-500 transition-colors">
                      <Pencil className="w-3 h-3" />
                    </button>
                  </div>
                )}

                {/* Student name */}
                {lap.studentName && lap.studentName !== 'DNF' ? (
                  <div className="flex items-center gap-2">
                    <span className="text-xs text-gray-600">{lap.studentName}</span>
                    {lap.position && <span className="px-1.5 py-0.5 bg-amber-100 text-amber-700 text-[10px] font-bold rounded">Pos {lap.position}</span>}
                  </div>
                ) : lap.status === 'dnf' ? (
                  <span className="text-xs text-red-500 font-bold">Did Not Finish</span>
                ) : (
                  <span className="text-xs text-orange-400 font-medium">Tap Assign to select student...</span>
                )}
              </div>

              {/* Actions */}
              {!lap.studentId ? (
                <button onClick={() => setAssigningLap(lap.id)} className="px-3 py-2 bg-orange-500 text-white text-xs font-bold rounded-xl active:scale-90 transition-transform">
                  Assign
                </button>
              ) : (
                <button onClick={() => handleDeleteLap(lap.id)} className="p-2 text-gray-300 hover:text-red-400 transition-colors">
                  <span className="text-xs">✕</span>
                </button>
              )}
            </div>

            {/* Student Assignment Dropdown */}
            {assigningLap === lap.id && (
              <div className="mt-3 pt-3 border-t border-gray-100 space-y-2">
                <p className="text-xs font-bold text-gray-500 uppercase">Select Student for this Lap:</p>
                <div className="grid grid-cols-1 gap-2 max-h-40 overflow-y-auto">
                  {unassignedStudents.length === 0 ? (
                    <p className="text-xs text-gray-400 py-2">All students assigned</p>
                  ) : (
                    unassignedStudents.map(s => (
                      <button key={s.studentId} onClick={() => handleAssignStudent(lap.id, s.studentId, s.studentName)}
                        className="flex items-center gap-2 p-2.5 bg-gray-50 rounded-xl text-left hover:bg-orange-50 transition-colors active:scale-95">
                        <div className="w-7 h-7 rounded-full brand-gradient flex items-center justify-center text-white text-[10px] font-bold flex-shrink-0">
                          {s.studentName.charAt(0)}
                        </div>
                        <span className="text-xs font-semibold text-gray-800 truncate">{s.studentName}</span>
                      </button>
                    ))
                  )}
                </div>
                <button onClick={() => setAssigningLap(null)} className="w-full py-2 text-gray-400 text-xs rounded-xl">Cancel</button>
              </div>
            )}
          </div>
        ))}

        {/* === NOT FINISHED / DNF SECTION === */}
        {raceDone && (unassignedStudents.length > 0 || dnfRecords.length > 0) && (
          <div className="mt-4 pt-4 border-t-2 border-dashed border-gray-200">
            <div className="flex items-center gap-2 mb-3">
              <UserX className="w-4 h-4 text-red-500" />
              <h3 className="text-sm font-bold text-gray-800">Not Finished ({unassignedStudents.length + dnfRecords.length})</h3>
            </div>

            {unassignedStudents.map(s => (
              <div key={s.studentId} className="bg-white rounded-2xl p-3 card-shadow flex items-center gap-3 mb-2">
                <div className="w-10 h-10 bg-gray-100 rounded-xl flex items-center justify-center flex-shrink-0">
                  <span className="text-sm font-bold text-gray-400">{s.studentName.charAt(0)}</span>
                </div>
                <div className="flex-1">
                  <p className="text-sm font-semibold text-gray-800">{s.studentName}</p>
                  <span className="text-xs text-gray-400">No time recorded</span>
                </div>
                <button onClick={() => handleMarkStudentDNF(s.studentId, s.studentName)}
                  className="px-3 py-2 bg-red-50 text-red-500 text-xs font-bold rounded-xl hover:bg-red-100 active:scale-90 transition-transform border border-red-100">
                  <UserX className="w-3.5 h-3.5 inline mr-1" />Mark DNF
                </button>
              </div>
            ))}

            {dnfRecords.map(d => (
              <div key={d.studentId} className="bg-red-50 rounded-2xl p-3 border border-red-100 flex items-center gap-3 mb-2 opacity-70">
                <div className="w-10 h-10 bg-red-200 rounded-xl flex items-center justify-center flex-shrink-0">
                  <UserX className="w-5 h-5 text-red-500" />
                </div>
                <div className="flex-1">
                  <p className="text-sm font-semibold text-gray-800 line-through">{d.studentName}</p>
                  <span className="text-xs text-red-500 font-bold">Did Not Finish</span>
                </div>
                <button onClick={() => handleUnmarkDNF(d.studentId)}
                  className="px-3 py-2 text-gray-400 text-xs font-medium rounded-xl hover:bg-white transition-colors">
                  Undo
                </button>
              </div>
            ))}
          </div>
        )}

        {/* Save / New Round Buttons */}
        {raceDone && laps.length > 0 && (
          <div className="space-y-3 mt-4">
            {unassignedStudents.length > 0 && dnfRecords.length === 0 && (
              <p className="text-xs text-amber-600 text-center bg-amber-50 py-2 rounded-xl">
                {unassignedStudents.length} student{unassignedStudents.length > 1 ? 's' : ''} not accounted for. Use &quot;Add Missed Student&quot; above or mark as DNF.
              </p>
            )}
            <button onClick={handleSaveAll}
              disabled={unassignedStudents.length > 0 && dnfRecords.length === 0}
              className="w-full h-14 bg-emerald-500 text-white font-bold rounded-2xl shadow-lg flex items-center justify-center gap-2 active:scale-[0.97] transition-transform disabled:opacity-40">
              <Save className="w-5 h-5" /> Save Round {currentRound}
            </button>
            <button onClick={handleNewRound} className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow flex items-center justify-center gap-2 active:scale-[0.97] transition-transform">
              <RotateCcw className="w-5 h-5" /> Run Again - New Round
            </button>
          </div>
        )}
      </div>

      {/* === ADD MISSED STUDENT MODAL === */}
      {missedStudentMode && (
        <div className="fixed inset-0 z-[60] flex items-end">
          <div className="absolute inset-0 bg-black/40" onClick={() => setMissedStudentMode(false)} />
          <div className="relative bg-white rounded-t-3xl w-full max-w-lg mx-auto p-6 pb-10 animate-slide-up">
            <div className="w-10 h-1 bg-gray-300 rounded-full mx-auto mb-5" />
            <h3 className="text-lg font-bold text-gray-900 mb-1">Add Missed Student</h3>
            <p className="text-xs text-gray-400 mb-4">Select the student you missed and enter their time</p>

            <div className="space-y-4">
              {/* Student Selection */}
              <div>
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">Select Student</label>
                <div className="space-y-2 max-h-48 overflow-y-auto">
                  {unassignedStudents.length === 0 ? (
                    <p className="text-xs text-gray-400 py-3 text-center">No unassigned students</p>
                  ) : (
                    unassignedStudents.map(s => (
                      <button
                        key={s.studentId}
                        onClick={() => setSelectedMissedStudentId(s.studentId)}
                        className={`w-full flex items-center gap-3 p-3 rounded-xl text-left transition-all ${
                          selectedMissedStudentId === s.studentId
                            ? 'bg-orange-50 border-2 border-orange-400'
                            : 'bg-gray-50 border-2 border-transparent hover:bg-gray-100'
                        }`}
                      >
                        <div className="w-8 h-8 rounded-full brand-gradient flex items-center justify-center text-white text-[10px] font-bold">
                          {s.studentName.charAt(0)}
                        </div>
                        <div>
                          <p className="text-sm font-semibold text-gray-800">{s.studentName}</p>
                          <p className="text-[10px] text-gray-400">{s.studentId}</p>
                        </div>
                        {selectedMissedStudentId === s.studentId && (
                          <div className="ml-auto w-5 h-5 bg-orange-500 rounded-full flex items-center justify-center">
                            <svg className="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} d="M5 13l4 4L19 7" /></svg>
                          </div>
                        )}
                      </button>
                    ))
                  )}
                </div>
              </div>

              {/* Time Input */}
              <div>
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">Their Time</label>
                <input
                  type="text"
                  value={missedTimeValue}
                  onChange={e => setMissedTimeValue(e.target.value)}
                  placeholder="e.g. 45.23 or 01:15.50"
                  className="w-full h-14 px-4 bg-gray-50 border border-gray-100 rounded-2xl text-sm font-mono focus:outline-none focus:border-orange-400 focus:ring-4 focus:ring-orange-500/10 transition-all"
                />
                <p className="text-[10px] text-gray-400 mt-1">Format: SS.ms (45.23) or MM:SS.ms (01:15.50)</p>
              </div>

              {/* Save Button */}
              <button
                onClick={saveMissedStudent}
                disabled={!selectedMissedStudentId || !missedTimeValue}
                className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow disabled:opacity-40 active:scale-[0.97] transition-transform"
              >
                Add Student with Time
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
