import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import { GradeBadge } from '../../components/GradeBadge';
import {
  Calendar, BookOpen, DollarSign, MessageSquare,
  ArrowRight, GraduationCap, CheckCircle2, Rocket,
  BookText, ChevronRight, UserCircle, Sparkles, FileCheck
} from 'lucide-react';

export default function StudentDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  // PR 3 §6.4 — count of submissions with at least one returned marked-script
  // attachment. Drives the "Marked scripts available" callout below the recent
  // grades card.
  const [markedScriptCount, setMarkedScriptCount] = useState(0);
  const [recentMarkedScript, setRecentMarkedScript] = useState<any | null>(null);

  useEffect(() => {
    api.get('/dashboard/student')
      .then(res => setData(res.data))
      .catch(err => {
        console.error('Failed to load student dashboard:', err);
        setError(err?.response?.data?.error || 'Failed to load dashboard');
      })
      .finally(() => setLoading(false));
  }, []);

  // PR 3 §6.4 — fetch my submissions so we can surface "X new marked scripts
  // available" when the teacher has returned work. Pulled separately from
  // /dashboard/student so the dashboard call doesn't have to grow a new field.
  useEffect(() => {
    let cancelled = false;
    api.get('/assignments/my/submissions')
      .then(res => {
        if (cancelled) return;
        const rows: any[] = Array.isArray(res.data) ? res.data : [];
        const returnedWithScripts = rows.filter(s =>
          s.status === 'returned' && Array.isArray(s.marked_scripts) && s.marked_scripts.length > 0
        );
        setMarkedScriptCount(returnedWithScripts.length);
        // Track the most recent returned submission so the callout can label it.
        if (returnedWithScripts.length > 0) {
          returnedWithScripts.sort((a, b) => {
            const at = a.graded_at || a.submitted_at || '';
            const bt = b.graded_at || b.submitted_at || '';
            return bt.localeCompare(at);
          });
          setRecentMarkedScript(returnedWithScripts[0]);
        } else {
          setRecentMarkedScript(null);
        }
      })
      .catch(err => {
        // Silent — a missing endpoint or 403 shouldn't break the dashboard.
        console.warn('Could not load marked-scripts summary:', err?.response?.status || err?.message);
        if (!cancelled) {
          setMarkedScriptCount(0);
          setRecentMarkedScript(null);
        }
      });
    return () => { cancelled = true; };
  }, []);

  if (loading) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
      <p className="text-text-muted font-medium animate-pulse">Loading student dashboard...</p>
    </div>
  );

  if (error || !data) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
      <p className="text-text-muted font-medium">Unable to load dashboard data.</p>
      <p className="text-sm text-text-muted">{error}</p>
      <button onClick={() => window.location.reload()} className="px-4 py-2 bg-primary text-white rounded-xl">Retry</button>
    </div>
  );

  const attendancePercent = data.attendancePercent || 0;
  const activeClasses = data.activeClasses || 0;
  const fees = data.feesSummary || { pending: 0, paid: 0 };
  const unreadMessages = data.unreadMessages || 0;
  const upcomingExams = data.upcomingExams || [];
  const recentGrades = data.recentGrades || [];
  const attendanceByDay = data.attendanceByDay || [];
  const pendingAssignments = data.pendingAssignments || 0;

  const stats = [
    { label: 'Attendance', value: `${attendancePercent}%`, icon: CheckCircle2, color: 'emerald' },
    { label: 'Active Classes', value: activeClasses, icon: BookOpen, color: 'blue' },
    { label: 'Fees Due', value: `$${fees.pending.toLocaleString()}`, icon: DollarSign, color: 'orange' },
    { label: 'New Messages', value: unreadMessages, icon: MessageSquare, color: 'purple' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Header & Profile Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-end">
        <div className="lg:col-span-8">
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Hello, {user?.first_name}!</h1>
          <p className="text-text-muted mt-2 text-lg max-w-xl font-medium">
            Welcome back to your learning hub. You have {activeClasses} active {activeClasses === 1 ? 'class' : 'classes'} and your attendance is at {attendancePercent}%.
          </p>
        </div>
        <div className="lg:col-span-4">
          <div className="bg-card rounded-2xl p-6 border border-border shadow-sm relative overflow-hidden flex items-center gap-4">
            <div className="absolute top-0 right-0 w-24 h-24 bg-primary/5 rounded-full -mr-12 -mt-12"></div>
            <div className="w-16 h-16 rounded-xl bg-blue-50 dark:bg-blue-900/20 flex items-center justify-center text-primary border border-blue-100 dark:border-blue-900/30 shadow-inner">
              <UserCircle size={40} strokeWidth={1.5} />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-lg font-bold text-text truncate">{user?.first_name} {user?.last_name}</p>
              <p className="text-[0.65rem] font-bold text-text-muted uppercase tracking-wider mt-0.5">ID: #EDU-{user?.id || '001'}</p>
              <span className="mt-2 inline-flex px-2.5 py-1 bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 rounded-full text-[0.6rem] font-black uppercase tracking-tight border border-emerald-100 dark:border-emerald-900/30">Active Enrollment</span>
            </div>
          </div>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center
              ${stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-900/30' :
                stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-900/30' :
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-900/30' :
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-900/30'}
              border group-hover:scale-110 transition-transform`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <p className="text-2xl font-black text-text">{stat.value}</p>
            </div>
          </div>
        ))}
      </div>

      {/* Content Row: Schedule and Chart */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-6">
        {/* Upcoming Exams */}
        <div className="lg:col-span-7 space-y-4">
          <div className="flex items-center justify-between mb-2">
            <h3 className="text-lg font-black text-text uppercase tracking-tight">Upcoming Exams</h3>
            <button onClick={() => navigate('/exams')} className="text-primary text-[0.7rem] font-bold hover:underline flex items-center gap-1">
              View All <ArrowRight size={14} />
            </button>
          </div>
          <div className="space-y-3">
            {upcomingExams.length > 0 ? upcomingExams.map((exam: any) => (
              <div key={exam.id} onClick={() => navigate('/exams')} className="bg-card border border-border rounded-2xl p-4 flex items-center justify-between hover:border-primary hover:shadow-sm transition-all cursor-pointer group">
                <div className="flex items-center gap-4">
                  <div className="w-16 h-16 bg-muted rounded-xl flex flex-col items-center justify-center border border-border shadow-inner group-hover:bg-blue-50 dark:group-hover:bg-blue-900/20 transition-colors">
                    <span className="text-xs font-black text-primary">{exam.formattedTime || 'TBA'}</span>
                    <span className="text-[0.55rem] font-black uppercase text-text-muted">{exam.durationMinutes || 120}min</span>
                  </div>
                  <div>
                    <p className="text-[0.95rem] font-bold text-text">{exam.subject}</p>
                    <p className="text-[0.7rem] text-text-muted font-medium">{exam.formattedDate} • {exam.className}</p>
                  </div>
                </div>
                <ChevronRight size={20} className="text-text-muted group-hover:text-primary transition-colors" />
              </div>
            )) : (
              <p className="text-sm text-text-muted text-center py-10 bg-card border border-dashed border-border rounded-2xl">
                No upcoming exams in the next two weeks.
              </p>
            )}
          </div>

          {/* Recent Grades */}
          {recentGrades.length > 0 && (
            <div className="pt-4">
              <h3 className="text-lg font-black text-text uppercase tracking-tight mb-4">Recent Grades</h3>
              <div className="space-y-2">
                {recentGrades.map((g: any) => (
                  <div key={g.id} onClick={() => navigate('/grades')} className="bg-card border border-border p-3 rounded-xl flex items-center justify-between hover:border-primary transition-all cursor-pointer">
                    <div>
                      <p className="font-bold text-text text-sm">{g.subject}</p>
                      <p className="text-[0.65rem] text-text-muted uppercase font-black tracking-wider">{g.examType} • {g.time}</p>
                    </div>
                    <div className="text-right">
                      <p className="text-lg font-black text-text">{g.marks}/{g.totalMarks}</p>
                      <div className="mt-1">
                        <GradeBadge
                          percentage={g.percent}
                          gradingScale={(g as any).grading_scale ?? null}
                          band={(g as any).resolved_scale ? {
                            letter: g.grade,
                            scale: { key: (g as any).resolved_scale, label: '' },
                          } : null}
                          size="sm"
                        />
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Attendance Summary Chart */}
        <div className="lg:col-span-5 space-y-4">
          <h3 className="text-lg font-black text-text uppercase tracking-tight">Attendance Summary</h3>
          <div onClick={() => navigate('/attendance')} className="bg-card border border-border rounded-2xl p-6 h-[320px] flex flex-col justify-between shadow-sm relative overflow-hidden cursor-pointer group hover:border-primary transition-all">
            <div className="flex items-end justify-between h-44 px-4 relative z-10">
              {attendanceByDay.length > 0 ? attendanceByDay.map((day: any, i: number) => {
                const dt = new Date(day.date);
                return (
                  <div key={i} className="flex flex-col items-center gap-3 w-8 group">
                    <div
                      className={`w-full rounded-t-xl transition-all duration-500 relative ${day.present >= 80 ? 'bg-primary' : day.present >= 50 ? 'bg-orange-400' : 'bg-red-400'}`}
                      style={{ height: `${day.present}%` }}
                    >
                      <div className="absolute -top-10 left-1/2 -translate-x-1/2 bg-slate-900 text-white text-[0.6rem] font-black px-2 py-1 rounded-lg whitespace-nowrap shadow-lg">
                        {day.present}%
                      </div>
                    </div>
                  </div>
                );
              }) : (
                <p className="w-full text-center text-text-muted text-sm">No attendance data yet.</p>
              )}
            </div>
            <div className="border-t border-border pt-4 flex justify-around relative z-10">
              {attendanceByDay.map((day: any, i: number) => {
                const dt = new Date(day.date);
                return (
                  <span key={i} className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">
                    {dt.toLocaleDateString('en-US', { weekday: 'short' })}
                  </span>
                );
              })}
            </div>
            <p className="text-[0.7rem] text-text-muted text-center italic font-medium mt-2">
              Overall: <span className="text-emerald-600 dark:text-emerald-400 font-bold uppercase tracking-tighter">{attendancePercent}% — {
                attendancePercent >= 90 ? 'Excellent' : attendancePercent >= 75 ? 'Good' : attendancePercent >= 50 ? 'Needs improvement' : 'Concerning'
              }</span>
            </p>
          </div>
        </div>
      </div>

      {/* PR 3 §6.4 — marked-scripts callout. Appears above the
          Financials/Academic-Alert row whenever at least one of the student's
          submissions has been returned with a marked_script attachment. */}
      {markedScriptCount > 0 && (
        <div
          onClick={() => navigate('/assignments')}
          className="bg-emerald-50 border border-emerald-200 dark:bg-emerald-500/10 dark:border-emerald-500/30 rounded-3xl p-6 sm:p-7 flex flex-col sm:flex-row items-start sm:items-center gap-4 cursor-pointer hover:shadow-lg hover:border-emerald-300 transition-all group"
          role="button"
          tabIndex={0}
          onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') navigate('/assignments'); }}
        >
          <div className="w-14 h-14 rounded-2xl bg-card border border-emerald-100 dark:border-emerald-500/30 flex items-center justify-center text-emerald-600 shrink-0 shadow-sm group-hover:scale-105 transition-transform">
            <FileCheck size={26} />
          </div>
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-2 mb-1">
              <span className="text-[0.6rem] font-black uppercase tracking-[3px] text-emerald-700 dark:text-emerald-400">Marked Scripts Available</span>
              <span className="inline-flex items-center justify-center min-w-[20px] h-5 px-1.5 rounded-full bg-emerald-600 text-white text-[0.65rem] font-black">
                {markedScriptCount}
              </span>
            </div>
            <h4 className="text-lg font-black text-text tracking-tight">
              {markedScriptCount === 1
                ? 'Your teacher has returned a marked script.'
                : `Your teacher has returned ${markedScriptCount} marked scripts.`}
            </h4>
            {recentMarkedScript?.assignment_title && (
              <p className="text-sm text-text-muted mt-1 font-medium">
                Latest: <span className="font-bold text-text">{recentMarkedScript.assignment_title}</span>
                {recentMarkedScript.marked_scripts?.[0]?.uploaded_at && (
                  <span className="text-text-muted/70"> · returned {new Date(recentMarkedScript.marked_scripts[0].uploaded_at).toLocaleDateString()}</span>
                )}
              </p>
            )}
          </div>
          <div className="flex items-center gap-2 text-emerald-700 dark:text-emerald-400 font-black text-xs uppercase tracking-widest group-hover:translate-x-1 transition-transform">
            Open Assignments
            <ChevronRight size={18} />
          </div>
        </div>
      )}

      {/* Notifications / High-Impact Cards */}
      <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div className="md:col-span-2 bg-slate-900 text-white p-8 rounded-3xl overflow-hidden relative group shadow-xl shadow-blue-900/10">
          <div className="relative z-10">
            <div className="flex items-center gap-2 mb-4 text-[#FFA500]">
              <BookText size={18} strokeWidth={2.5} />
              <span className="text-[0.6rem] font-black uppercase tracking-[3px]">Academic Alert</span>
            </div>
            <h4 className="text-2xl font-black mb-2 tracking-tight">
              {upcomingExams.length > 0 ? `Upcoming Exam: ${upcomingExams[0].subject}` : 'No Upcoming Exams'}
            </h4>
            <p className="text-slate-300 text-[0.9rem] max-w-md leading-relaxed font-medium">
              {upcomingExams.length > 0
                ? `Your examination is scheduled for ${upcomingExams[0].formattedDate} at ${upcomingExams[0].formattedTime}. Study materials are available in your course locker.`
                : 'You have no exams in the next two weeks. Use this time to revise and complete any pending assignments.'}
              {pendingAssignments > 0 && ` You have ${pendingAssignments} assignment${pendingAssignments === 1 ? '' : 's'} due soon.`}
            </p>
            <button onClick={() => navigate('/exams')} className="mt-8 bg-[#FFA500] hover:bg-[#FF8C00] text-[#002147] font-black py-3 px-8 rounded-xl transition-all flex items-center gap-2 group/btn shadow-lg shadow-orange-500/20 active:scale-95">
              {upcomingExams.length > 0 ? 'Access Materials' : 'View Assignments'}
              <Rocket size={18} className="group-hover/btn:translate-x-1 group-hover/btn:-translate-y-1 transition-transform" />
            </button>
          </div>
          <div className="absolute bottom-[-40px] right-[-40px] opacity-[0.03] group-hover:opacity-10 transition-opacity duration-700">
            <Rocket size={300} />
          </div>
        </div>

        <div className="bg-[#FFA500] text-[#002147] p-8 rounded-3xl flex flex-col justify-between shadow-xl shadow-orange-500/10 relative overflow-hidden group">
          <div className="absolute top-[-20px] left-[-20px] w-24 h-24 bg-white/10 rounded-full"></div>
          <div>
            <div className="flex items-center gap-2 mb-4">
              <DollarSign size={18} strokeWidth={2.5} />
              <span className="text-[0.6rem] font-black uppercase tracking-[3px]">Financials</span>
            </div>
            <h4 className="text-2xl font-black mb-2 tracking-tight">Fee Reminder</h4>
            <p className="text-[0.85rem] font-bold opacity-80 leading-snug">
              {fees.pending > 0
                ? `Outstanding balance of $${fees.pending.toLocaleString()}. Please pay via Paynow or Ecocash before the due date.`
                : 'All fees are paid up. Thank you!'}
            </p>
          </div>
          <div className="mt-8 flex items-center justify-between">
            <span className="text-3xl font-black tracking-tighter">${fees.pending.toLocaleString()}</span>
            <button onClick={() => navigate('/fees')} className="bg-[#002147] text-white p-3 rounded-2xl hover:scale-110 transition-transform shadow-lg active:scale-95">
              <ArrowRight size={24} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
