import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../../store/auth';
import api from '../../store/api';
import { useEducationTerms } from '../../utils/educationTerms';
import {
  BookOpen, Calendar, Clock, CheckCircle, MessageSquare,
  Plus, Send, Edit3, UserCheck, ChevronRight,
  Sparkles, MoreHorizontal, BarChart3, AlertTriangle
} from 'lucide-react';

export default function TeacherDashboard() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const terms = useEducationTerms();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  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 teacher 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 myClasses = data.myClasses || [];
  const todayStats = data.todayStats || { totalStudents: 0, periodsToday: 0, pendingTasks: 0, unreadMessages: 0 };
  const recentMessages = data.recentMessages || [];
  const todaysAttendance = data.todaysAttendance || { marked: 0, present: 0, absent: 0 };
  const mySubjects = data.mySubjects || [];
  // Education-level-aware KPI labels (shapeshift). Fall back to the
  // legacy strings when the controller hasn't shipped labels yet.
  const labels = data.labels || {
    marking: 'Marking',
    average: 'Average',
    below_average: 'Below Average',
  };

  const stats = [
    { label: 'Classes', value: myClasses.length, icon: BookOpen, color: 'blue', path: '/classes' },
    { label: labels.average, value: `${todayStats.average ?? 0}%`, icon: BarChart3, color: 'indigo', path: '/teacher-tools' },
    { label: labels.marking, value: todayStats.marking ?? todayStats.pendingTasks, icon: CheckCircle, color: 'orange', path: '/teacher-tools' },
    { label: labels.below_average, value: todayStats.belowAverage ?? 0, icon: AlertTriangle, color: (todayStats.belowAverage ?? 0) > 0 ? 'red' : 'emerald', path: '/students' },
  ];

  const attendancePct = todaysAttendance.marked > 0
    ? Math.round((todaysAttendance.present / todaysAttendance.marked) * 100)
    : 0;

  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-primary 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 {myClasses.length} {myClasses.length === 1 ? 'class' : 'classes'} and {todayStats.marking ?? todayStats.pendingTasks} pending {todayStats.marking ?? todayStats.pendingTasks === 1 ? 'task' : 'tasks'}.{' '}
              {attendancePct > 0 && `${attendancePct}% attendance marked today.`}
            </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} onClick={() => navigate(stat.path)} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-pointer">
              <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' :
                  stat.color === 'indigo' ? 'bg-indigo-50 dark:bg-indigo-900/20 text-indigo-600 dark:text-indigo-400 border-indigo-100 dark:border-indigo-900/30' :
                  stat.color === 'red' ? 'bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 border-red-100 dark:border-red-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, path: '/attendance/take' },
                { label: 'Mark Grades', icon: Edit3, path: '/teacher-tools' },
                { label: 'Send Message', icon: Send, path: '/messages' },
              ].map((action) => (
                <button key={action.label} onClick={() => navigate(action.path)} 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 onClick={() => navigate('/classes')} className="text-primary text-[0.7rem] font-bold hover:underline">View All</button>
            </div>
            <div className="space-y-3">
              {myClasses.length > 0 ? myClasses.map((cls: any) => (
                <div key={cls.id} onClick={() => navigate('/classes')} 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">
                      {cls.students} {cls.students === 1 ? 'Student' : 'Students'}
                    </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">
                    Active
                  </div>
                </div>
              )) : (
                <p className="text-sm text-text-muted text-center py-6">No classes assigned yet.</p>
              )}
            </div>

            {mySubjects.length > 0 && (
              <div className="pt-4 border-t border-border">
                <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mb-3">My {terms.subjects}</h3>
                <div className="flex flex-wrap gap-2">
                  {mySubjects.map((s: any) => (
                    <span key={s.id} className="px-3 py-1.5 bg-primary/10 text-primary rounded-lg text-[0.7rem] font-bold">
                      {s.name}
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Today's Attendance Overview (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 Overview</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 grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div className="p-6 bg-emerald-50/50 dark:bg-emerald-950/20 border border-emerald-100 dark:border-emerald-900/30 rounded-2xl">
                <p className="text-[0.65rem] text-emerald-700 dark:text-emerald-400 uppercase font-black tracking-widest">Present</p>
                <p className="text-3xl font-black text-emerald-700 dark:text-emerald-300 mt-2">{todaysAttendance.present}</p>
              </div>
              <div className="p-6 bg-red-50/50 dark:bg-red-950/20 border border-red-100 dark:border-red-900/30 rounded-2xl">
                <p className="text-[0.65rem] text-red-700 dark:text-red-400 uppercase font-black tracking-widest">Absent</p>
                <p className="text-3xl font-black text-red-700 dark:text-red-300 mt-2">{todaysAttendance.absent}</p>
              </div>
              <div className="p-6 bg-blue-50/50 dark:bg-blue-950/20 border border-blue-100 dark:border-blue-900/30 rounded-2xl">
                <p className="text-[0.65rem] text-blue-700 dark:text-blue-400 uppercase font-black tracking-widest">Marked</p>
                <p className="text-3xl font-black text-blue-700 dark:text-blue-300 mt-2">{todaysAttendance.marked}</p>
              </div>
            </div>
            {attendancePct > 0 && (
              <div className="px-8 pb-8">
                <div className="flex justify-between text-[0.7rem] font-black uppercase text-text-muted mb-2">
                  <span>Attendance Rate</span>
                  <span className="text-emerald-600 dark:text-emerald-400">{attendancePct}%</span>
                </div>
                <div className="w-full bg-muted rounded-full h-3 overflow-hidden border border-border shadow-inner">
                  <div className="bg-emerald-500 h-full rounded-full transition-all duration-1000" style={{ width: `${attendancePct}%` }}></div>
                </div>
              </div>
            )}
          </div>
        </div>

        {/* Recent Messages (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">
                {todayStats.unreadMessages} New
              </span>
            </div>
            <div className="space-y-4">
              {recentMessages.length > 0 ? recentMessages.map((msg: any) => (
                <div key={msg.id} onClick={() => navigate('/messages')} 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 || 'Sender'}</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 onClick={() => navigate('/messages')} 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>
      </div>
    </div>
  );
}
