import { useAuthStore } from '@/stores/authStore';
import { useStudentStore } from '@/stores/studentStore';
import { useTimingStore } from '@/stores/timingStore';
import { useSprintRaceStore } from '@/stores/sprintRaceStore';
import { Avatar, ProgressRing } from '@/components/common';
import { Calendar, Timer, Trophy, Bell, TrendingUp, Clock, Award, Star, Zap } from 'lucide-react';
import { Line } from 'react-chartjs-2';
import { Chart as ChartJS, CategoryScale, LinearScale, LineElement, PointElement, Tooltip } from 'chart.js';
import { timingChartOptions } from '@/lib/chartConfig';

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

export default function StudentDashboard() {
  const { user } = useAuthStore();
  const { students } = useStudentStore();
  const { records } = useTimingStore();
  const { races } = useSprintRaceStore();

  // Find the actual student record by matching username (SK001) with studentId
  const myStudentRecord = students.find(s => s.studentId === user?.username);
  const myNumericId = myStudentRecord?.id ?? user?.id ?? -1;

  // My regular timing records (from TimingEntryScreen)
  const myTimingRecords = records
    .filter(r => r.studentId === myNumericId)
    .sort((a, b) => new Date(b.recordDate).getTime() - new Date(a.recordDate).getTime());
  const bestTime = myTimingRecords.length > 0
    ? myTimingRecords.reduce((best, r) => r.timeSeconds < best.timeSeconds ? r : best, myTimingRecords[0])
    : null;

  // My sprint race results
  const myRaceResults: {
    raceName: string;
    distance: string;
    round: number;
    position: number | null;
    timeDisplay: string | null;
    status: string;
    date: string;
  }[] = [];

  races.forEach(race => {
    race.rounds.forEach(round => {
      round.participants.forEach(p => {
        if (p.studentId === myNumericId) {
          myRaceResults.push({
            raceName: race.name,
            distance: race.distance,
            round: round.roundNumber,
            position: p.position,
            timeDisplay: p.timeDisplay,
            status: p.status,
            date: race.date,
          });
        }
      });
    });
  });

  // Sort race results by date desc
  myRaceResults.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());

  // Performance chart data from actual timing records
  const chartLabels = myTimingRecords.slice(0, 6).reverse().map(r => r.recordDate.slice(5));
  const chartData = myTimingRecords.slice(0, 6).reverse().map(r => r.timeSeconds);

  const progressData = {
    labels: chartLabels.length > 0 ? chartLabels : ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
    datasets: [{
      label: 'Timing (seconds)',
      data: chartData.length > 0 ? chartData : [48.5, 46.2, 44.8, 43.1],
      borderColor: '#F26522',
      backgroundColor: 'rgba(242,101,34,0.1)',
      fill: true,
      tension: 0.4,
      pointRadius: 4,
      pointBackgroundColor: '#F26522',
    }],
  };

  const upcomingEvents = [
    { id: 1, title: 'Inter-Academy Competition', date: '15 July 2025', type: 'competition' },
    { id: 2, title: 'Advanced Skating Workshop', date: '20 July 2025', type: 'workshop' },
    { id: 3, title: 'Monthly Assessment', date: '25 July 2025', type: 'assessment' },
  ];

  const adminMessages = [
    { id: 1, message: 'Great improvement this month! Keep practicing your 500m sprints.', date: '28 Jun', read: false },
    { id: 2, message: 'Reminder: Advanced workshop registration is open. Sign up soon!', date: '25 Jun', read: true },
  ];

  const eventTypeColors: Record<string, { bg: string; icon: string }> = {
    competition: { bg: 'bg-red-50', icon: 'text-red-500' },
    workshop: { bg: 'bg-blue-50', icon: 'text-blue-500' },
    assessment: { bg: 'bg-amber-50', icon: 'text-amber-500' },
  };

  return (
    <div className="px-4 pt-4 pb-4 space-y-5">
      {/* Profile Header */}
      <div className="brand-gradient rounded-2xl p-5 text-white shadow-lg">
        <div className="flex items-center gap-4">
          <Avatar name={user?.name || 'Student'} size="lg" />
          <div>
            <p className="text-white/70 text-xs">Welcome back,</p>
            <h2 className="text-xl font-bold">{user?.name || 'Student'}</h2>
            <p className="text-white/60 text-xs mt-0.5">{user?.username || ''} &bull; {myStudentRecord?.batchName || 'Beginner Batch'}</p>
          </div>
        </div>
      </div>

      {/* My Attendance */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <div className="flex items-center gap-2 mb-3">
          <Calendar className="w-4 h-4 text-orange-500" />
          <h3 className="text-sm font-bold text-gray-900">My Attendance</h3>
        </div>
        <div className="flex items-center gap-4">
          <ProgressRing percentage={85} size={72} />
          <div className="flex-1 space-y-2">
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-emerald-500" />
                <span className="text-xs text-gray-500">Present</span>
              </div>
              <span className="text-sm font-bold text-gray-800">18 days</span>
            </div>
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-red-400" />
                <span className="text-xs text-gray-500">Absent</span>
              </div>
              <span className="text-sm font-bold text-gray-800">2 days</span>
            </div>
            <div className="flex justify-between items-center">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full bg-gray-300" />
                <span className="text-xs text-gray-500">Total</span>
              </div>
              <span className="text-sm font-bold text-gray-800">20 days</span>
            </div>
          </div>
        </div>
      </div>

      {/* My Best Timing */}
      <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">My Best Timing</h3>
        </div>
        {bestTime ? (
          <div className="flex items-center gap-4">
            <div className="w-16 h-16 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 mt-0.5">BEST</span>
            </div>
            <div>
              <p className="text-3xl font-mono font-extrabold text-gray-900">{bestTime.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">{bestTime.distance}</span>
                <span className="text-xs text-gray-400">{bestTime.recordDate}</span>
              </div>
            </div>
          </div>
        ) : (
          <p className="text-sm text-gray-400">No timing records yet</p>
        )}
      </div>

      {/* Performance Chart */}
      {myTimingRecords.length > 0 && (
        <div className="bg-white rounded-2xl p-4 card-shadow">
          <div className="flex items-center gap-2 mb-3">
            <TrendingUp className="w-4 h-4 text-emerald-500" />
            <h3 className="text-sm font-bold text-gray-900">My Performance</h3>
          </div>
          <div className="h-40">
            <Line data={progressData} options={timingChartOptions} />
          </div>
          {bestTime && myTimingRecords.length > 1 && (
            <div className="flex items-center justify-center gap-1 mt-2">
              <Zap className="w-3 h-3 text-emerald-500" />
              <span className="text-xs text-emerald-600 font-medium">
                {(myTimingRecords[myTimingRecords.length - 1]?.timeSeconds ?? 0) > 0
                  ? `${Math.abs((myTimingRecords[0]?.timeSeconds ?? 0) - (myTimingRecords[myTimingRecords.length - 1]?.timeSeconds ?? 0)).toFixed(1)}s improvement!`
                  : 'Keep practicing!'}
              </span>
            </div>
          )}
        </div>
      )}

      {/* My Recent Timings */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <div className="flex items-center gap-2 mb-3">
          <Timer className="w-4 h-4 text-orange-500" />
          <h3 className="text-sm font-bold text-gray-900">My Timings</h3>
        </div>
        {myTimingRecords.length > 0 ? (
          <div className="space-y-2">
            {myTimingRecords.slice(0, 6).map((record, i) => (
              <div key={i} 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="px-2 py-0.5 bg-orange-100 text-orange-600 text-[10px] font-bold rounded-md">{record.distance}</span>
                  <span className="text-xs text-gray-400">{record.recordDate}</span>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-sm font-mono font-bold text-gray-800">{record.timeDisplay}</span>
                  {record.improvement && record.improvement > 0 && (
                    <span className="text-[10px] text-emerald-600 font-medium">-{record.improvement}s</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        ) : (
          <p className="text-sm text-gray-400 text-center py-4">No timing records yet</p>
        )}
      </div>

      {/* My Sprint Race Results */}
      {myRaceResults.length > 0 && (
        <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-purple-500" />
            <h3 className="text-sm font-bold text-gray-900">My Race Results</h3>
          </div>
          <div className="space-y-2">
            {myRaceResults.slice(0, 6).map((result, i) => (
              <div key={i} className="flex items-center justify-between py-2 border-b border-gray-50 last:border-0">
                <div>
                  <p className="text-sm font-semibold text-gray-900">{result.raceName}</p>
                  <div className="flex items-center gap-2 mt-0.5">
                    <span className="px-1.5 py-0.5 bg-purple-100 text-purple-600 text-[10px] font-bold rounded">{result.distance}</span>
                    <span className="text-[10px] text-gray-400">Round {result.round}</span>
                    {result.position && result.position > 0 && (
                      <span className="px-1.5 py-0.5 bg-amber-100 text-amber-700 text-[10px] font-bold rounded">Pos #{result.position}</span>
                    )}
                  </div>
                </div>
                <div className="text-right">
                  {result.status === 'dnf' ? (
                    <span className="text-sm font-bold text-red-500">DNF</span>
                  ) : (
                    <span className="text-sm font-mono font-bold text-gray-800">{result.timeDisplay}</span>
                  )}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Upcoming Events */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <div className="flex items-center gap-2 mb-3">
          <Award className="w-4 h-4 text-purple-500" />
          <h3 className="text-sm font-bold text-gray-900">Upcoming Events</h3>
        </div>
        <div className="space-y-3">
          {upcomingEvents.map(event => {
            const colors = eventTypeColors[event.type] || eventTypeColors.competition;
            return (
              <div key={event.id} className="flex items-center gap-3 p-3 bg-gray-50 rounded-xl">
                <div className={`w-10 h-10 ${colors.bg} rounded-xl flex items-center justify-center flex-shrink-0`}>
                  <Award className={`w-5 h-5 ${colors.icon}`} />
                </div>
                <div className="flex-1 min-w-0">
                  <p className="text-sm font-semibold text-gray-900 truncate">{event.title}</p>
                  <p className="text-xs text-gray-400">{event.date}</p>
                </div>
                <span className="px-2 py-0.5 bg-white text-gray-500 text-[10px] font-medium rounded-md capitalize">{event.type}</span>
              </div>
            );
          })}
        </div>
      </div>

      {/* Messages from Admin */}
      <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">
            <Bell className="w-4 h-4 text-blue-500" />
            <h3 className="text-sm font-bold text-gray-900">From Coach</h3>
          </div>
          {adminMessages.some(m => !m.read) && (
            <span className="px-2 py-0.5 bg-red-500 text-white text-[10px] font-bold rounded-full">{adminMessages.filter(m => !m.read).length} new</span>
          )}
        </div>
        <div className="space-y-2">
          {adminMessages.map(msg => (
            <div key={msg.id} className={`p-3 rounded-xl ${msg.read ? 'bg-gray-50' : 'bg-blue-50 border border-blue-100'}`}>
              <div className="flex items-start gap-2">
                {!msg.read && <div className="w-2 h-2 bg-blue-500 rounded-full mt-1.5 flex-shrink-0" />}
                <div className="flex-1">
                  <p className="text-sm text-gray-700">{msg.message}</p>
                  <p className="text-[10px] text-gray-400 mt-1">{msg.date}</p>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Achievements */}
      <div className="bg-white rounded-2xl p-4 card-shadow">
        <div className="flex items-center gap-2 mb-3">
          <Star className="w-4 h-4 text-amber-500" />
          <h3 className="text-sm font-bold text-gray-900">My Achievements</h3>
        </div>
        <div className="grid grid-cols-3 gap-3">
          {[
            { icon: <Trophy className="w-5 h-5 text-amber-500" />, label: '1st Sprint', sub: 'Completed' },
            { icon: <TrendingUp className="w-5 h-5 text-emerald-500" />, label: 'Improved', sub: myTimingRecords.length > 1 ? 'Active' : 'Keep going' },
            { icon: <Clock className="w-5 h-5 text-blue-500" />, label: '85%', sub: 'Attendance' },
          ].map((ach, i) => (
            <div key={i} className="flex flex-col items-center text-center p-3 bg-gray-50 rounded-xl">
              {ach.icon}
              <span className="text-xs font-semibold text-gray-800 mt-1.5">{ach.label}</span>
              <span className="text-[10px] text-gray-400">{ach.sub}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}
