import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import api, { useAuthStore } from '../../store/auth';
import {
  Calendar as CalendarIcon, Clock, MapPin, User,
  ChevronLeft, ChevronRight, BookOpen, CheckCircle2,
  XCircle, AlertCircle, ChevronDown, Search, X,
  Download, Filter, Sparkles, School,
  Users, Bell, Trash2, Edit2, Info, MoreHorizontal,
  CalendarDays, Video, Heart, Award,
  GraduationCap, TrendingUp, ShieldCheck, Activity,
  UserCircle
} from 'lucide-react';

interface ScheduleItem {
  id: number;
  subject_name: string;
  class_name?: string;
  instructor_name?: string;
  room?: string;
  start_time?: string;
  end_time?: string;
  status?: 'upcoming' | 'ongoing' | 'completed' | 'cancelled';
  color?: string;
  description?: string;
  type?: string;
  location?: string;
  venue?: string;
}

interface Student {
  id: number;
  first_name: string;
  last_name: string;
  class?: string;
  grade?: string;
  avatar?: string;
}

interface CalendarEvent {
  id?: number | string;
  title?: string;
  subject_name?: string;
  description?: string;
  start_time?: string;
  end_time?: string;
  start?: string;
  end?: string;
  venue?: string;
  location?: string;
  room?: string;
  class_name?: string;
  instructor_name?: string;
  created_by_name?: string;
  event_type?: string;
  type?: string;
  [key: string]: unknown;
}

interface GradeEntry {
  period: string;
  avg: number;
  math?: number;
  english?: number;
  science?: number;
}

interface SubjectPerformance {
  subject: string;
  currentGrade: number;
  previousGrade: number;
  trend: 'up' | 'down' | 'stable';
  rank: number;
  totalStudents: number;
}

// Literal lookup for the bento-stats tile colors. Tailwind's JIT cannot
// scan template-built class names like `bg-${color}-50`, so we resolve them
// at module load. Add a color here when introducing new stat tiles.
type TileColor = 'blue' | 'emerald' | 'orange' | 'purple';
const TILE_THEME: Record<TileColor, { bg: string; text: string; border: string }> = {
  blue:    { bg: 'bg-blue-50 dark:bg-blue-950/30',       text: 'text-blue-600 dark:text-blue-400',       border: 'border-blue-100 dark:border-blue-900/30' },
  emerald: { bg: 'bg-emerald-50 dark:bg-emerald-950/30', text: 'text-emerald-600 dark:text-emerald-400', border: 'border-emerald-100 dark:border-emerald-900/30' },
  orange:  { bg: 'bg-orange-50 dark:bg-orange-950/30',   text: 'text-orange-600 dark:text-orange-400',   border: 'border-orange-100 dark:border-orange-900/30' },
  purple:  { bg: 'bg-purple-50 dark:bg-purple-950/30',   text: 'text-purple-600 dark:text-purple-400',   border: 'border-purple-100 dark:border-purple-900/30' },
};

export default function ParentCalendar() {
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const [selectedDate, setSelectedDate] = useState(new Date());
  const [schedule, setSchedule] = useState<ScheduleItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [children, setChildren] = useState<Student[]>([]);
  const [selectedChild, setSelectedChild] = useState<number | null>(null);
  const [showChildPicker, setShowChildPicker] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // Load children
  useEffect(() => {
    api.get('/users/children').then(res => {
      setChildren(res.data);
      if (res.data.length > 0) {
        setSelectedChild(res.data[0].id);
      }
    }).catch(err => {
      console.error('Error loading children:', err);
      setLoading(false);
    });
  }, []);

  // Load calendar events for the selected date
  useEffect(() => {
    // No selected child yet — wait for the children-load effect to populate
    // selectedChild so we don't fire a request with student_id=null.
    if (!selectedChild) {
      setLoading(false);
      setSchedule([]);
      return;
    }
    let cancelled = false;
    setLoading(true);

    const dateKey = selectedDate.toISOString().split('T')[0];

    api.get('/calendar', {
      params: {
        date: dateKey,
        student_id: selectedChild,
      },
    })
      .then(res => {
        if (cancelled) return;

        const payload = res.data as { events?: CalendarEvent[] | Record<string, CalendarEvent[]> } | CalendarEvent[];
        let rawEvents: CalendarEvent[] = [];

        if (payload && Array.isArray(payload.events)) {
          rawEvents = payload.events;
        } else if (payload && payload.events && typeof payload.events === 'object') {
          rawEvents = (payload.events as Record<string, CalendarEvent[]>)[dateKey] || [];
        } else if (Array.isArray(payload)) {
          rawEvents = payload;
        }

        const mapped: ScheduleItem[] = rawEvents.map((ev, idx) => ({
          id: ev.id ?? idx + 1,
          subject_name: ev.title ?? ev.subject_name ?? 'Untitled Event',
          class_name: ev.class_name,
          instructor_name: ev.instructor_name ?? ev.created_by_name,
          room: ev.room ?? ev.venue ?? ev.location ?? '',
          venue: ev.venue,
          location: ev.location,
          start_time: ev.start_time ?? ev.start ?? '00:00',
          end_time: ev.end_time ?? ev.end ?? '23:59',
          status: 'upcoming',
          color: ['blue', 'emerald', 'orange', 'purple', 'rose', 'indigo'][idx % 6],
          description: ev.description,
          type: ev.event_type ?? ev.type,
        }));

        setSchedule(mapped);
        setLoading(false);
      })
      .catch(err => {
        if (cancelled) return;
        console.error('Error loading calendar:', err);
        setSchedule([]);
        setLoading(false);
      });

    return () => {
      cancelled = true;
    };
  }, [selectedDate, selectedChild]);

  const navigateDate = (direction: number) => {
    const newDate = new Date(selectedDate);
    newDate.setDate(newDate.getDate() + direction);
    setSelectedDate(newDate);
  };

  const getStatusStyles = (status: ScheduleItem['status']) => {
    switch (status) {
      case 'ongoing': return { bg: 'bg-emerald-50 dark:bg-emerald-950/30', text: 'text-emerald-600 dark:text-emerald-400', border: 'border-emerald-100 dark:border-emerald-900/30', icon: Activity, label: 'Live' };
      case 'completed': return { bg: 'bg-primary/10', text: 'text-primary', border: 'border-primary/20', icon: CheckCircle2, label: 'Logged' };
      case 'cancelled': return { bg: 'bg-rose-50 dark:bg-rose-950/30', text: 'text-rose-600 dark:text-rose-400', border: 'border-rose-100 dark:border-rose-900/30', icon: XCircle, label: 'Cancelled' };
      default: return { bg: 'bg-muted/50', text: 'text-text-muted', border: 'border-border', icon: Clock, label: 'Pending' };
    }
  };

  const formatTime = (time: string) => {
    if (!time) return '';
    const [hours, minutes] = time.split(':').map(Number);
    const period = hours >= 12 ? 'PM' : 'AM';
    const displayHours = hours > 12 ? hours - 12 : hours === 0 ? 12 : hours;
    return `${displayHours}:${minutes.toString().padStart(2, '0')} ${period}`;
  };

  const selectedChildData = children.find(c => c.id === selectedChild) || (children.length > 0 ? children[0] : { first_name: 'Learner', last_name: '', grade: 'N/A' });
  const childDisplayName = selectedChildData.first_name + ' ' + selectedChildData.last_name;

  const stats = [
    { label: 'Academic Periods', value: schedule.length, icon: BookOpen, color: 'blue', trend: 'Today' },
    { label: 'Weekly Mastery', value: '92%', icon: Award, color: 'emerald', trend: 'Average' },
    { label: 'Intel Alerts', value: '0', icon: Bell, color: 'orange', trend: 'System' },
    { label: 'Learning Pulse', value: 'Stable', icon: ShieldCheck, color: 'purple', trend: 'Verified' },
  ];

  // CSV export helper for schedule
  const handleExportSchedule = () => {
    const rows = [
      ['Date', 'Subject', 'Class', 'Instructor', 'Room', 'Start', 'End', 'Status'],
      ...schedule.map(s => [
        selectedDate.toISOString().split('T')[0],
        s.subject_name ?? '',
        s.class_name ?? '',
        s.instructor_name ?? '',
        s.room ?? '',
        s.start_time ?? '',
        s.end_time ?? '',
        s.status ?? '',
      ]),
    ];
    const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(',')).join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `timetable-${childDisplayName.replace(/\s+/g, '-')}-${selectedDate.toISOString().split('T')[0]}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <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">Academic Timetable</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Guardian Portal</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Daily Schedule Intelligence</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button onClick={handleExportSchedule} 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 transition-all shadow-sm active:scale-95">
            <Download size={18} />
            Export Schedule
          </button>
        </div>
      </div>

      {/* Bento Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => {
          const theme = TILE_THEME[stat.color as TileColor] ?? TILE_THEME.blue;
          return (
            <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 ${theme.bg} ${theme.text} ${theme.border} group-hover:scale-110 transition-transform`}>
                <stat.icon size={22} />
              </div>
              <div>
                <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
                <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>

      {/* 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">
        {/* Child Picker */}
        <div className="relative shrink-0">
            <button
                onClick={() => setShowChildPicker(!showChildPicker)}
                className="flex items-center gap-3 px-6 py-3 bg-muted/50 rounded-2xl text-text font-black text-[0.7rem] uppercase tracking-widest transition-all hover:bg-muted min-w-[220px]"
            >
                <div className="w-8 h-8 rounded-lg bg-primary flex items-center justify-center text-white text-xs font-black shadow-lg">
                    {selectedChildData.first_name?.[0] || 'L'}
                </div>
                <span>{childDisplayName}</span>
                <ChevronDown size={16} className={`text-text-muted transition-transform ${showChildPicker ? 'rotate-180' : ''}`} />
            </button>

            {showChildPicker && (
                <div className="absolute left-0 top-full mt-3 w-64 bg-card border border-border rounded-2xl shadow-2xl z-[100] p-2 animate-in zoom-in-95 duration-200">
                    <p className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted px-4 py-2 border-b border-border/50 mb-1">Select Learner Registry</p>
                    {children.map(c => (
                        <button
                            key={c.id}
                            onClick={() => { setSelectedChild(c.id); setShowChildPicker(false); }}
                            className={`w-full flex items-center gap-3 p-3 rounded-xl transition-all ${selectedChild === c.id ? 'bg-primary/10' : 'hover:bg-muted'}`}
                        >
                            <div className="w-10 h-10 rounded-xl bg-card border border-border flex items-center justify-center text-primary text-xs font-black shadow-sm">
                                {c.first_name?.[0] || 'L'}
                            </div>
                            <div className="text-left">
                                <p className="text-sm font-bold text-text">{c.first_name} {c.last_name}</p>
                                <p className="text-[0.6rem] text-text-muted font-bold uppercase">{c.grade || 'Grade 10'}</p>
                            </div>
                        </button>
                    ))}
                </div>
            )}
        </div>

        {/* Date Navigator */}
        <div className="flex items-center gap-2 bg-muted/50 rounded-2xl p-1 shrink-0">
            <button onClick={() => navigateDate(-1)} className="p-3 bg-card rounded-xl shadow-sm border border-border text-text hover:bg-muted transition-all"><ChevronLeft size={18} /></button>
            <div className="px-6 flex flex-col items-center min-w-[180px]">
                <span className="text-[0.6rem] font-black uppercase tracking-widest text-text-muted">{selectedDate.toLocaleDateString('en-US', { month: 'long', year: 'numeric' })}</span>
                <span className="text-sm font-black text-text">{selectedDate.toLocaleDateString('en-US', { day: 'numeric', weekday: 'long' })}</span>
            </div>
            <button onClick={() => navigateDate(1)} className="p-3 bg-card rounded-xl shadow-sm border border-border text-text hover:bg-muted transition-all"><ChevronRight size={18} /></button>
        </div>

        <div className="relative group flex-1">
          <Search size={18} className="absolute left-4 top-1/2 -translate-y-1/2 text-text-muted/30 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"
            placeholder="Search subjects or instructors..."
            value={searchQuery}
            onChange={e => setSearchQuery(e.target.value)}
          />
        </div>
      </div>

      {/* Main Schedule Grid */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">

        {/* Timeline View (8/12) */}
        <div className="lg:col-span-8 space-y-6">
            <div className="flex items-center justify-between px-2">
                <h3 className="text-lg font-black text-text uppercase tracking-tight">Daily Schedule</h3>
                <div className="flex gap-2">
                    <button onClick={() => setSelectedDate(new Date())} className="px-4 py-2 bg-primary text-white rounded-lg text-[0.6rem] font-black uppercase tracking-widest shadow-lg shadow-blue-900/10">Return to Today</button>
                    <span className="px-4 py-2 bg-muted/50 text-text-muted border border-border rounded-lg text-[0.6rem] font-black uppercase tracking-widest">{schedule.length} Registered Slots</span>
                </div>
            </div>

            <div className="relative pl-12 space-y-8">
                {/* Visual Line */}
                <div className="absolute left-[23px] top-4 bottom-4 w-0.5 bg-muted"></div>

                {loading ? (
                    <div className="py-20 text-center">
                        <div className="w-8 h-8 border-3 border-primary border-t-transparent rounded-full animate-spin mx-auto"></div>
                    </div>
                ) : schedule.length === 0 ? (
                    <div className="py-24 text-center bg-card border border-dashed border-border rounded-[2.5rem] opacity-60">
                        <CalendarIcon size={64} className="mx-auto text-text-muted/10 mb-6" />
                        <p className="text-text-muted font-bold uppercase tracking-widest text-xs italic">System Idle: No Academic Transmissions for this Date</p>
                    </div>
                ) : schedule.map((item) => {
                    const styles = getStatusStyles(item.status ?? 'upcoming');
                    return (
                        <div key={item.id} className="relative group">
                            {/* Dot */}
                            <div className={`absolute left-[-35px] top-6 w-3 h-3 rounded-full border-2 border-white dark:border-slate-900 shadow-md z-10 transition-all group-hover:scale-125 ${styles.bg.includes('primary') ? 'bg-primary' : styles.bg.replace('50', '500')}`}></div>

                            <div className="bg-card border border-border rounded-[2.5rem] p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group relative overflow-hidden flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
                                <div className="absolute top-0 right-0 w-32 h-32 bg-muted/50 rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-primary/10 transition-colors"></div>

                                <div className="flex items-start gap-6 relative z-10">
                                    <div className={`w-14 h-14 rounded-2xl ${styles.bg} ${styles.text} border ${styles.border} flex items-center justify-center group-hover:rotate-6 transition-transform shadow-sm`}>
                                        <BookOpen size={24} />
                                    </div>
                                    <div>
                                        <div className="flex items-center gap-3 mb-1">
                                            <h4 className="text-xl font-black text-text group-hover:text-primary transition-colors">{item.subject_name}</h4>
                                            <span className={`px-2 py-0.5 rounded-lg text-[0.55rem] font-black uppercase tracking-widest border ${styles.bg} ${styles.text} ${styles.border}`}>
                                                {styles.label}
                                            </span>
                                        </div>
                                        <p className="text-[0.85rem] text-text-muted font-medium leading-relaxed max-w-md line-clamp-1">{item.description || `Core curriculum session for ${selectedChildData.grade ?? 'this term'}.`}</p>

                                        <div className="flex flex-wrap items-center gap-6 mt-4">
                                            {(item.start_time || item.end_time) && (
                                                <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                                    <Clock size={14} className="text-text-muted/30" />
                                                    {item.start_time ? formatTime(item.start_time) : ''}{item.end_time ? ` - ${formatTime(item.end_time)}` : ''}
                                                </div>
                                            )}
                                            {item.room && (
                                                <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                                    <MapPin size={14} className="text-text-muted/30" />
                                                    {item.room}
                                                </div>
                                            )}
                                            {item.instructor_name && (
                                                <div className="flex items-center gap-2 text-[0.7rem] font-bold text-text-muted uppercase tracking-widest">
                                                    <UserCircle size={14} className="text-text-muted/30" />
                                                    {item.instructor_name}
                                                </div>
                                            )}
                                        </div>
                                    </div>
                                </div>

                                <div className="flex items-center gap-2 self-end md:self-center opacity-0 group-hover:opacity-100 transition-opacity relative z-10">
                                    <button onClick={() => navigate('/messages')} className="flex items-center gap-2 bg-text 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">
                                        View Details
                                        <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
                                    </button>
                                </div>
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>

        {/* Right Sidebar (4/12) */}
        <div className="lg:col-span-4 space-y-8">
            {/* Activity Log (Mini Calendar) */}
            <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
                <div className="flex items-center justify-between mb-8">
                    <h4 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Activity Log</h4>
                    <MoreHorizontal size={18} className="text-text-muted/30" />
                </div>
                <div className="space-y-4">
                    <div className="bg-muted/50 rounded-3xl p-6 border border-border text-center relative overflow-hidden group">
                        <div className="absolute top-0 right-0 w-24 h-24 bg-primary opacity-[0.02] rounded-bl-full"></div>
                        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-1">{selectedDate.toLocaleDateString('en-US', { weekday: 'long' })}</p>
                        <h2 className="text-6xl font-black text-text tracking-tighter">{selectedDate.getDate()}</h2>
                        <p className="text-sm font-black text-primary uppercase tracking-[4px] mt-2">{selectedDate.toLocaleDateString('en-US', { month: 'long' })}</p>
                    </div>
                    <div className="grid grid-cols-7 gap-2 text-center">
                        {['M','T','W','T','F','S','S'].map((d, i) => (
                            <div key={i} className="text-[0.6rem] font-black text-text-muted/30 uppercase">{d}</div>
                        ))}
                        {Array.from({length: 31}).map((_, i) => {
                            const date = new Date(selectedDate.getFullYear(), selectedDate.getMonth(), i + 1);
                            const isSelected = date.toDateString() === selectedDate.toDateString();
                            const isToday = date.toDateString() === new Date().toDateString();
                            return (
                                <div
                                    key={i}
                                    onClick={() => setSelectedDate(date)}
                                    className={`aspect-square flex items-center justify-center text-[0.7rem] font-bold rounded-lg transition-all cursor-pointer ${isSelected ? 'bg-primary text-white shadow-lg' : isToday ? 'bg-primary/10 text-primary' : 'text-text-muted hover:bg-muted'}`}
                                >
                                    {i + 1}
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>

            {/* AI Assistant Card */}
            <div className="bg-slate-950 dark:bg-card-elevated rounded-[2.5rem] p-10 text-white shadow-2xl relative overflow-hidden group">
                <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:rotate-12 transition-transform duration-700">
                    <Sparkles size={200} strokeWidth={1} />
                </div>
                <div className="relative z-10">
                    <div className="flex items-center gap-3 mb-6">
                        <div className="p-2.5 bg-white/10 rounded-xl backdrop-blur-md text-blue-400">
                            <GraduationCap size={20} />
                        </div>
                        <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-white/40">Helpful Note</span>
                    </div>
                    <h4 className="text-xl font-black mb-3 leading-tight tracking-tight">{selectedChildData.first_name}'s schedule is finalized.</h4>
                    <p className="text-sm font-medium text-blue-50/70 leading-relaxed mb-8">
                        The upcoming <span className="text-white font-black">Mathematics</span> session is a critical module focusing on Advanced Pure Algebra.
                    </p>
                    <button onClick={() => navigate('/academic-progress')} className="w-full py-4 bg-white/10 hover:bg-white/20 text-white rounded-xl text-[0.65rem] font-black uppercase tracking-widest transition-all border border-white/10">
                        Session Briefing
                    </button>
                </div>
            </div>

            {/* Support Tooltip */}
            <div className="bg-success/10 border border-success/20 rounded-[2rem] p-8 flex items-center gap-6 relative overflow-hidden">
                <div className="absolute -right-6 -bottom-6 opacity-10">
                    <ShieldCheck size={120} className="text-success" />
                </div>
                <div className="w-14 h-14 rounded-2xl bg-card flex items-center justify-center text-success shadow-sm border border-success/20 shrink-0">
                    <ShieldCheck size={28} />
                </div>
                <div>
                    <p className="text-sm font-black text-success">Secure Protocol</p>
                    <p className="text-[0.7rem] font-medium text-success/80 leading-snug mt-1">All timetable transmissions are authenticated by the academic registry.</p>
                </div>
            </div>
        </div>
      </div>

      <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; }
      `}</style>
    </div>
  );
}
