import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useNavigate, useLocation } from 'react-router-dom';
import api from '../../store/auth';
import { useAuthStore } from '../../store/auth';
import { useEducationTerms } from '../../utils/educationTerms';
import {
  Users, Mail, Phone, Eye, TrendingUp, Award,
  AlertCircle, CheckCircle2, XCircle, X,
  ChevronRight, Search, Filter, Download,
  Sparkles, GraduationCap, BarChart3, Clock,
  MoreHorizontal, MessageSquare, Info, FileText,
  Brain, Home, Heart, Pencil, Lightbulb, BookOpen
} from 'lucide-react';
import { StudentSocialDoc } from '../../components/StudentSocialDoc';
import { Avatar } from '../../components/Avatar';
import { useTeacherStore } from '../../store/teacher';

interface Student {
  id: number;
  first_name: string;
  last_name: string;
  email: string;
  phone: string;
  course: string;
  score: number;
  progress: number;
  status: 'excellent' | 'good' | 'attention';
  attendance: number;
  assignmentsCompleted: number;
  totalAssignments: number;
}

interface GradeItem {
  assignment: string;
  score: number;
  maxScore: number;
  date: string;
}

interface AttendanceItem {
  date: string;
  status: 'present' | 'absent' | 'excused';
}

export default function Students() {
  const navigate = useNavigate();
  const location = useLocation();
  const terms = useEducationTerms();
  const { user } = useAuthStore();
  const [students, setStudents] = useState<Student[]>([]);
  const [selectedStudent, setSelectedStudent] = useState<Student | null>(null);
  const [showDetailsModal, setShowDetailsModal] = useState(false);
  const [activeTab, setActiveTab] = useState<'overview' | 'social' | 'grades' | 'attendance' | 'assignments'>('overview');
  const [filterStatus, setFilterStatus] = useState<'all' | 'excellent' | 'good' | 'attention'>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(true);
  
  const [studentGrades, setStudentGrades] = useState<GradeItem[]>([]);
  const [studentAttendance, setStudentAttendance] = useState<AttendanceItem[]>([]);
  const [studentAssignments, setStudentAssignments] = useState<any[]>([]);
  const [studentSocialDoc, setStudentSocialDoc] = useState<any | null>(null);
  const [socialLoading, setSocialLoading] = useState(false);
  const { fetchStudentDoc } = useTeacherStore();

  useEffect(() => {
    loadStudents();
  }, []);

  const loadStudents = async () => {
    setLoading(true);
    try {
      const res = await api.get('/users/teacher-students');
      // Defensive dedupe: keep the first occurrence per numeric id.
      const deduped = new Map<number, any>();
      (Array.isArray(res.data) ? res.data : []).forEach((s: any) => {
        if (!deduped.has(s.id)) deduped.set(s.id, s);
      });
      setStudents(Array.from(deduped.values()));
    } catch (err) {
      console.error('Failed to load student directory');
      setStudents([]);
    } finally {
      setLoading(false);
    }
  };

  const loadStudentDetails = async (studentId: number) => {
    try {
      // Fetch grades
      const gradesRes = await api.get(`/grades?student_id=${studentId}`);
      setStudentGrades(gradesRes.data.map((g: any) => ({
        assignment: g.subject_name || 'Term Assessment',
        score: g.marks,
        maxScore: g.total_marks,
        date: g.created_at?.split(' ')[0] || '2024-06-01'
      })));

      // Fetch attendance
      const attendanceRes = await api.get(`/attendance?student_id=${studentId}`);
      setStudentAttendance(attendanceRes.data.slice(0, 14).map((a: any) => ({
        date: a.date,
        status: a.status
      })));

      // Fetch assignments
      const assignmentsRes = await api.get(`/assignments?student_id=${studentId}`);
      setStudentAssignments(assignmentsRes.data.map((a: any) => ({
        title: a.title,
        dueDate: a.due_date,
        status: a.submission_status || 'pending',
        grade: a.grade
      })));

      // Fetch social doc (best-effort: server returns placeholder if not found)
      try {
        setSocialLoading(true);
        await fetchStudentDoc(String(studentId));
        setStudentSocialDoc(useTeacherStore.getState().currentStudentDoc);
      } finally {
        setSocialLoading(false);
      }
    } catch (err) {
      console.error('Error loading student details:', err);
    }
  };

  const openDetailsModal = (student: Student) => {
    setSelectedStudent(student);
    setShowDetailsModal(true);
    setActiveTab('overview');
    loadStudentDetails(student.id);
  };

  const getStatusStyles = (status: Student['status']) => {
    switch (status) {
      case 'excellent': return { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/30', border: 'border-emerald-100 dark:border-emerald-800', icon: Award };
      case 'good': return { text: 'text-blue-600 dark:text-blue-400', bg: 'bg-blue-50 dark:bg-blue-900/30', border: 'border-blue-100 dark:border-blue-800', icon: TrendingUp };
      case 'attention': return { text: 'text-amber-600 dark:text-amber-400', bg: 'bg-amber-50 dark:bg-amber-900/30', border: 'border-amber-100 dark:border-amber-800', icon: AlertCircle };
      default: return { text: 'text-text-muted', bg: 'bg-muted', border: 'border-border', icon: Info };
    }
  };

  const getStatColors = (color: string) => {
    switch (color) {
      case 'blue': return 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800';
      case 'emerald': return 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800';
      case 'purple': return 'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800';
      case 'orange': return 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800';
      default: return 'bg-muted text-text-muted border-border';
    }
  };

  const stats = [
    { label: 'Managed Learners', value: students.length, icon: Users, color: 'blue', trend: 'Academic' },
    { label: 'Peak Performance', value: students.filter(s => s.status === 'excellent').length, icon: Award, color: 'emerald', trend: 'Excellent' },
    { label: 'Priority Support', value: students.filter(s => s.status === 'attention').length, icon: AlertCircle, color: 'orange', trend: 'Attention' },
    { label: 'Avg. Proficiency', value: `${students.length ? Math.round(students.reduce((acc, s) => acc + s.score, 0) / students.length) : 0}%`, icon: BarChart3, color: 'purple', trend: 'Optimal' },
  ];

  const [showSocialModal, setShowSocialModal] = useState(false);
  const [socialStudent, setSocialStudent] = useState<any>(null);

  const openSocialDoc = (student: any) => {
    setSocialStudent(student);
    setShowSocialModal(true);
  };

  const filteredStudents = students.filter(student => {
    const matchesSearch = `${student.first_name} ${student.last_name} ${student.email} ${student.phone || ''}`
      .toLowerCase()
      .includes(searchQuery.toLowerCase());
    const matchesStatus = filterStatus === 'all' || student.status === filterStatus;
    const stateClassName = location.state?.class_name;
    const matchesClass = !stateClassName || student.course === stateClassName;
    return matchesSearch && matchesStatus && matchesClass;
  });

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Header Section */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize dark:text-white uppercase">Student Directory</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Faculty Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Learner Insights</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button
            type="button"
            onClick={() => {
              const headers = ['ID', 'Name', 'Email', 'Phone', 'Class', 'Status', 'Score', 'Progress', 'Attendance'];
              const rows = filteredStudents.map((s) => [
                s.id,
                `"${s.first_name} ${s.last_name}"`,
                s.email,
                s.phone,
                s.course,
                s.status,
                s.score,
                s.progress,
                s.attendance,
              ]);
              const csv = [headers.join(','), ...rows.map((r) => r.join(','))].join('\n');
              const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
              const url = URL.createObjectURL(blob);
              const link = document.createElement('a');
              link.href = url;
              link.setAttribute('download', `student-directory-${new Date().toISOString().slice(0, 10)}.csv`);
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              URL.revokeObjectURL(url);
            }}
            className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
          >
            <Download size={18} />
            Export Directory
          </button>
          <button
            type="button"
            onClick={() => navigate('/messages')}
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
          >
            <MessageSquare size={18} />
            Notification
          </button>
        </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 cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center ${getStatColors(stat.color)} 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>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">{stat.trend}</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Control Bar */}
      <div className="bg-card border border-border rounded-[2rem] p-2 shadow-sm flex flex-col lg:flex-row items-stretch lg:items-center gap-4">
        {/* Filter Tabs */}
        <div className="flex p-1 bg-muted/50 rounded-2xl flex-grow lg:flex-grow-0 min-w-0">
          {(['all', 'excellent', 'good', 'attention'] as const).map((status) => (
            <button
              key={status}
              onClick={() => setFilterStatus(status)}
              className={`
                flex-1 px-4 py-2.5 rounded-xl text-[0.7rem] font-black uppercase tracking-widest transition-all
                ${filterStatus === status 
                  ? 'bg-card text-primary shadow-sm ring-1 ring-border' 
                  : 'text-text-muted hover:text-text'}
              `}
            >
              {status}
            </button>
          ))}
        </div>

        {/* Search Bar */}
        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted group-focus-within:text-primary transition-colors" />
          <input 
            type="text" 
            className="w-full bg-muted/50 border border-border rounded-2xl pl-11 pr-4 py-3.5 text-sm font-medium focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text"
            placeholder="Search by learner name, email or assigned subject..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
        </div>

      </div>

      {/* Student Grid */}
      {loading ? (
        <div className="py-20 text-center">
          <div className="w-12 h-12 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">Loading students...</p>
        </div>
      ) : filteredStudents.length === 0 ? (
        <div className="py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
          <Users size={64} className="mx-auto text-text-muted/30 mb-6" />
          <h3 className="text-2xl font-black text-text mb-2">No Matching Records</h3>
          <p className="text-text-muted font-medium mb-8 max-w-sm mx-auto">Try adjusting your filters or search query to identify specific learners.</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
          {filteredStudents.map((student) => {
            const styles = getStatusStyles(student.status);
            return (
              <div key={student.id} className="bg-card rounded-[2.5rem] border border-border overflow-hidden hover:shadow-xl hover:shadow-blue-900/5 transition-all group flex flex-col">
                <div className="p-8 flex flex-col sm:flex-row gap-8">
                  {/* Profile & Identification */}
                  <div className="flex flex-col items-center sm:items-start gap-4">
                    <div className="relative group/avatar">
                        <div className="w-24 h-24 rounded-3xl bg-muted border border-border flex items-center justify-center text-3xl font-black text-primary shadow-inner overflow-hidden group-hover:scale-105 transition-transform">
                            <Avatar 
                                src={`https://api.dicebear.com/9.x/initials/svg?seed=${student.id}`} 
                                firstName={student.first_name} 
                                lastName={student.last_name} 
                                />
                        </div>
                        <div className={`absolute -bottom-2 -right-2 w-8 h-8 rounded-xl border-4 border-card flex items-center justify-center shadow-lg ${styles.bg} ${styles.text}`}>
                            <styles.icon size={14} strokeWidth={3} />
                        </div>
                    </div>
                    <div className="text-center sm:text-left">
                        <span className={`inline-flex px-2 py-0.5 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border mb-1 ${styles.bg} ${styles.text} ${styles.border}`}>
                            {student.status}
                        </span>
                        <h3 className="text-xl font-black text-text tracking-tight truncate max-w-[180px]">{student.first_name} {student.last_name}</h3>
                        <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest mt-0.5">UID-2024-{student.id.toString().padStart(3, '0')}</p>
                    </div>
                  </div>

                  {/* Performance Snapshot */}
                  <div className="flex-grow space-y-6">
                    <div className="grid grid-cols-3 gap-3">
                        {[
                            { label: 'Score', val: `${student.score}%`, color: 'blue' },
                            { label: 'Progress', val: `${student.progress}%`, color: 'emerald' },
                            { label: 'Attend', val: `${student.attendance}%`, color: 'purple' },
                        ].map(m => (
                            <div key={m.label} className="bg-muted/50 rounded-2xl p-3 border border-border text-center">
                                <p className="text-[0.55rem] font-black uppercase tracking-widest text-text-muted mb-1">{m.label}</p>
                                <p className={`text-lg font-black ${m.color === 'blue' ? 'text-blue-600 dark:text-blue-400' : m.color === 'emerald' ? 'text-emerald-600 dark:text-emerald-400' : 'text-purple-600 dark:text-purple-400'}`}>{m.val}</p>
                            </div>
                        ))}
                    </div>

                    <div className="space-y-4">
                        <div className="flex justify-between items-end">
                            <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted">{terms.subject}: <span className="text-primary">{student.course}</span></p>
                            <p className="text-[0.65rem] font-black text-text-muted uppercase tracking-tighter">
                                {student.assignmentsCompleted}/{student.totalAssignments} Tasks
                            </p>
                        </div>
                        <div className="w-full h-1.5 bg-muted rounded-full overflow-hidden p-0.5 shadow-inner">
                            <div 
                                className="h-full bg-primary rounded-full transition-all duration-1000"
                                style={{ width: `${student.progress}%` }}
                            />
                        </div>
                    </div>
                  </div>
                </div>

                {/* Footer Quick Actions */}
                <div className="px-8 py-6 bg-muted/50 border-t border-border flex items-center justify-between mt-auto shrink-0">
                    <div className="flex gap-2">
                        <a href={`mailto:${student.email}`} className="p-3 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm">
                            <Mail size={18} />
                        </a>
                        <a href={`tel:${student.phone}`} className="p-3 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm">
                            <Phone size={18} />
                        </a>
                        <button 
                            onClick={() => openSocialDoc(student)}
                            className="p-3 bg-card border border-border text-text-muted hover:text-primary hover:border-primary rounded-xl transition-all shadow-sm"
                            title="Social Document"
                        >
                            <Sparkles size={18} />
                        </button>
                    </div>
                    <button 
                        onClick={() => openDetailsModal(student)}
                        className="flex items-center gap-2 bg-[#002147] hover:bg-black text-white px-6 py-3 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest transition-all shadow-lg shadow-blue-900/10 active:scale-95 group/btn"
                    >
                        Detailed Audit
                        <ChevronRight size={14} className="group-hover/btn:translate-x-1 transition-transform" />
                    </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Social Document Modal */}
      {showSocialModal && socialStudent && (
        <StudentSocialDoc 
          student={socialStudent} 
          onClose={() => setShowSocialModal(false)} 
        />
      )}

      {/* Details Modal */}
      {showDetailsModal && selectedStudent && createPortal(
        <div className="fixed inset-0 bg-[#002147]/80 backdrop-blur-md z-[150] flex items-center justify-center p-4" onClick={() => setShowDetailsModal(false)}>
          <div className="bg-card rounded-[3rem] w-full max-w-3xl shadow-2xl overflow-hidden animate-in zoom-in-95 duration-200 max-h-[90vh] flex flex-col border border-border" onClick={(e) => e.stopPropagation()}>
            {/* Modal Header */}
            <div className="p-10 pb-8 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10 flex items-center gap-6">
                <div className="w-20 h-20 rounded-[1.5rem] bg-card border border-border shadow-xl overflow-hidden flex-shrink-0">
                    <Avatar 
                        src={`https://api.dicebear.com/9.x/initials/svg?seed=${selectedStudent.id}`} 
                        firstName={selectedStudent.first_name} 
                        lastName={selectedStudent.last_name} 
                    />
                </div>
                <div>
                    <h2 className="text-2xl font-black text-text tracking-tight uppercase">{selectedStudent.first_name} {selectedStudent.last_name}</h2>
                    <div className="flex items-center gap-3 mt-1">
                        <span className="text-[0.65rem] font-black text-primary uppercase tracking-[3px]">{selectedStudent.course}</span>
                        <div className="w-1 h-1 rounded-full bg-border"></div>
                        <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">ID: EDU-{selectedStudent.id}</span>
                    </div>
                </div>
              </div>
              <button
                onClick={() => setShowDetailsModal(false)}
                className="relative z-10 w-12 h-12 flex items-center justify-center rounded-2xl bg-card border border-border text-text-muted hover:text-rose-500 transition-all shadow-sm"
              >
                <X size={24} />
              </button>
            </div>

            {/* Modal Navigation */}
            <div className="px-10 py-2 bg-card border-b border-border flex gap-8 shrink-0 overflow-x-auto">
                {(['overview', 'social', 'grades', 'attendance', 'assignments'] as const).map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        className={`py-4 text-[0.65rem] font-black uppercase tracking-[3px] transition-all relative whitespace-nowrap ${activeTab === tab ? 'text-primary' : 'text-text-muted hover:text-text'}`}
                    >
                        {tab === 'social' && <Brain size={11} className="inline mr-1.5 -mt-0.5" />}
                        {tab}
                        {activeTab === tab && <div className="absolute bottom-0 left-0 right-0 h-1 bg-primary rounded-full"></div>}
                    </button>
                ))}
            </div>

            {/* Modal Body */}
            <div className="p-10 overflow-y-auto flex-1 custom-scrollbar">
                {activeTab === 'overview' && (
                    <div className="space-y-8 animate-in fade-in duration-500">
                        <div className="grid grid-cols-2 gap-6">
                            <div className="p-8 bg-blue-50/10 dark:bg-blue-900/10 border border-blue-100/20 rounded-3xl relative group overflow-hidden">
                                <div className="absolute right-0 top-0 w-24 h-24 bg-blue-500/5 rounded-bl-full"></div>
                                <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-blue-600 dark:text-blue-400 mb-4">Performance</p>
                                <div className="flex items-center gap-4">
                                    <div className="w-14 h-14 rounded-2xl bg-card flex items-center justify-center text-blue-600 dark:text-blue-400 shadow-sm border border-border text-2xl font-black">{selectedStudent.score}%</div>
                                    <p className="text-sm font-medium text-text-secondary leading-relaxed max-w-[200px]">Learner is currently in the top <span className="text-primary font-bold">12%</span> of this subject division.</p>
                                </div>
                            </div>
                            <div className="p-8 bg-emerald-50/10 dark:bg-emerald-900/10 border border-emerald-100/20 rounded-3xl relative group overflow-hidden">
                                <div className="absolute right-0 top-0 w-24 h-24 bg-emerald-500/5 rounded-bl-full"></div>
                                <p className="text-[0.6rem] font-black uppercase tracking-[2px] text-emerald-600 dark:text-emerald-400 mb-4">System Progress</p>
                                <div className="flex items-center gap-4">
                                    <div className="w-14 h-14 rounded-2xl bg-card flex items-center justify-center text-emerald-600 dark:text-emerald-400 shadow-sm border border-border text-2xl font-black">{selectedStudent.progress}%</div>
                                    <p className="text-sm font-medium text-text-secondary leading-relaxed max-w-[200px]">Curriculum completion is <span className="text-emerald-600 font-bold">Optimal</span> for this period.</p>
                                </div>
                            </div>
                        </div>

                        <div className="bg-muted/50 border border-border rounded-3xl p-8">
                            <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted mb-6">Contact Channels</h4>
                            <div className="space-y-4">
                                <div className="flex items-center gap-4 p-4 bg-card rounded-2xl border border-border">
                                    <div className="w-10 h-10 rounded-xl bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 flex items-center justify-center"><Mail size={18} /></div>
                                    <div>
                                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Email Identity</p>
                                        <p className="text-sm font-bold text-text">{selectedStudent.email}</p>
                                    </div>
                                </div>
                                <div className="flex items-center gap-4 p-4 bg-card rounded-2xl border border-border">
                                    <div className="w-10 h-10 rounded-xl bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 flex items-center justify-center"><Phone size={18} /></div>
                                    <div>
                                        <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Direct Line</p>
                                        <p className="text-sm font-bold text-text">{selectedStudent.phone}</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {activeTab === 'social' && (
                    <SocialProfileTab
                        doc={studentSocialDoc}
                        loading={socialLoading}
                        onEdit={() => {
                            setSocialStudent(selectedStudent);
                            setShowSocialModal(true);
                        }}
                    />
                )}

                {activeTab === 'grades' && (
                    <div className="animate-in fade-in duration-500">
                        <div className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
                            <table className="w-full text-left">
                                <thead>
                                    <tr className="bg-muted/80 border-b border-border">
                                        <th className="px-6 py-4 text-[0.6rem] font-black text-primary uppercase tracking-widest">Assessment</th>
                                        <th className="px-6 py-4 text-[0.6rem] font-black text-primary uppercase tracking-widest text-center">Score</th>
                                        <th className="px-6 py-4 text-[0.6rem] font-black text-primary uppercase tracking-widest text-right">Date Recorded</th>
                                    </tr>
                                </thead>
                                <tbody className="divide-y divide-border">
                                    {studentGrades.length === 0 ? (
                                        <tr><td colSpan={3} className="px-6 py-10 text-center text-text-muted font-bold italic">No grades recorded for this period.</td></tr>
                                    ) : studentGrades.map((grade, i) => (
                                        <tr key={i} className="hover:bg-muted/50 transition-colors">
                                            <td className="px-6 py-4">
                                                <p className="text-sm font-bold text-text">{grade.assignment}</p>
                                                 <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-tighter">Current Term</p>
                                            </td>
                                            <td className="px-6 py-4 text-center">
                                                <span className={`px-3 py-1 rounded-full text-[0.6rem] font-black uppercase tracking-widest border ${
                                                    grade.score >= grade.maxScore * 0.8 ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 'bg-blue-50 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800'
                                                }`}>
                                                    {grade.score}/{grade.maxScore}
                                                </span>
                                            </td>
                                            <td className="px-6 py-4 text-right">
                                                <p className="text-[0.7rem] font-bold text-text-muted font-mono">{grade.date}</p>
                                            </td>
                                        </tr>
                                    ))}
                                </tbody>
                            </table>
                        </div>
                    </div>
                )}

                {activeTab === 'attendance' && (
                    <div className="space-y-8 animate-in fade-in duration-500">
                        <div className="grid grid-cols-7 gap-3 text-text">
                            {studentAttendance.length === 0 ? (
                                <div className="col-span-7 py-10 text-center text-text-muted font-bold italic">No attendance history available.</div>
                            ) : studentAttendance.map((record, i) => (
                                <div key={i} className={`p-5 text-center rounded-[1.5rem] border transition-all ${
                                    record.status === 'present' ? 'bg-emerald-50/10 dark:bg-emerald-900/10 border-emerald-100/20 dark:border-emerald-800/20' : 'bg-rose-50/10 dark:bg-rose-900/10 border-rose-100/20 dark:border-rose-800/20'
                                }`}>
                                    <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest mb-3">{record.date.split('-')[2]}</p>
                                    <div className="flex justify-center">
                                        {record.status === 'present' ? <CheckCircle2 size={24} className="text-emerald-500" /> : <XCircle size={24} className="text-rose-500" />}
                                    </div>
                                </div>
                            ))}
                        </div>
                        <div className="bg-muted/50 p-6 rounded-3xl border border-border flex items-center justify-center gap-8">
                             {[
                                { icon: CheckCircle2, label: 'Present', color: 'text-emerald-500' },
                                { icon: XCircle, label: 'Absent', color: 'text-rose-500' },
                                { icon: AlertCircle, label: 'Excused', color: 'text-amber-500' },
                             ].map(l => (
                                <div key={l.label} className="flex items-center gap-2">
                                    <l.icon size={16} className={l.color} />
                                    <span className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted">{l.label}</span>
                                </div>
                             ))}
                        </div>
                    </div>
                )}

                {activeTab === 'assignments' && (
                    <div className="animate-in fade-in duration-500">
                        <div className="space-y-3">
                            {studentAssignments.length === 0 ? (
                                <div className="py-10 text-center text-text-muted font-bold italic">No assignments pending or submitted.</div>
                            ) : studentAssignments.map((assignment, i) => (
                                <div key={i} className="flex items-center justify-between p-6 bg-card border border-border rounded-[2rem] hover:border-primary transition-all group">
                                    <div className="flex items-center gap-4">
                                        <div className="w-12 h-12 rounded-2xl bg-muted flex items-center justify-center text-primary border border-border shadow-inner group-hover:scale-110 transition-transform">
                                            <FileText size={22} />
                                        </div>
                                        <div>
                                            <p className="text-[0.95rem] font-black text-text tracking-tight">{assignment.title}</p>
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-[2px] mt-0.5">Target: {assignment.dueDate}</p>
                                        </div>
                                    </div>
                                    <div className="flex items-center gap-4">
                                        {assignment.grade && (
                                            <span className="text-sm font-black text-primary bg-primary/5 px-3 py-1 rounded-xl border border-primary/10">{assignment.grade}</span>
                                        )}
                                        <span className={`px-3 py-1.5 rounded-xl text-[0.6rem] font-black uppercase tracking-widest border ${
                                            assignment.status === 'submitted' ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 'bg-amber-50 dark:bg-amber-900/30 text-amber-600 dark:text-amber-400 border-amber-100 dark:border-amber-800'
                                        }`}>
                                            {assignment.status}
                                        </span>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </div>

            {/* Modal Footer */}
            <div className="p-10 border-t border-border bg-muted/50 shrink-0 flex items-center justify-between">
                <div className="flex gap-4">
                   <button
                     type="button"
                     onClick={() => window.print()}
                     className="px-6 py-4 bg-card border border-border text-text-muted rounded-2xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-muted/50 transition-all flex items-center gap-2"
                   >
                        <Printer size={16} /> Export Transcript
                   </button>
                </div>
                <button
                    onClick={() => setShowDetailsModal(false)}
                    className="px-12 py-4 bg-primary hover:bg-primary-dark text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-xl active:scale-95"
                >
                    Close Profile
                </button>
            </div>
          </div>
        </div>
      ,
        document.body
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
        .dark .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.1); }
      `}</style>
    </div>
  );
}

// Helper icon not in main list
const Printer = ({ size, className }: any) => <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}><polyline points="6 9 6 2 18 2 18 9"></polyline><path d="M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2"></path><rect x="6" y="14" width="12" height="8"></rect></svg>;

// =========================================================================
// Social Profile tab — read-only glanceable view of the student_social_docs
// row, designed so a new teacher can understand the child quickly at year
// handover. Read-only here; clicking "Edit Document" opens the existing
// StudentSocialDoc modal for full CRUD.
// =========================================================================

interface SocialProfileTabProps {
  doc: any | null;
  loading: boolean;
  onEdit: () => void;
}

function SocialProfileTab({ doc, loading, onEdit }: SocialProfileTabProps) {
  if (loading) {
    return (
      <div className="animate-in fade-in duration-500 py-16 flex flex-col items-center justify-center gap-3">
        <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin" />
        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted">Loading social profile...</p>
      </div>
    );
  }

  if (!doc || doc._empty) {
    return (
      <div className="animate-in fade-in duration-500 py-12 text-center bg-muted/30 border-2 border-dashed border-border rounded-[2rem]">
        <div className="w-16 h-16 rounded-2xl bg-card border border-border mx-auto flex items-center justify-center text-text-muted mb-4">
          <Brain size={28} />
        </div>
        <h4 className="text-xl font-black text-text mb-2">No social profile yet</h4>
        <p className="text-sm text-text-muted font-medium max-w-sm mx-auto mb-6">
          Capture this student's learner style, home environment, and pastoral notes so the next teacher has context on day one.
        </p>
        <button
          onClick={onEdit}
          className="px-6 py-3 bg-primary hover:bg-primary/90 text-white rounded-2xl text-[0.7rem] font-black uppercase tracking-widest transition-all shadow-lg shadow-blue-900/20 inline-flex items-center gap-2"
        >
          <Pencil size={16} />
          Create Social Profile
        </button>
      </div>
    );
  }

  return (
    <div className="animate-in fade-in duration-500 space-y-6">
      {/* Header with Edit button */}
      <div className="flex items-center justify-between gap-4 flex-wrap">
        <div>
          <h3 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">
            Holistic Learner Profile
          </h3>
          <p className="text-xs text-text-muted mt-1">
            Year-over-year context: carried forward automatically when the student moves up.
          </p>
        </div>
        <button
          onClick={onEdit}
          className="px-5 py-2.5 bg-card border border-border hover:bg-muted/50 text-text rounded-2xl text-[0.7rem] font-black uppercase tracking-widest transition-all inline-flex items-center gap-2 shadow-sm"
        >
          <Pencil size={14} />
          Edit Document
        </button>
      </div>

      {/* Quick-glance stats row */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <StatCard
          icon={<Lightbulb size={16} />}
          label="Learner Type"
          value={doc.learner_type}
          color="amber"
        />
        <StatCard
          icon={<Users size={16} />}
          label="Family Size"
          value={doc.family_size != null ? `${doc.family_size} members` : null}
          color="emerald"
        />
        <StatCard
          icon={<Home size={16} />}
          label="Parents At Home"
          value={doc.parents_available}
          color="blue"
        />
        <StatCard
          icon={<Heart size={16} />}
          label="Medical Notes"
          value={doc.medical_notes ? 'On file' : null}
          color="rose"
        />
      </div>

      {/* Detailed cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <ProfileCard
          icon={<BookOpen size={16} />}
          color="amber"
          title="Past Behavior"
          text={doc.past_behavior}
        />
        <ProfileCard
          icon={<Home size={16} />}
          color="emerald"
          title="Home Environment & Setup"
          text={doc.home_environment}
        />
        <ProfileCard
          icon={<Sparkles size={16} />}
          color="blue"
          title="Social Strengths"
          text={doc.social_strengths}
        />
        <ProfileCard
          icon={<AlertCircle size={16} />}
          color="rose"
          title="Social Challenges"
          text={doc.social_challenges}
        />
        <ProfileCard
          icon={<Heart size={16} />}
          color="rose"
          title="Medical Notes (Confidential)"
          text={doc.medical_notes}
        />
        <ProfileCard
          icon={<Sparkles size={16} />}
          color="blue"
          title="Interests & Hobbies"
          text={doc.interests}
        />
      </div>

      {doc.other_data && (
        <div className="p-6 bg-muted/30 border border-border rounded-2xl">
          <div className="flex items-center gap-2 mb-3">
            <Info size={14} className="text-text-muted" />
            <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">
              Additional Notes
            </h4>
          </div>
          <p className="text-sm text-text-secondary whitespace-pre-wrap leading-relaxed">{doc.other_data}</p>
        </div>
      )}

      <div className="text-[0.6rem] text-text-muted/70 italic flex items-center gap-1.5">
        <Clock size={11} />
        Last updated {doc.updated_at || doc.created_at || 'unknown'}
        {doc.updated_by && ` · by user #${doc.updated_by}`}
      </div>
    </div>
  );
}

function StatCard({ icon, label, value, color }: { icon: React.ReactNode; label: string; value: string | null; color: 'amber' | 'emerald' | 'blue' | 'rose' }) {
  const palette = {
    amber:   { text: 'text-amber-600 dark:text-amber-400',   bg: 'bg-amber-50 dark:bg-amber-900/20 border-amber-100 dark:border-amber-800' },
    emerald: { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50 dark:bg-emerald-900/20 border-emerald-100 dark:border-emerald-800' },
    blue:    { text: 'text-blue-600 dark:text-blue-400',       bg: 'bg-blue-50 dark:bg-blue-900/20 border-blue-100 dark:border-blue-800' },
    rose:    { text: 'text-rose-600 dark:text-rose-400',       bg: 'bg-rose-50 dark:bg-rose-900/20 border-rose-100 dark:border-rose-800' },
  }[color];
  return (
    <div className={`p-4 border rounded-2xl ${palette.bg}`}>
      <div className={`flex items-center gap-2 mb-1.5 ${palette.text}`}>
        {icon}
        <span className="text-[0.55rem] font-black uppercase tracking-[2px]">{label}</span>
      </div>
      <p className={`text-sm font-black ${value ? palette.text : 'text-text-muted/50 italic'}`}>
        {value || 'Not recorded'}
      </p>
    </div>
  );
}

function ProfileCard({ icon, color, title, text }: { icon: React.ReactNode; color: 'amber' | 'emerald' | 'blue' | 'rose'; title: string; text: string | null }) {
  const palette = {
    amber:   { text: 'text-amber-600 dark:text-amber-400',   bg: 'bg-amber-50/10 dark:bg-amber-900/10 border-amber-100/20' },
    emerald: { text: 'text-emerald-600 dark:text-emerald-400', bg: 'bg-emerald-50/10 dark:bg-emerald-900/10 border-emerald-100/20' },
    blue:    { text: 'text-blue-600 dark:text-blue-400',       bg: 'bg-blue-50/10 dark:bg-blue-900/10 border-blue-100/20' },
    rose:    { text: 'text-rose-600 dark:text-rose-400',       bg: 'bg-rose-50/10 dark:bg-rose-900/10 border-rose-100/20' },
  }[color];
  return (
    <div className={`p-5 border rounded-2xl ${palette.bg}`}>
      <div className={`flex items-center gap-2 mb-2 ${palette.text}`}>
        {icon}
        <h4 className={`text-[0.6rem] font-black uppercase tracking-[2px] ${palette.text}`}>
          {title}
        </h4>
      </div>
      {text ? (
        <p className="text-sm text-text-secondary whitespace-pre-wrap leading-relaxed">{text}</p>
      ) : (
        <p className="text-sm text-text-muted/60 italic">Not recorded</p>
      )}
    </div>
  );
}
