import { useState } from 'react';
import { useStudentStore } from '@/stores/studentStore';
import { useAttendanceStore } from '@/stores/attendanceStore';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { useUIStore } from '@/stores/uiStore';
import { Avatar } from '@/components/common';
import { Check, ChevronLeft, Users, Timer } from 'lucide-react';
import { format } from 'date-fns';

const DISTANCE_OPTIONS = ['500m', '1000m', '1500m', '3000m', 'Custom'];

export default function SprintRaceCreateScreen() {
  const { students } = useStudentStore();
  const { records: attendanceRecords } = useAttendanceStore();
  const { createRace } = useSprintRaceStore();
  const { navigateTo, showToast } = useUIStore();
  const [step, setStep] = useState<'distance' | 'students'>('distance');
  const [raceName, setRaceName] = useState('');
  const [distance, setDistance] = useState('');
  const [customDist, setCustomDist] = useState('');
  const [selectedStudents, setSelectedStudents] = useState<number[]>([]);

  // 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 activeStudents = presentStudentIds.length > 0
    ? students.filter(s => s.isActive && presentStudentIds.includes(s.id))
    : students.filter(s => s.isActive);

  const toggleStudent = (id: number) => {
    setSelectedStudents(prev =>
      prev.includes(id) ? prev.filter(s => s !== id) : prev.length < 10 ? [...prev, id] : prev
    );
  };

  const handleCreate = () => {
    const dist = distance === 'Custom' ? customDist : distance;
    if (!raceName.trim() || !dist) {
      showToast({ type: 'error', message: 'Enter race name and distance' });
      return;
    }
    if (selectedStudents.length === 0) {
      showToast({ type: 'error', message: 'Select at least 1 student' });
      return;
    }

    const names = selectedStudents.map(id => activeStudents.find(s => s.id === id)!.fullName);
    const race = createRace(raceName, dist, selectedStudents, names);
    showToast({ type: 'success', message: `Race "${raceName}" created!` });
    navigateTo('sprintRaceTimer');
  };

  const finalDistance = distance === 'Custom' ? customDist : distance;

  return (
    <div className="min-h-screen bg-gray-50">
      {/* Header */}
      <div className="brand-gradient px-5 pt-6 pb-8 rounded-b-[32px] shadow-lg">
        <button onClick={() => step === 'students' ? setStep('distance') : navigateTo('sprintRaceList')} className="flex items-center gap-1 text-white/80 text-sm mb-4">
          <ChevronLeft className="w-4 h-4" /> {step === 'distance' ? 'Back' : 'Back to Distance'}
        </button>
        <h1 className="text-xl font-extrabold text-white">Create Sprint Race</h1>
        <p className="text-sm text-white/70 mt-0.5">{step === 'distance' ? 'Step 1: Race Details' : `Step 2: Select Students (${selectedStudents.length}/10)`}</p>
      </div>

      <div className="px-4 -mt-4 pb-8">
        <div className="bg-white rounded-3xl shadow-lg p-5">

          {step === 'distance' ? (
            <div className="space-y-5">
              {/* Race Name */}
              <div>
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">Race Name</label>
                <input
                  type="text"
                  value={raceName}
                  onChange={e => setRaceName(e.target.value)}
                  placeholder="e.g. Morning Sprint A"
                  className="w-full h-13 px-4 bg-gray-50 border border-gray-100 rounded-2xl text-sm focus:outline-none focus:border-orange-400 focus:ring-4 focus:ring-orange-500/10 transition-all"
                />
              </div>

              {/* Distance */}
              <div>
                <label className="block text-xs font-bold text-gray-500 mb-2 uppercase tracking-wider">Distance</label>
                <div className="grid grid-cols-3 gap-2">
                  {DISTANCE_OPTIONS.map(d => (
                    <button
                      key={d}
                      onClick={() => setDistance(d)}
                      className={`py-3 rounded-xl text-sm font-semibold transition-all ${
                        distance === d ? 'brand-gradient text-white shadow-md' : 'bg-gray-50 text-gray-600 border border-gray-100'
                      }`}
                    >
                      {d}
                    </button>
                  ))}
                </div>
                {distance === 'Custom' && (
                  <input
                    type="text"
                    value={customDist}
                    onChange={e => setCustomDist(e.target.value)}
                    placeholder="e.g. 750m"
                    className="w-full h-12 mt-2 px-4 bg-gray-50 border border-gray-100 rounded-2xl text-sm focus:outline-none focus:border-orange-400"
                  />
                )}
              </div>

              <button
                onClick={() => setStep('students')}
                disabled={!raceName.trim() || !finalDistance}
                className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow disabled:opacity-40 active:scale-[0.97] transition-transform"
              >
                Next: Select Students
              </button>
            </div>
          ) : (
            <div className="space-y-4">
              {/* Selected count */}
              <div className="flex items-center justify-between bg-orange-50 rounded-xl p-3">
                <div className="flex items-center gap-2">
                  <Users className="w-4 h-4 text-orange-500" />
                  <span className="text-sm font-semibold text-orange-700">{selectedStudents.length} students selected</span>
                </div>
                <span className="text-xs text-orange-400">Max 10</span>
              </div>

              {/* Student List */}
              <div className="space-y-2 max-h-[400px] overflow-y-auto no-scrollbar">
                {activeStudents.map(student => {
                  const isSelected = selectedStudents.includes(student.id);
                  return (
                    <button
                      key={student.id}
                      onClick={() => toggleStudent(student.id)}
                      className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left ${
                        isSelected ? 'bg-orange-50 border-2 border-orange-300' : 'bg-gray-50 border-2 border-transparent'
                      }`}
                    >
                      <Avatar name={student.fullName} size="sm" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-semibold text-gray-900">{student.fullName}</p>
                        <p className="text-[10px] text-gray-400">{student.studentId}</p>
                      </div>
                      {isSelected && (
                        <div className="w-6 h-6 bg-orange-500 rounded-full flex items-center justify-center">
                          <Check className="w-3.5 h-3.5 text-white" />
                        </div>
                      )}
                    </button>
                  );
                })}
              </div>

              <button
                onClick={handleCreate}
                disabled={selectedStudents.length === 0}
                className="w-full h-14 brand-gradient text-white font-bold rounded-2xl button-shadow disabled:opacity-40 active:scale-[0.97] transition-transform flex items-center justify-center gap-2"
              >
                <Timer className="w-5 h-5" /> Create Race & Start Timer
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
