import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../../store/auth';
import { 
  Calendar, BookOpen, DollarSign, MessageSquare, Clock, 
  ArrowRight, GraduationCap, CheckCircle2, Rocket, 
  BookText, ChevronRight, UserCircle
} from 'lucide-react';

export default function StudentDashboard() {
  const { user } = useAuthStore();
  const [myAttendance, setMyAttendance] = useState<any>({ present: 0, total: 0 });
  const [myFees, setMyFees] = useState<any>({ pending: 0, paid: 0 });
  const [myClasses, setMyClasses] = useState<any[]>([]);
  const [messages, setMessages] = useState<any[]>([]);

  useEffect(() => {
    if (user?.id) {
      api.get(`/attendance?student_id=${user.id}`).then(res => {
        const present = res.data.filter((a: any) => a.status === 'present').length;
        setMyAttendance({ present, total: res.data.length });
      });
      api.get(`/fees/students?student_id=${user.id}`).then(res => {
        const fees = res.data;
        const pending = fees.filter((f: any) => f.status !== 'paid').reduce((sum: number, f: any) => sum + (f.amount - f.paid_amount), 0);
        const paid = fees.filter((f: any) => f.status === 'paid').reduce((sum: number, f: any) => sum + f.paid_amount, 0);
        setMyFees({ pending, paid });
      });
    }
    api.get('/classes').then(res => setMyClasses(res.data.slice(0, 3)));
    api.get('/messages').then(res => setMessages(res.data.slice(0, 2)));
  }, [user?.id]);

  const stats = [
    { label: 'Attendance', value: myAttendance.total > 0 ? `${Math.round((myAttendance.present / myAttendance.total) * 100)}%` : '95%', icon: CheckCircle2, color: 'emerald' },
    { label: 'Active Classes', value: myClasses.length || '3', icon: BookOpen, color: 'blue' },
    { label: 'Fees Due', value: `$${myFees.pending || '500'}`, icon: DollarSign, color: 'orange' },
    { label: 'New Messages', value: messages.length || '2', icon: MessageSquare, color: 'purple' },
  ];

  const todayClasses = [
    { time: '09:00', period: 'AM', subject: 'Advanced Mathematics', detail: 'Room 302 • Prof. Sarah Jenkins' },
    { time: '11:30', period: 'AM', subject: 'Theoretical Physics', detail: 'Lab A1 • Dr. Michael Chen' },
    { time: '02:00', period: 'PM', subject: 'World History', detail: 'Main Hall • Prof. Elena Rodriguez' },
  ];

  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 {myClasses.length || 3} classes today and your attendance remains excellent.
          </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">Grade 2-A • 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">
        {/* Today's Schedule */}
        <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">Today's Classes</h3>
            <button className="text-primary text-[0.7rem] font-bold hover:underline flex items-center gap-1">
              View Full Timetable <ArrowRight size={14} />
            </button>
          </div>
          <div className="space-y-3">
            {todayClasses.map((cls, idx) => (
              <div key={idx} 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-sm font-black text-primary">{cls.time}</span>
                    <span className="text-[0.6rem] font-black uppercase text-text-muted">{cls.period}</span>
                  </div>
                  <div>
                    <p className="text-[0.95rem] font-bold text-text">{cls.subject}</p>
                    <p className="text-[0.7rem] text-text-muted font-medium">{cls.detail}</p>
                  </div>
                </div>
                <ChevronRight size={20} className="text-text-muted group-hover:text-primary transition-colors" />
              </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 className="bg-card border border-border rounded-2xl p-6 h-[320px] flex flex-col justify-between shadow-sm relative overflow-hidden">
            <div className="flex items-end justify-between h-44 px-4 relative z-10">
              {[
                { h: '70%', label: 'Mon' },
                { h: '85%', label: 'Tue' },
                { h: '100%', label: 'Wed', active: true },
                { h: '75%', label: 'Thu' },
                { h: '90%', label: 'Fri' }
              ].map((bar, i) => (
                <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 ${bar.active ? 'bg-primary' : 'bg-muted group-hover:bg-blue-200 dark:group-hover:bg-blue-900/40'}`} 
                    style={{ height: bar.h }}
                  >
                    {bar.active && <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">Current Day</div>}
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t border-border pt-4 flex justify-around relative z-10">
              {['Mon', 'Tue', 'Wed', 'Thu', 'Fri'].map((day, i) => (
                <span key={i} className={`text-[0.65rem] font-black uppercase tracking-widest ${day === 'Wed' ? 'text-primary' : 'text-text-muted'}`}>
                  {day}
                </span>
              ))}
            </div>
            <p className="text-[0.7rem] text-text-muted text-center italic font-medium mt-2">Overall stability: <span className="text-emerald-600 dark:text-emerald-400 font-bold uppercase tracking-tighter">Excellent</span></p>
          </div>
        </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-[#002147] 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">Upcoming Exam: Physics II</h4>
            <p className="text-slate-300 text-[0.9rem] max-w-md leading-relaxed font-medium">
              Your mid-term examination is scheduled for next Tuesday at 10:00 AM. Study materials are available in the course locker.
            </p>
            <button 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">
              Access Materials
              <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">
              Term 2 tuition fees are pending. Please complete payment by end of month.
            </p>
          </div>
          <div className="mt-8 flex items-center justify-between">
            <span className="text-3xl font-black tracking-tighter">$500.00</span>
            <button 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>
  );
}