/**
 * Teacher Dashboard (teacher)
 *
 * Consumes /api/dashboard/teacher via useDashboardStore. Layout:
 *   1. KPI tiles: courses taught, total students, pending grading, overall pending tasks
 *   2. Per-course table: avg_completion, median_score, students_below_threshold
 *   3. Recharts BarChart of per-course median score
 *   4. Today's attendance panel (legacy) and recent messages sidebar
 */

import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  BookOpen, ClipboardCheck, AlertTriangle, Users, BarChart3,
  AlertCircle, ShieldX, RefreshCw, CheckCircle2, MessageSquare,
} from 'lucide-react';
import {
  BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell,
} from 'recharts';
import { useDashboardStore } from '../../store/dashboard';
import { useEducationTerms } from '../../utils/educationTerms';
import { T } from '../../lib/terminology';

export default function TeacherDashboard() {
  const navigate = useNavigate();
  const terms = useEducationTerms();
  const {
    teacher, loading, error, accessDenied, fetchTeacher,
    teacherOutliers, fetchTeacherOutliers,
    teacherStudentDetail, fetchTeacherStudentDetail,
  } = useDashboardStore();

  useEffect(() => {
    fetchTeacher();
    fetchTeacherOutliers();
  }, [fetchTeacher, fetchTeacherOutliers]);

  if (loading && !teacher) {
    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" />
        <p className="text-text-muted font-medium animate-pulse">Loading teacher dashboard...</p>
      </div>
    );
  }

  if (accessDenied) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <ShieldX size={56} className="text-red-500" />
        <h2 className="text-2xl font-extrabold text-text">Access denied</h2>
        <p className="text-text-muted text-sm max-w-md text-center">
          {error || 'You do not have permission to view the teacher dashboard.'}
        </p>
        <button onClick={() => navigate('/dashboard/teacher')} className="px-4 py-2 bg-primary text-white rounded-xl hover:opacity-90">
          Go back
        </button>
      </div>
    );
  }

  if (error && !teacher) {
    return (
      <div className="flex flex-col justify-center items-center h-[60vh] gap-4">
        <AlertCircle size={48} className="text-red-500" />
        <p className="text-text-muted font-medium">Unable to load dashboard data.</p>
        <p className="text-sm text-text-muted">{error}</p>
        <button onClick={() => fetchTeacher()} className="flex items-center gap-2 px-4 py-2 bg-primary text-white rounded-xl">
          <RefreshCw size={16} /> Retry
        </button>
      </div>
    );
  }

  if (!teacher) return null;

  const courseCount = teacher.per_course?.length || 0;
  const belowThresholdTotal = (teacher.per_course || []).reduce(
    (sum, c) => sum + (c.students_below_threshold || 0),
    0,
  );

  const kpis = [
    { label: terms.subjects, value: courseCount, icon: BookOpen, color: 'blue', path: '/my-courses' },
    { label: teacher.labels?.average ?? 'Average', value: `${teacher.average ?? 0}%`, icon: BarChart3, color: 'indigo', path: '/teacher-tools' },
    { label: teacher.labels?.marking ?? 'Marking', value: (teacher.marking ?? teacher.pending_grading_count).toLocaleString(), icon: ClipboardCheck, color: 'orange', path: '/teacher-tools' },
    { label: teacher.labels?.below_average ?? 'Below Average', value: (teacher.below_average ?? belowThresholdTotal).toLocaleString(), icon: AlertTriangle, color: (teacher.below_average ?? belowThresholdTotal) > 0 ? 'red' : 'emerald', path: '/students' },
  ];

  // Bar chart: median score per course (null = no data)
  const chartData = (teacher.per_course || [])
    .filter((c) => c.median_score != null)
    .map((c) => ({
      course: c.course_name.length > 14 ? `${c.course_name.slice(0, 12)}…` : c.course_name,
      fullName: c.course_name,
      median: c.median_score as number,
      fill: (c.median_score as number) >= 70 ? '#10b981' : (c.median_score as number) >= 50 ? '#f59e0b' : '#ef4444',
    }));

  return (
    <div className="space-y-8 animate-in fade-in duration-500 pb-10">
      {/* Header */}
      <div className="flex flex-col md:flex-row md:items-end justify-between gap-4">
        <div>
          <h1 className="text-3xl font-extrabold text-text tracking-tight">Teacher Dashboard</h1>
          <p className="text-text-muted mt-1 text-lg">Your {terms.subjects.toLowerCase()}, students, and pending grading.</p>
        </div>
        <button onClick={() => fetchTeacher()} className="flex items-center gap-2 px-4 py-2 bg-card border border-border text-text rounded-xl text-sm font-semibold hover:border-primary hover:text-primary transition-all">
          <RefreshCw size={16} /> Refresh
        </button>
      </div>

      {/* KPI Tiles */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {kpis.map((kpi) => (
          <div
            key={kpi.label}
            onClick={() => navigate(kpi.path)}
            className="bg-card p-5 rounded-2xl border border-border flex items-center gap-4 hover:shadow-md transition-all group cursor-pointer"
          >
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center border group-hover:scale-110 transition-transform ${
              kpi.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' :
              kpi.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' :
              kpi.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' :
              kpi.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-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-900/30'
            }`}>
              <kpi.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{kpi.label}</p>
              <p className="text-2xl font-black text-text">{kpi.value}</p>
            </div>
          </div>
        ))}
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Per-course table */}
        <div className="lg:col-span-2 bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/50 flex items-center gap-2">
            <BarChart3 size={14} className="text-primary" />
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              Per-{terms.subject} Analytics
            </h4>
          </div>
          {(teacher.per_course?.length ?? 0) === 0 ? (
            <div className="p-10 text-center text-text-muted text-sm">
              No {terms.subjects.toLowerCase()} assigned yet.
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="w-full text-left">
                <thead className="bg-muted/80 border-b border-border">
                  <tr>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest">{terms.subject}</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Enrolled</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Avg Completion</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">Median Score</th>
                    <th className="px-6 py-4 text-[0.6rem] uppercase text-text-muted font-black tracking-widest text-right">{T.BELOW_THRESHOLD_HEADER}</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-border">
                  {teacher.per_course!.map((c) => {
                    const scoreColor =
                      c.median_score == null ? 'text-text-muted'
                        : c.median_score >= 70 ? 'text-emerald-600 dark:text-emerald-400'
                        : c.median_score >= 50 ? 'text-orange-600 dark:text-orange-400'
                        : 'text-red-600 dark:text-red-400';
                    return (
                      <tr key={c.course_id} className="hover:bg-muted/30 transition-colors">
                        <td className="px-6 py-4">
                          <p className="text-[0.9rem] font-bold text-text">{c.course_name}</p>
                          <p className="text-[0.6rem] text-text-muted font-mono">#{c.course_id}</p>
                        </td>
                        <td className="px-6 py-4 text-right text-sm font-semibold">{c.enrolled}</td>
                        <td className="px-6 py-4 text-right text-sm font-semibold">{c.avg_completion}%</td>
                        <td className={`px-6 py-4 text-right text-sm font-black ${scoreColor}`}>
                          {c.median_score != null ? `${c.median_score}%` : '—'}
                        </td>
                        <td className="px-6 py-4 text-right">
                          {c.students_below_threshold > 0 ? (
                            <span className="px-2.5 py-1 rounded-full text-[0.6rem] font-black uppercase bg-red-50 dark:bg-red-900/20 text-red-600 dark:text-red-400 border border-red-100 dark:border-red-900/30">
                              {c.students_below_threshold}
                            </span>
                          ) : (
                            <span className="px-2.5 py-1 rounded-full text-[0.6rem] font-black uppercase bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border border-emerald-100 dark:border-emerald-900/30">
                              OK
                            </span>
                          )}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>

        {/* Right column: today + messages */}
        <div className="space-y-6">
          {/* Today's attendance (legacy) */}
          {teacher.todaysAttendance && (
            <div className="bg-card border border-border rounded-2xl overflow-hidden shadow-sm">
              <div className="px-6 py-4 border-b border-border bg-muted/50">
                <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">Today&apos;s Attendance</h4>
              </div>
              <div className="p-5 grid grid-cols-3 gap-3">
                <div className="text-center">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-emerald-600">Present</p>
                  <p className="text-2xl font-black text-emerald-600 dark:text-emerald-300">{teacher.todaysAttendance.present}</p>
                </div>
                <div className="text-center">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-red-600">Absent</p>
                  <p className="text-2xl font-black text-red-600 dark:text-red-300">{teacher.todaysAttendance.absent}</p>
                </div>
                <div className="text-center">
                  <p className="text-[0.55rem] uppercase font-black tracking-widest text-blue-600">Marked</p>
                  <p className="text-2xl font-black text-blue-600 dark:text-blue-300">{teacher.todaysAttendance.marked}</p>
                </div>
              </div>
              {teacher.todaysAttendance.marked > 0 && (
                <div className="px-5 pb-5">
                  <div className="w-full bg-muted rounded-full h-2.5 overflow-hidden border border-border">
                    <div
                      className="bg-emerald-500 h-full transition-all"
                      style={{ width: `${Math.round((teacher.todaysAttendance.present / teacher.todaysAttendance.marked) * 100)}%` }}
                    />
                  </div>
                  <p className="text-[0.65rem] text-text-muted mt-1 text-center">
                    {Math.round((teacher.todaysAttendance.present / teacher.todaysAttendance.marked) * 100)}% present
                  </p>
                </div>
              )}
            </div>
          )}

          {/* Recent messages */}
          <div className="bg-card border border-border rounded-2xl p-6 shadow-sm">
            <div className="flex justify-between items-center mb-4">
              <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Messages</h4>
              <span className="bg-accent text-[#002147] text-[0.6rem] font-black px-2.5 py-1 rounded-full">
                {teacher.todayStats.unreadMessages} new
              </span>
            </div>
            <div className="space-y-3 max-h-72 overflow-y-auto">
              {(teacher.recentMessages?.length ?? 0) === 0 ? (
                <div className="text-center py-6 text-text-muted">
                  <MessageSquare size={20} className="mx-auto mb-2 opacity-30" />
                  <p className="text-[0.65rem] font-bold uppercase tracking-widest">Inbox clean</p>
                </div>
              ) : (
                teacher.recentMessages!.slice(0, 5).map((m) => (
                  <div key={m.id} onClick={() => navigate('/messages')} className="p-3 bg-muted/40 rounded-xl border border-border hover:border-primary transition-all cursor-pointer">
                    <div className="flex items-center gap-2 mb-1">
                      <div className="w-1.5 h-1.5 bg-primary rounded-full" />
                      <span className="text-[0.6rem] font-black uppercase tracking-wider text-primary">{m.sender_role || 'Sender'}</span>
                    </div>
                    <p className="text-xs font-bold text-text line-clamp-1">{m.subject}</p>
                    <p className="text-[0.65rem] text-text-muted line-clamp-2 mt-1">{m.body}</p>
                  </div>
                ))
              )}
            </div>
            <button onClick={() => navigate('/messages')} className="w-full mt-4 py-2.5 px-4 bg-muted hover:bg-muted/80 text-text font-bold text-[0.7rem] uppercase tracking-widest rounded-xl border border-border transition-all flex items-center justify-center gap-2">
              Open Message Center <CheckCircle2 size={14} />
            </button>
          </div>
        </div>
      </div>

      {/* Median score chart */}
      <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
        <div className="px-6 py-4 border-b border-border bg-muted/50 flex items-center gap-2">
          <BarChart3 size={14} className="text-primary" />
          <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
            Median Score by {terms.subject}
          </h4>
        </div>
        <div className="p-6">
          {chartData.length === 0 ? (
            <div className="py-10 text-center text-text-muted text-sm">
              No graded marks yet — the chart will populate once students complete work.
            </div>
          ) : (
            <div className="h-72 w-full">
              <ResponsiveContainer width="100%" height="100%">
                <BarChart data={chartData} margin={{ top: 10, right: 10, left: 0, bottom: 40 }}>
                  <CartesianGrid strokeDasharray="3 3" stroke="rgba(148,163,184,0.2)" />
                  <XAxis dataKey="course" tick={{ fill: 'currentColor', fontSize: 11 }} angle={-25} textAnchor="end" interval={0} />
                  <YAxis domain={[0, 100]} tick={{ fill: 'currentColor', fontSize: 11 }} unit="%" />
                  <Tooltip
                    cursor={{ fill: 'currentColor', className: 'text-muted/10' }}
                    contentStyle={{ backgroundColor: 'var(--card)', border: '1px solid var(--border)', borderRadius: 12, color: 'var(--text)' }}
                    labelStyle={{ color: 'var(--text-light)', fontWeight: 700 }}
                    formatter={(value: number, _name: string, props: any) => [
                      `${value}%`,
                      props?.payload?.fullName || 'Score',
                    ]}
                  />
                  <Bar dataKey="median" radius={[8, 8, 0, 0]}>
                    {chartData.map((entry, i) => (
                      <Cell key={`cell-${i}`} fill={entry.fill} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
            </div>
          )}
        </div>
      </div>
    {/* Outliers + Drill-down */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/50 flex items-center gap-2">
            <AlertTriangle size={14} className="text-red-500" />
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              {T.OUTLIERS_HEADING}
            </h4>
            <span className="ml-auto text-[0.7rem] font-bold text-text-muted">
              {teacherOutliers.length} flagged
            </span>
          </div>
          <div className="p-4 max-h-72 overflow-y-auto">
            {teacherOutliers.length === 0 ? (
              <div className="py-6 text-center text-text-muted text-sm">
                <CheckCircle2 size={20} className="mx-auto mb-2 text-emerald-500 opacity-50" />
                <p>{T.BELOW_THRESHOLD_EMPTY}</p>
              </div>
            ) : (
              <div className="space-y-2">
                {teacherOutliers.map((o) => (
                  <div
                    key={`${o.student_id}-${o.course_id}`}
                    onClick={() => fetchTeacherStudentDetail(o.student_id)}
                    className="flex items-center justify-between gap-2 p-2.5 bg-red-50/40 dark:bg-red-950/20 rounded-xl border border-red-100 dark:border-red-900/30 hover:border-red-400 cursor-pointer transition-all"
                  >
                    <div className="min-w-0 flex-1">
                      <p className="text-sm font-bold text-text truncate">{o.student_name}</p>
                      <p className="text-[0.6rem] text-text-muted">{o.course_name} • {o.grades_count} marks</p>
                    </div>
                    <div className="text-right shrink-0">
                      <p className="text-base font-black text-red-600 dark:text-red-300">{o.avg_score}%</p>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        <div className="bg-card rounded-2xl border border-border overflow-hidden shadow-sm">
          <div className="px-6 py-4 border-b border-border bg-muted/50 flex items-center gap-2">
            <Users size={14} className="text-primary" />
            <h4 className="text-[0.65rem] font-black uppercase tracking-[2px] text-primary">
              {T.STUDENT_DRILLDOWN}
            </h4>
            <span className="ml-auto text-[0.7rem] font-bold text-text-muted">
              {T.OUTLIERS_CTA}
            </span>
          </div>
          <div className="p-4 max-h-72 overflow-y-auto">
            {!teacherStudentDetail ? (
              <div className="py-6 text-center text-text-muted text-sm">
                <Users size={20} className="mx-auto mb-2 opacity-30" />
                <p>{T.SELECT_FLAGGED_LEARNER}</p>
              </div>
            ) : (
              <div className="space-y-3">
                <div className="flex items-center justify-between">
                  <p className="text-base font-extrabold text-text">{teacherStudentDetail.student.name}</p>
                  <p className="text-[0.6rem] text-text-muted">{teacherStudentDetail.student.email}</p>
                </div>
                <div className="grid grid-cols-3 gap-2 text-center">
                  <div className="p-2 bg-muted/40 rounded-xl border border-border">
                    <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Attendance</p>
                    <p className={`text-base font-black ${teacherStudentDetail.attendance.percent >= 75 ? 'text-emerald-600' : 'text-red-600'}`}>
                      {teacherStudentDetail.attendance.percent}%
                    </p>
                  </div>
                  <div className="p-2 bg-muted/40 rounded-xl border border-border">
                    <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Submissions</p>
                    <p className="text-base font-black text-text">{teacherStudentDetail.submissions.graded}/{teacherStudentDetail.submissions.total}</p>
                  </div>
                  <div className="p-2 bg-muted/40 rounded-xl border border-border">
                    <p className="text-[0.55rem] uppercase font-black tracking-widest text-text-muted">Points</p>
                    <p className="text-base font-black text-purple-600">{teacherStudentDetail.gamification_points}</p>
                  </div>
                </div>
                {teacherStudentDetail.grades_history.length > 0 && (
                  <div>
                    <p className="text-[0.6rem] uppercase font-black tracking-widest text-text-muted mb-1">{T.RECENT_GRADES}</p>
                    <div className="space-y-1 max-h-32 overflow-y-auto">
                      {teacherStudentDetail.grades_history.slice(0, 5).map((g) => (
                        <div key={g.id} className="flex justify-between items-center text-xs px-2 py-1 bg-muted/30 rounded">
                          <span className="font-bold truncate">{g.subject}</span>
                          <span className={`font-black ${g.pct >= 70 ? 'text-emerald-600' : g.pct >= 50 ? 'text-orange-600' : 'text-red-600'}`}>
                            {g.pct}%
                          </span>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
