import { useState, useMemo } from 'react';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { formatDate } from '@/lib/formatters';
import { Timer, Plus, ChevronRight, Trophy, Filter, Trash2 } from 'lucide-react';

export default function SprintRaceListScreen() {
  const { races, deleteRace } = useSprintRaceStore();
  const { user } = useAuthStore();
  const { navigateTo, showToast } = useUIStore();
  const [filterDistance, setFilterDistance] = useState('All');
  const [deleteId, setDeleteId] = useState<number | null>(null);

  const isStudent = user?.role === 'student';
  const studentUserId = user?.id ?? -1;

  // For students: only show races they participated in
  const visibleRaces = useMemo(() => {
    if (!isStudent) return races;
    return races.filter(r =>
      r.rounds.some(round =>
        round.participants.some(p => p.studentId === studentUserId)
      )
    );
  }, [races, isStudent, studentUserId]);

  const distances = ['All', ...new Set(visibleRaces.map(r => r.distance))];
  const filtered = filterDistance === 'All' ? visibleRaces : visibleRaces.filter(r => r.distance === filterDistance);

  const handleRaceTap = (race: { id: number } | null) => {
    if (!race) return;
    const fullRace = useSprintRaceStore.getState().races.find(r => r.id === race.id);
    if (fullRace) {
      useSprintRaceStore.setState({ currentRace: fullRace });
      navigateTo('sprintRaceDetail');
    }
  };

  const handleDelete = (id: number) => {
    deleteRace(id);
    setDeleteId(null);
    showToast({ type: 'success', message: 'Race deleted' });
  };

  return (
    <div className="px-4 pt-4 pb-4">
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div>
          <h1 className="text-xl font-extrabold text-gray-900">Sprint Races</h1>
          <p className="text-xs text-gray-400 mt-0.5">
            {isStudent ? 'View your race results' : 'Create races, run timer, track results'}
          </p>
        </div>
        {/* Only admin/coach can create races */}
        {!isStudent && (
          <button
            onClick={() => navigateTo('sprintRaceCreate')}
            className="w-10 h-10 brand-gradient rounded-xl flex items-center justify-center text-white shadow-lg active:scale-90 transition-transform"
          >
            <Plus className="w-5 h-5" />
          </button>
        )}
      </div>

      {/* Distance Filter */}
      <div className="flex gap-2 overflow-x-auto no-scrollbar mb-4">
        {distances.map(d => (
          <button
            key={d}
            onClick={() => setFilterDistance(d)}
            className={`px-3.5 py-1.5 rounded-full text-xs font-semibold whitespace-nowrap transition-all ${
              filterDistance === d ? 'brand-gradient text-white shadow-sm' : 'bg-gray-100 text-gray-500'
            }`}
          >
            {d}
          </button>
        ))}
      </div>

      {/* Race List */}
      {filtered.length === 0 ? (
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="w-16 h-16 bg-orange-50 rounded-2xl flex items-center justify-center mb-4">
            <Timer className="w-8 h-8 text-orange-300" />
          </div>
          <p className="text-sm font-semibold text-gray-400">No races yet</p>
          <p className="text-xs text-gray-300 mt-1">
            {isStudent ? 'No races you participated in' : 'Create your first sprint race!'}
          </p>
        </div>
      ) : (
        <div className="space-y-3">
          {filtered.map(race => (
            <button
              key={race.id}
              onClick={() => handleRaceTap(race)}
              className="w-full bg-white rounded-2xl p-4 card-shadow flex items-center gap-3 text-left active:scale-[0.98] transition-transform"
            >
              <div className="w-12 h-12 brand-gradient rounded-xl flex items-center justify-center text-white flex-shrink-0">
                <Trophy className="w-6 h-6" />
              </div>
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <h3 className="text-sm font-bold text-gray-900 truncate">{race.name}</h3>
                  <span className="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{race.distance}</span>
                </div>
                <p className="text-xs text-gray-400 mt-0.5">
                  {formatDate(race.date)} &bull; {race.rounds.length} round{race.rounds.length > 1 ? 's' : ''} &bull; {race.rounds[0]?.participants.length || 0} students
                </p>
              </div>
              <div className="flex items-center gap-1">
                <ChevronRight className="w-4 h-4 text-gray-300" />
              </div>
            </button>
          ))}
        </div>
      )}

      {/* Create Button - only for admin/coach */}
      {!isStudent && (
        <button
          onClick={() => navigateTo('sprintRaceCreate')}
          className="fixed bottom-24 right-4 w-14 h-14 brand-gradient rounded-full button-shadow flex items-center justify-center text-white z-40 active:scale-90 transition-transform"
        >
          <Plus className="w-6 h-6" />
        </button>
      )}
    </div>
  );
}
