import { useState, useMemo } from 'react';
import { useTimingStore } from '@/stores/timingStore';
import { useStudentStore } from '@/stores/studentStore';
import { useAuthStore } from '@/stores/authStore';
import { useUIStore } from '@/stores/uiStore';
import { SectionTitle } from '@/components/common';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, LineElement, PointElement, Tooltip } from 'chart.js';
import { timingChartOptions } from '@/lib/chartConfig';
import { Trophy, TrendingDown, Clock } from 'lucide-react';

ChartJS.register(CategoryScale, LinearScale, LineElement, PointElement, Tooltip);

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

export default function TimingHistoryScreen() {
  const { records } = useTimingStore();
  const { students } = useStudentStore();
  const { user } = useAuthStore();
  const isStudent = user?.role === 'student';

  // Auto-detect student's numeric ID from their login username (SK001)
  const myStudentRecord = isStudent ? students.find(s => s.studentId === user?.username) : null;
  const myStudentId = myStudentRecord?.id ?? -1;

  const [selectedStudent, setSelectedStudent] = useState<number | ''>(isStudent ? myStudentId : '');
  const [selectedDistance, setSelectedDistance] = useState('All');

  const filteredRecords = records.filter(r => {
    if (selectedStudent && r.studentId !== Number(selectedStudent)) return false;
    if (selectedDistance !== 'All' && r.distance !== selectedDistance) return false;
    return true;
  }).sort((a, b) => new Date(a.recordDate).getTime() - new Date(b.recordDate).getTime());

  // Get unique student IDs from records
  const studentIds = [...new Set(records.map(r => r.studentId))];
  const recordStudents = studentIds.map(id => students.find(s => s.id === id)).filter(Boolean);

  const bestRecord = filteredRecords.length > 0
    ? filteredRecords.reduce((best, r) => r.timeSeconds < best.timeSeconds ? r : best, filteredRecords[0])
    : null;

  // Chart data - numeric seconds for proper charting
  const chartData = {
    labels: filteredRecords.map((_, i) => `Attempt ${i + 1}`),
    datasets: [{
      label: 'Time (seconds)',
      data: filteredRecords.map(r => r.timeSeconds),
      borderColor: '#F26522',
      backgroundColor: 'rgba(242,101,34,0.1)',
      fill: true,
      tension: 0.4,
      pointRadius: 5,
      pointBackgroundColor: '#F26522',
      pointBorderColor: '#fff',
      pointBorderWidth: 2,
    }],
  };

  // Average time
  const avgTime = filteredRecords.length > 0
    ? (filteredRecords.reduce((sum, r) => sum + r.timeSeconds, 0) / filteredRecords.length).toFixed(2)
    : '0';

  return (
    <div className="px-4 pt-4 pb-4 space-y-4">
      {/* Filters - hide student filter for student users (auto-selected) */}
      <div className={`grid gap-3 ${isStudent ? 'grid-cols-1' : 'grid-cols-2'}`}>
        {!isStudent && (
          <div>
            <label className="text-xs font-semibold text-gray-500 mb-1 block">Student</label>
            <select value={selectedStudent} onChange={e => setSelectedStudent(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="">All Students</option>
              {recordStudents.map(s => 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={selectedDistance} onChange={e => setSelectedDistance(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>

      {/* Best Time Card */}
      {bestRecord && (
        <div className="bg-white rounded-2xl p-4 card-shadow">
          <div className="flex items-center gap-2 mb-3">
            <Trophy className="w-4 h-4 text-amber-500" />
            <h3 className="text-sm font-bold text-gray-900">Best Time</h3>
          </div>
          <div className="flex items-center gap-4">
            <div className="w-14 h-14 bg-amber-50 rounded-2xl flex flex-col items-center justify-center">
              <Trophy className="w-6 h-6 text-amber-500" />
              <span className="text-[8px] text-amber-600 font-bold">BEST</span>
            </div>
            <div>
              <p className="text-3xl font-mono font-extrabold text-gray-900">{bestRecord.timeDisplay}</p>
              <div className="flex items-center gap-2 mt-1">
                <span className="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{bestRecord.distance}</span>
                <span className="text-xs text-gray-400">{bestRecord.studentName}</span>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Performance Chart - LOWER IS BETTER */}
      {filteredRecords.length > 1 && (
        <div className="bg-white rounded-2xl p-4 card-shadow">
          <div className="flex items-center justify-between mb-3">
            <div className="flex items-center gap-2">
              <TrendingDown className="w-4 h-4 text-emerald-500" />
              <h3 className="text-sm font-bold text-gray-900">Performance Trend</h3>
            </div>
            <span className="text-[10px] text-emerald-600 font-medium bg-emerald-50 px-2 py-0.5 rounded-full">Lower is Better</span>
          </div>
          <div className="h-52">
            <Line data={chartData} options={timingChartOptions} />
          </div>
        </div>
      )}

      {/* Stats */}
      <div className="grid grid-cols-3 gap-3">
        <div className="bg-white rounded-xl p-3 card-shadow text-center">
          <Clock className="w-4 h-4 text-orange-500 mx-auto mb-1" />
          <p className="text-lg font-bold text-gray-900">{filteredRecords.length}</p>
          <p className="text-[10px] text-gray-400">Records</p>
        </div>
        <div className="bg-white rounded-xl p-3 card-shadow text-center">
          <Trophy className="w-4 h-4 text-amber-500 mx-auto mb-1" />
          <p className="text-lg font-bold text-gray-900">{bestRecord?.timeDisplay || '-'}</p>
          <p className="text-[10px] text-gray-400">Best</p>
        </div>
        <div className="bg-white rounded-xl p-3 card-shadow text-center">
          <TrendingDown className="w-4 h-4 text-emerald-500 mx-auto mb-1" />
          <p className="text-lg font-bold text-gray-900">{avgTime}s</p>
          <p className="text-[10px] text-gray-400">Average</p>
        </div>
      </div>

      {/* Records List */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <SectionTitle title="Timing Records" />
        <div className="space-y-2">
          {filteredRecords.map((record, i) => {
            const prevRecord = i > 0 ? filteredRecords[i - 1] : null;
            const improved = prevRecord ? record.timeSeconds < prevRecord.timeSeconds : false;
            const worsened = prevRecord ? record.timeSeconds > prevRecord.timeSeconds : false;
            return (
              <div key={record.id} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                <div className="flex items-center gap-3">
                  <span className="text-xs text-gray-400 w-6">#{i + 1}</span>
                  <span className="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{record.distance}</span>
                  <div>
                    <p className="text-sm font-semibold text-gray-900">{record.studentName}</p>
                    <p className="text-[10px] text-gray-400">{record.recordDate}</p>
                  </div>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm font-mono font-bold text-gray-800">{record.timeDisplay}</span>
                  {improved && <span className="text-[10px] text-emerald-600 font-medium bg-emerald-50 px-1.5 py-0.5 rounded">↓ Improved</span>}
                  {worsened && <span className="text-[10px] text-red-500 font-medium bg-red-50 px-1.5 py-0.5 rounded">↑ Slower</span>}
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
