import { useState } from 'react';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { formatDate } from '@/lib/formatters';
import { ChevronLeft, Trophy, Clock, UserX, Play, RotateCcw, Edit3 } from 'lucide-react';

export default function SprintRaceDetailScreen() {
  const { currentRace, startNewRound, resetTimer, deleteRace } = useSprintRaceStore();
  const { user } = useAuthStore();
  const { navigateTo, showToast, goBack } = useUIStore();
  const [activeRound, setActiveRound] = useState(1);
  const [showDelete, setShowDelete] = useState(false);

  if (!currentRace) return null;

  const roundData = currentRace.rounds.find(r => r.roundNumber === activeRound);
  const isAdminOrCoach = user?.role === 'admin' || user?.role === 'assistant';
  const isStudent = user?.role === 'student';
  const studentUserId = user?.id ?? -1;

  const handleRunAgain = () => {
    startNewRound();
    resetTimer();
    navigateTo('sprintRaceTimer');
  };

  const handleDelete = () => {
    deleteRace(currentRace.id);
    setShowDelete(false);
    showToast({ type: 'success', message: 'Race deleted' });
    goBack();
  };

  // Sort participants by position for display
  // For students: only show their own result
  const allParticipants = roundData ? roundData.participants : [];
  const visibleParticipants = isStudent
    ? allParticipants.filter(p => p.studentId === studentUserId)
    : allParticipants;

  const sortedParticipants = [...visibleParticipants].sort((a, b) => {
    if (a.status === 'finished' && b.status === 'finished') return (a.position || 999) - (b.position || 999);
    if (a.status === 'finished') return -1;
    if (b.status === 'finished') return 1;
    if (a.status === 'dnf') return 1;
    return -1;
  });

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <button onClick={goBack} className="flex items-center gap-1 text-sm text-gray-400">
          <ChevronLeft className="w-4 h-4" /> Back
        </button>
        {isAdminOrCoach && (
          <button onClick={() => setShowDelete(true)} className="p-2">
            <span className="text-xs text-red-400">Delete</span>
          </button>
        )}
      </div>

      {/* Race Info */}
      <div className="bg-white rounded-2xl p-4 card-shadow mb-4">
        <div className="flex items-center gap-3 mb-3">
          <div className="w-12 h-12 brand-gradient rounded-xl flex items-center justify-center text-white">
            <Trophy className="w-6 h-6" />
          </div>
          <div>
            <h1 className="text-lg font-extrabold text-gray-900">{currentRace.name}</h1>
            <div className="flex items-center gap-2">
              <span className="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{currentRace.distance}</span>
              <span className="text-xs text-gray-400">{formatDate(currentRace.date)}</span>
            </div>
          </div>
        </div>

        {/* Round Tabs */}
        <div className="flex gap-2 overflow-x-auto no-scrollbar">
          {currentRace.rounds.map(r => (
            <button
              key={r.roundNumber}
              onClick={() => setActiveRound(r.roundNumber)}
              className={`px-4 py-2 rounded-xl text-xs font-bold transition-all flex-shrink-0 ${
                activeRound === r.roundNumber ? 'brand-gradient text-white shadow-sm' : 'bg-gray-100 text-gray-500'
              }`}
            >
              Round {r.roundNumber}
            </button>
          ))}
        </div>
      </div>

      {/* Results Table */}
      <div className="bg-white rounded-2xl card-shadow overflow-hidden mb-4">
        <div className="p-4 border-b border-gray-50">
          <h3 className="text-sm font-bold text-gray-900">Round {activeRound} Results</h3>
        </div>

        {sortedParticipants.length === 0 ? (
          <div className="p-8 text-center text-gray-400 text-sm">No results yet</div>
        ) : (
          <div className="divide-y divide-gray-50">
            {sortedParticipants.map(p => (
              <div key={p.studentId} className={`flex items-center gap-3 px-4 py-3 ${p.status === 'dnf' ? 'opacity-50' : ''}`}>
                {/* Position */}
                <div className={`w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0 ${
                  p.position === 1 ? 'bg-amber-100' : p.position === 2 ? 'bg-gray-100' : p.position === 3 ? 'bg-orange-50' : 'bg-gray-50'
                }`}>
                  {p.status === 'finished' && p.position ? (
                    <span className={`text-xs font-extrabold ${p.position === 1 ? 'text-amber-600' : p.position === 2 ? 'text-gray-500' : p.position === 3 ? 'text-orange-500' : 'text-gray-400'}`}>
                      {p.position}
                    </span>
                  ) : p.status === 'dnf' ? (
                    <UserX className="w-4 h-4 text-red-400" />
                  ) : (
                    <span className="text-xs text-gray-300">-</span>
                  )}
                </div>

                {/* Name */}
                <div className="flex-1 min-w-0">
                  <p className={`text-sm font-semibold ${p.status === 'dnf' ? 'text-gray-400 line-through' : 'text-gray-900'}`}>{p.studentName}</p>
                </div>

                {/* Time */}
                <div className="text-right">
                  {p.status === 'finished' && p.timeDisplay ? (
                    <p className="text-sm font-mono font-bold text-gray-800">{p.timeDisplay}</p>
                  ) : p.status === 'dnf' ? (
                    <p className="text-xs font-bold text-red-500">DNF</p>
                  ) : (
                    <p className="text-xs text-gray-300">Pending</p>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Admin/Coach Actions */}
      {isAdminOrCoach && (
        <div className="space-y-3">
          <button onClick={handleRunAgain} 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 (Round {currentRace.rounds.length + 1})
          </button>
          <button onClick={() => { useSprintRaceStore.setState({ currentRace }); navigateTo('sprintRaceTimer'); }} className="w-full h-14 border-2 border-orange-200 text-orange-500 font-bold rounded-2xl flex items-center justify-center gap-2 active:scale-[0.97] transition-transform">
            <Play className="w-5 h-5" /> Continue This Race
          </button>
        </div>
      )}

      {/* Delete Confirmation */}
      {showDelete && (
        <div className="fixed inset-0 z-[60] flex items-center justify-center px-6">
          <div className="absolute inset-0 bg-black/50" onClick={() => setShowDelete(false)} />
          <div className="relative bg-white rounded-2xl p-6 max-w-xs w-full text-center animate-scale-in">
            <div className="w-12 h-12 rounded-full bg-red-100 flex items-center justify-center mx-auto mb-3">
              <UserX className="w-6 h-6 text-red-500" />
            </div>
            <h3 className="text-lg font-bold text-gray-900">Delete Race?</h3>
            <p className="text-sm text-gray-500 mt-1">This will delete all rounds and results.</p>
            <div className="flex gap-3 mt-5">
              <button onClick={() => setShowDelete(false)} className="flex-1 py-2.5 border border-gray-200 rounded-xl text-sm font-semibold text-gray-600">Cancel</button>
              <button onClick={handleDelete} className="flex-1 py-2.5 bg-red-500 text-white rounded-xl text-sm font-semibold">Delete</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
