import { useState, useEffect } from 'react';
import api, { useAuthStore } from '../../store/auth';
import { 
  BookOpen, Calendar, Clock, CheckCircle, MessageSquare, 
  Bell, Plus, Send, Edit3, UserCheck, ChevronRight, 
  Sparkles, MoreHorizontal
} from 'lucide-react';

export default function TeacherDashboard() {
  const { user } = useAuthStore();
  const [myClasses, setMyClasses] = useState<any[]>([]);
  const [pendingTasks, setPendingTasks] = useState(0);
  const [recentMessages, setRecentMessages] = useState<any[]>([]);

  useEffect(() => {
    api.get('/classes').then(res => setMyClasses(res.data.slice(0, 3)));
    api.get('/messages').then(res => {
      const unread = res.data.filter((m: any) => !m.is_read).length;
      setPendingTasks(unread);
      setRecentMessages(res.data.slice(0, 3));
    });
  }, []);

  const stats = [
    { label: 'Classes', value: myClasses.length || '4', icon: BookOpen, color: 'blue' },
    { label: 'Periods', value: '6', icon: Clock, color: 'orange' },
    { label: 'Tasks', value: '2', icon: CheckCircle, color: 'emerald' },
    { label: 'Messages', value: recentMessages.length || '5', icon: MessageSquare, color: 'purple' },
  ];

  const schedule = [
    { time: '08:00', subject: 'Math - Advanced Algebra', detail: 'Room 402 • Grade 11-A', status: 'Active' },
    { time: '09:30', subject: 'English - Literature II', detail: 'Room 105 • Grade 10-C', status: 'Upcoming' },
    { time: '11:00', subject: 'Science - Quantum Physics', detail: 'Lab 3 • Grade 12-B', status: 'Upcoming' },
    { time: '12:30', subject: 'Lunch Break', detail: '45 mins', isBreak: true },
    { time: '13:15', subject: 'Math - Remedial Session', detail: 'Room 402 • Various Grades', status: 'Upcoming' },
  ];

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Greeting & Stats Section */}
      <section className="flex flex-col lg:flex-row gap-6">
        <div className="flex-grow bg-[#0047AB] text-white p-10 rounded-3xl relative overflow-hidden flex flex-col justify-center shadow-xl shadow-blue-900/20">
          <div className="absolute right-[-40px] top-[-40px] opacity-10">
            <Sparkles size={240} strokeWidth={1} />
          </div>
          <div className="relative z-10">
            <h2 className="text-3xl font-black text-white mb-2 tracking-tight">Good day, {user?.first_name}!</h2>
            <p className="text-lg opacity-80 max-w-md font-medium leading-relaxed">
              You have 4 classes today and 2 pending tasks. Your first period starts in 15 minutes.
            </p>
          </div>
        </div>

        <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-2 gap-4 w-full lg:w-1/3">
          {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-xl flex items-center justify-center border group-hover:scale-110 transition-transform
                ${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'}`}>
                <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>
      </section>

      {/* Bento Layout Content */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Quick Actions & My Classes (Left) */}
        <div className="lg:col-span-3 space-y-8">
          <div className="space-y-4">
            <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Quick Actions</h3>
            <div className="space-y-2">
              {[
                { label: 'Take Attendance', icon: UserCheck },
                { label: 'Mark Grades', icon: Edit3 },
                { label: 'Send Message', icon: Send },
              ].map((action) => (
                <button key={action.label} className="w-full flex items-center gap-4 p-4 bg-card border border-border rounded-2xl hover:bg-primary hover:text-white hover:border-transparent transition-all group shadow-sm">
                  <action.icon size={20} className="group-hover:scale-110 transition-transform text-primary group-hover:text-white" />
                  <span className="text-sm font-bold tracking-tight">{action.label}</span>
                </button>
              ))}
            </div>
          </div>

          <div className="space-y-4 pt-4 border-t border-border">
            <div className="flex items-center justify-between">
              <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">My Classes</h3>
              <button className="text-primary text-[0.7rem] font-bold hover:underline">View All</button>
            </div>
            <div className="space-y-3">
              {myClasses.map((cls, idx) => (
                <div key={idx} className="bg-card border border-border p-4 rounded-2xl flex justify-between items-center group hover:border-primary transition-all cursor-pointer shadow-sm">
                  <div className="min-w-0">
                    <p className="font-bold text-text truncate group-hover:text-primary">{cls.name}</p>
                    <p className="text-[0.65rem] text-text-muted font-black uppercase tracking-wider mt-0.5">Grade {cls.section || '11-A'}</p>
                  </div>
                  <div className="bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 px-3 py-1 rounded-full text-[0.6rem] font-black tracking-tighter whitespace-nowrap border border-emerald-100 dark:border-emerald-900/30 shadow-sm">
                    {cls.capacity || '28'} Students
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Today's Schedule (Center) */}
        <div className="lg:col-span-6">
          <div className="bg-card border border-border rounded-3xl overflow-hidden shadow-sm">
            <div className="bg-muted/50 p-6 border-b border-border flex justify-between items-center">
              <h3 className="text-lg font-black text-text uppercase tracking-tight">Today's Schedule</h3>
              <div className="flex items-center gap-2 bg-card px-3 py-1.5 rounded-xl border border-border shadow-sm">
                <Calendar size={14} className="text-primary" />
                <span className="text-[0.7rem] font-black text-primary uppercase tracking-widest">{new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}</span>
              </div>
            </div>
            <div className="p-8 relative">
              {/* Timeline Line */}
              <div className="absolute left-14 top-10 bottom-10 w-0.5 bg-muted"></div>
              
              <div className="space-y-10">
                {schedule.map((period, idx) => (
                  <div key={idx} className={`relative flex items-center gap-10 group ${period.isBreak ? 'opacity-60' : ''}`}>
                    <div className="w-10 text-right shrink-0">
                      <p className={`text-xs font-black ${period.status === 'Active' ? 'text-primary' : 'text-text-muted'}`}>{period.time}</p>
                    </div>
                    
                    <div className={`w-3.5 h-3.5 rounded-full z-10 border-2 border-border shadow-md transition-all duration-300 ${period.status === 'Active' ? 'bg-primary ring-4 ring-primary/10 scale-125' : period.isBreak ? 'bg-muted' : 'bg-text-muted/30 group-hover:bg-primary'}`}></div>
                    
                    <div className={`flex-grow p-4 bg-card rounded-2xl border transition-all duration-300 ${period.status === 'Active' ? 'border-primary ring-4 ring-primary/5 shadow-md' : period.isBreak ? 'border-dashed border-border bg-muted/50' : 'border-border group-hover:border-primary shadow-sm'}`}>
                      {period.isBreak ? (
                        <div className="flex justify-center items-center py-1">
                          <p className="text-[0.7rem] font-black uppercase tracking-[3px] text-text-muted italic">{period.subject} ({period.detail})</p>
                        </div>
                      ) : (
                        <div className="flex justify-between items-start">
                          <div>
                            <h4 className={`font-bold tracking-tight ${period.status === 'Active' ? 'text-primary' : 'text-text'}`}>{period.subject}</h4>
                            <p className="text-[0.7rem] text-text-muted font-medium mt-1">{period.detail}</p>
                          </div>
                          {period.status && (
                            <span className={`text-[0.6rem] font-black uppercase px-2 py-1 rounded-lg tracking-tighter ${period.status === 'Active' ? 'bg-primary text-white shadow-md shadow-blue-900/10' : 'bg-muted text-text-muted'}`}>
                              {period.status}
                            </span>
                          )}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Recent Messages Brief (Right) */}
        <div className="lg:col-span-3 space-y-6">
          <div className="bg-card border border-border rounded-3xl p-6 shadow-sm">
            <div className="flex justify-between items-center mb-6">
              <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Messages</h3>
              <span className="bg-accent text-white dark:text-slate-900 text-[0.6rem] font-black px-2.5 py-1 rounded-full shadow-sm border border-accent/20">
                {pendingTasks} New
              </span>
            </div>
            <div className="space-y-4">
              {recentMessages.length > 0 ? recentMessages.map((msg, idx) => (
                <div key={idx} className="p-4 bg-muted/80 rounded-2xl border border-border hover:border-primary transition-all cursor-pointer group">
                  <div className="flex items-center gap-2 mb-2">
                    <div className="w-1.5 h-1.5 bg-primary rounded-full"></div>
                    <span className="text-[0.6rem] font-black uppercase tracking-wider text-primary">{msg.sender_role || 'Parent'}</span>
                  </div>
                  <h4 className="text-xs font-bold text-text mb-1 line-clamp-1 group-hover:text-primary transition-colors">{msg.subject}</h4>
                  <p className="text-[0.65rem] text-text-muted line-clamp-2 leading-relaxed font-medium">{msg.body}</p>
                </div>
              )) : (
                <div className="py-10 text-center">
                  <div className="bg-muted w-12 h-12 rounded-full flex items-center justify-center mx-auto mb-3">
                    <MessageSquare size={20} className="text-text-muted/30" />
                  </div>
                  <p className="text-xs text-text-muted font-bold uppercase tracking-widest">Inbox Clean</p>
                </div>
              )}
            </div>
            <button className="w-full mt-6 py-3 px-4 bg-slate-900 dark:bg-slate-800 hover:bg-black text-white font-bold text-[0.7rem] rounded-xl transition-all flex items-center justify-center gap-2 shadow-lg shadow-blue-950/20">
              Open Message Center
              <ChevronRight size={16} />
            </button>
          </div>

          <div className="bg-emerald-600 rounded-3xl p-6 text-white shadow-xl shadow-emerald-900/10 relative overflow-hidden group">
            <div className="absolute right-[-20px] top-[-20px] opacity-10 group-hover:scale-110 transition-transform duration-700">
              <CheckCircle size={140} strokeWidth={1} />
            </div>
            <div className="relative z-10">
              <h4 className="text-[0.6rem] font-black uppercase tracking-[3px] text-emerald-100 mb-4">Task Completion</h4>
              <div className="space-y-4">
                <div className="flex items-end justify-between">
                  <span className="text-3xl font-black tracking-tighter">84%</span>
                  <span className="text-[0.6rem] font-bold text-emerald-100 bg-white/10 px-2 py-1 rounded-lg">Above Average</span>
                </div>
                <div className="w-full bg-white/10 rounded-full h-2 shadow-inner">
                  <div className="bg-white h-full rounded-full w-[84%]"></div>
                </div>
                <p className="text-[0.7rem] font-medium leading-relaxed opacity-90">
                  Great job! You've completed 12 of 14 tasks this week.
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}