import { useState, useEffect } from 'react';
import api from '../../store/auth';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, ResponsiveContainer,
  AreaChart, Area, PieChart, Pie, Cell, CartesianGrid
} from 'recharts';
import {
  TrendingUp, Users, BookOpen, DollarSign,
  Download, Calendar, ChevronRight, RefreshCw,
  Award, Activity, Sparkles, Filter, FileText,
  Database, ArrowUpRight, ArrowDownRight, MoreVertical
} from 'lucide-react';

interface ReportData {
  enrolmentStats: {
    totalEnrollments: number;
    activeCourses: number;
    avgCompletionRate: number;
    totalCompletions: number;
  };
  studentGrowth: any[];
  monthlyRevenue: any[];
  subjectPerformance: any[];
}

const CustomTooltip = ({ active, payload, label, prefix = "" }: any) => {
  if (active && payload && payload.length) {
    return (
      <div className="bg-card border border-border p-4 rounded-xl shadow-2xl backdrop-blur-md">
        <p className="text-[0.65rem] font-black uppercase tracking-widest text-text-muted mb-2">{label}</p>
        <div className="space-y-1.5">
          {payload.map((entry: any, index: number) => (
            <div key={index} className="flex items-center justify-between gap-6">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 rounded-full" style={{ backgroundColor: entry.color || entry.fill || "#3b82f6" }} />
                <span className="text-[0.75rem] font-bold text-text-secondary capitalize">{entry.name.replace(/([A-Z])/g, ' $1')}</span>
              </div>
              <span className="text-[0.85rem] font-black text-text">{prefix}{entry.value.toLocaleString()}</span>
            </div>
          ))}
        </div>
      </div>
    );
  }
  return null;
};

export default function Reports() {
  const [data, setData] = useState<ReportData | null>(null);
  const [loading, setLoading] = useState(true);
  const [timeRange, setTimeRange] = useState('6m');
  const [showExportMenu, setShowExportMenu] = useState(false);

  useEffect(() => {
    loadReportData();
  }, [timeRange]);

  const loadReportData = async () => {
    setLoading(true);
    try {
      const res = await api.get('/reports/summary', { params: { range: timeRange } });
      setData(res.data);
    } catch (err) {
      console.error('Failed to load report intelligence');
      setData(mockData);
    } finally {
      setLoading(false);
    }
  };

  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';
    }
  };

  if (loading || !data) return (
    <div className="flex flex-col justify-center items-center h-[60vh] gap-4 text-text-muted">
      <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
      <p className="font-black uppercase tracking-[3px] text-[0.6rem]">Generating Intelligence Suite...</p>
    </div>
  );

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col xl:flex-row justify-between items-start xl:items-end gap-6">
        <div className="space-y-1">
          <div className="flex items-center gap-3 mb-2">
            <div className="p-2 bg-primary/10 rounded-xl text-primary">
              <Activity size={20} />
            </div>
            <span className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">Executive Audit</span>
          </div>
          <h1 className="text-4xl font-black text-text tracking-tighter uppercase">Intelligence Center</h1>
          <p className="text-text-muted text-lg font-medium">Global academic performance and institutional metrics.</p>
        </div>
        
        <div className="flex flex-wrap items-center gap-3">
          {/* Time Range Toggle */}
          <div className="flex p-1 bg-muted/50 rounded-xl border border-border mr-2">
            {['1m', '3m', '6m', '1y'].map(range => (
                <button 
                key={range}
                onClick={() => setTimeRange(range)}
                className={`px-4 py-2 rounded-lg text-[0.65rem] font-black uppercase tracking-widest transition-all ${timeRange === range ? 'bg-card text-primary shadow-sm ring-1 ring-border' : 'text-text-muted hover:text-text'}`}
                >
                {range}
                </button>
            ))}
          </div>

          <button 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" onClick={loadReportData}>
            <RefreshCw size={18} className="text-primary" />
            Synchronize
          </button>
          
          <div className="relative">
            <button 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" onClick={() => setShowExportMenu(!showExportMenu)}>
              <Download size={18} />
              Export Intelligence
            </button>
            
            {showExportMenu && (
              <div className="absolute right-0 top-full mt-3 w-56 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">Select Protocol</p>
                <button className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-muted transition-all text-text font-bold text-sm">
                  <FileText className="text-blue-500" size={16} /> PDF Audit Report
                </button>
                <button className="w-full flex items-center gap-3 p-3 rounded-xl hover:bg-muted transition-all text-text font-bold text-sm">
                  <Database className="text-emerald-500" size={16} /> CSV Data Vault
                </button>
              </div>
            )}
          </div>
        </div>
      </div>

      {/* Bento Stats Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {[
          { label: 'Market Enrollment', value: data.enrolmentStats.totalEnrollments, icon: Users, color: 'blue', trend: '+14.2%', up: true },
          { label: 'Active Curriculum', value: data.enrolmentStats.activeCourses, icon: BookOpen, color: 'emerald', trend: '+2', up: true },
          { label: 'Engagement Rate', value: `${data.enrolmentStats.avgCompletionRate}%`, icon: Award, color: 'purple', trend: '-2.4%', up: false },
          { label: 'Intelligence Records', value: data.enrolmentStats.totalCompletions, icon: Activity, color: 'orange', trend: '+8.1%', up: true },
        ].map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-6 rounded-[2rem] shadow-sm relative overflow-hidden group hover:shadow-md transition-all">
            <div className="relative z-10 flex justify-between items-start mb-4">
              <div className={`p-3 rounded-2xl ${getStatColors(stat.color)} group-hover:scale-110 transition-transform`}>
                <stat.icon size={24} />
              </div>
              <div className={`flex items-center gap-1 text-[0.7rem] font-black px-2 py-1 rounded-lg ${stat.up ? 'bg-emerald-50 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400' : 'bg-rose-50 dark:bg-rose-900/30 text-rose-600 dark:text-rose-400'}`}>
                {stat.up ? <ArrowUpRight size={14} /> : <ArrowDownRight size={14} />}
                {stat.trend}
              </div>
            </div>
            <p className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted mb-1">{stat.label}</p>
            <h3 className="text-3xl font-black text-text tracking-tighter">{stat.value.toLocaleString()}</h3>
          </div>
        ))}
      </div>

      {/* Intelligence Charts Section */}
      <div className="grid grid-cols-1 lg:grid-cols-12 gap-8">
        
        {/* Main Enrollment Area Chart (Supabase-like) */}
        <div className="lg:col-span-8 space-y-6">
          <div className="bg-card border border-border rounded-[2.5rem] p-10 shadow-sm relative overflow-hidden group">
            <div className="absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-500/0 via-emerald-500 to-emerald-500/0 opacity-50"></div>
            <div className="flex justify-between items-start mb-10 relative z-10">
              <div>
                <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-emerald-500/50 mb-2">Growth Analysis</h4>
                <h2 className="text-2xl font-black text-text tracking-tight">Student Population Trend</h2>
              </div>
              <div className="flex gap-4">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-emerald-500"></div>
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Learners</span>
                </div>
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-primary"></div>
                  <span className="text-[0.65rem] font-black text-text-muted uppercase tracking-widest">Faculty</span>
                </div>
              </div>
            </div>

            <div className="h-[400px] w-full relative z-10">
              <ResponsiveContainer width="100%" height="100%">
                <AreaChart data={data.studentGrowth} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
                  <defs>
                    <linearGradient id="colorStudents" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#10b981" stopOpacity={0.3}/>
                      <stop offset="95%" stopColor="#10b981" stopOpacity={0}/>
                    </linearGradient>
                    <linearGradient id="colorTeachers" x1="0" y1="0" x2="0" y2="1">
                      <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.2}/>
                      <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/>
                    </linearGradient>
                  </defs>
                  <CartesianGrid vertical={false} strokeDasharray="3 3" stroke="currentColor" className="text-border/30" />
                  <XAxis 
                    dataKey="month" 
                    axisLine={false} 
                    tickLine={false} 
                    tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} 
                    className="text-text-muted"
                    dy={15}
                  />
                  <YAxis 
                    axisLine={false} 
                    tickLine={false} 
                    tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 900 }} 
                    className="text-text-muted"
                  />
                  <Tooltip content={<CustomTooltip />} cursor={{ stroke: 'currentColor', className: 'text-border', strokeWidth: 2, strokeDasharray: '4 4' }} />
                  <Area 
                    type="monotone" 
                    dataKey="students" 
                    stroke="#10b981" 
                    strokeWidth={4} 
                    fillOpacity={1} 
                    fill="url(#colorStudents)" 
                    animationDuration={1500}
                    name="Learners"
                  />
                  <Area 
                    type="monotone" 
                    dataKey="teachers" 
                    stroke="#3b82f6" 
                    strokeWidth={2} 
                    strokeDasharray="5 5"
                    fillOpacity={1} 
                    fill="url(#colorTeachers)" 
                    animationDuration={2000}
                    name="Faculty"
                  />
                </AreaChart>
              </ResponsiveContainer>
            </div>
          </div>

          {/* Revenue and Subject Performance Row */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div className="bg-card border border-border rounded-[2rem] p-8 shadow-sm">
              <div className="flex justify-between items-center mb-8">
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text-muted">Financial Velocity</h3>
                <div className="p-2 bg-emerald-50 dark:bg-emerald-900/20 rounded-xl text-emerald-600 dark:text-emerald-400">
                  <DollarSign size={18} />
                </div>
              </div>
              <div className="h-[250px]">
                <ResponsiveContainer width="100%" height="100%">
                  <BarChart data={data.monthlyRevenue} margin={{ top: 0, right: 0, left: -20, bottom: 0 }}>
                    <CartesianGrid vertical={false} strokeDasharray="3 3" stroke="currentColor" className="text-border/30" />
                    <XAxis dataKey="month" axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 800 }} className="text-text-muted" dy={10} />
                    <YAxis axisLine={false} tickLine={false} tick={{ fill: 'currentColor', fontSize: 10, fontWeight: 800 }} className="text-text-muted" />
                    <Tooltip content={<CustomTooltip prefix="$" />} cursor={{ fill: 'currentColor', className: 'text-muted/10' }} />
                    <Bar dataKey="revenue" fill="#0047AB" radius={[6, 6, 0, 0]} barSize={24} name="Revenue" />
                    <Bar dataKey="expenses" fill="currentColor" className="text-text-muted/20" radius={[6, 6, 0, 0]} barSize={24} name="Expenses" />
                  </BarChart>
                </ResponsiveContainer>
              </div>
            </div>

            <div className="bg-slate-900 rounded-[2rem] p-8 shadow-xl text-white relative overflow-hidden">
               <div className="absolute -right-10 -top-10 opacity-5 rotate-12">
                  <Activity size={200} />
               </div>
               <div className="relative z-10 flex justify-between items-center mb-8">
                <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-white/30">Engagement Stats</h3>
                <Sparkles className="text-blue-400" size={18} />
              </div>
              <div className="space-y-6 relative z-10">
                {[
                  { label: 'Completion Goal', value: 85, color: 'bg-blue-400' },
                  { label: 'Student Satisfaction', value: 92, color: 'bg-emerald-400' },
                  { label: 'Faculty Utilization', value: 78, color: 'bg-orange-400' },
                ].map(item => (
                  <div key={item.label} className="space-y-2">
                    <div className="flex justify-between items-end">
                      <span className="text-[0.65rem] font-black uppercase tracking-widest text-white/50">{item.label}</span>
                      <span className="text-sm font-black text-white">{item.value}%</span>
                    </div>
                    <div className="w-full h-1.5 bg-white/5 rounded-full overflow-hidden">
                      <div className={`h-full ${item.color} rounded-full transition-all duration-1000`} style={{ width: `${item.value}%` }}></div>
                    </div>
                  </div>
                ))}
              </div>
              <button className="w-full mt-10 py-4 bg-white/10 hover:bg-white/20 text-white text-[0.65rem] font-black uppercase tracking-[3px] rounded-xl transition-all border border-white/10">
                Generate Full Audit
              </button>
            </div>
          </div>
        </div>

        {/* Intelligence Ledger (Right column) */}
        <div className="lg:col-span-4 space-y-8">
          {/* Pie Chart Analysis */}
          <div className="bg-card border border-border rounded-[2.5rem] p-8 shadow-sm">
            <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text-muted mb-8 px-2 text-center">Faculty Distribution</h3>
            <div className="h-[240px] w-full">
              <ResponsiveContainer width="100%" height="100%">
                <PieChart>
                  <Pie
                    data={[
                      { name: 'Pure Sciences', value: 35 },
                      { name: 'Mathematics', value: 25 },
                      { name: 'Humanities', value: 20 },
                      { name: 'Languages', value: 20 },
                    ]}
                    innerRadius={60}
                    outerRadius={80}
                    paddingAngle={8}
                    dataKey="value"
                    stroke="none"
                  >
                    {[
                      { fill: '#0047AB' },
                      { fill: '#10b981' },
                      { fill: '#8b5cf6' },
                      { fill: '#f59e0b' }
                    ].map((entry, index) => (
                      <Cell key={`cell-${index}`} fill={entry.fill} />
                    ))}
                  </Pie>
                  <Tooltip content={<CustomTooltip />} />
                </PieChart>
              </ResponsiveContainer>
            </div>
            <div className="mt-4 grid grid-cols-2 gap-4">
               {[
                 { label: 'Sciences', color: 'bg-[#0047AB]' },
                 { label: 'Math', color: 'bg-[#10b981]' },
                 { label: 'Arts', color: 'bg-[#8b5cf6]' },
                 { label: 'Misc', color: 'bg-[#f59e0b]' }
               ].map(l => (
                 <div key={l.label} className="flex items-center gap-2">
                   <div className={`w-1.5 h-1.5 rounded-full ${l.color}`}></div>
                   <span className="text-[0.6rem] font-black uppercase text-text-muted tracking-widest">{l.label}</span>
                 </div>
               ))}
            </div>
          </div>

          {/* Subject Performance Ledger */}
          <div className="bg-card border border-border rounded-[2.5rem] overflow-hidden shadow-sm flex flex-col">
            <div className="p-8 bg-muted/50 border-b border-border flex justify-between items-center">
              <h3 className="text-[0.7rem] font-black uppercase tracking-[3px] text-text">Subject Ledger</h3>
              <button className="text-primary text-[0.65rem] font-black hover:underline uppercase tracking-widest">Full Rank</button>
            </div>
            <div className="p-2 divide-y divide-border">
              {data.subjectPerformance.slice(0, 5).map((subject, idx) => (
                <div key={idx} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors group rounded-2xl cursor-default">
                  <div className="flex items-center gap-4">
                    <div className="w-10 h-10 rounded-xl bg-slate-900 flex items-center justify-center text-[0.7rem] font-black text-emerald-500 shadow-sm border border-slate-800">
                      {subject.subject[0]}
                    </div>
                    <div>
                      <p className="text-sm font-black text-text tracking-tight">{subject.subject}</p>
                      <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">{subject.enrolled} Students</p>
                    </div>
                  </div>
                  <div className="text-right">
                    <p className="text-sm font-black text-primary">{subject.passRate}%</p>
                    <p className="text-[0.6rem] font-black text-emerald-500 uppercase tracking-tighter">Success</p>
                  </div>
                </div>
              ))}
            </div>
            <button className="m-4 mt-2 py-4 bg-muted/50 hover:bg-muted text-text-muted text-[0.65rem] font-black uppercase tracking-[3px] rounded-2xl transition-all border border-border">
              All Subject Intelligence
            </button>
          </div>

          {/* Forecast Card */}
          <div className="bg-gradient-to-br from-emerald-600 to-emerald-800 rounded-[2.5rem] p-8 text-white shadow-2xl relative overflow-hidden group">
            <div className="absolute right-[-40px] bottom-[-40px] opacity-10 group-hover:scale-110 transition-transform duration-700">
              <TrendingUp size={200} />
            </div>
            <div className="relative z-10">
              <div className="flex items-center gap-2 mb-6">
                <div className="p-2 bg-white/10 rounded-xl backdrop-blur-md">
                  <Sparkles size={16} />
                </div>
                <span className="text-[0.6rem] font-black uppercase tracking-[3px] text-emerald-100/50">NextGen AI Forecast</span>
              </div>
              <h4 className="text-xl font-black mb-3 leading-tight tracking-tight uppercase">Projected Enrollment for Term 3 is increasing.</h4>
              <p className="text-sm font-medium text-emerald-50/70 leading-relaxed mb-8">
                Based on current trends, we expect an 8.2% increase in pure science enrollments next cycle.
              </p>
              <div className="flex items-center gap-3">
                <div className="flex -space-x-2">
                   {[1, 2, 3].map(i => (
                     <div key={i} className="w-8 h-8 rounded-full border-2 border-emerald-700 bg-emerald-100 flex items-center justify-center text-[0.6rem] font-bold text-emerald-800 overflow-hidden shadow-sm">
                        <img src={`https://i.pravatar.cc/150?u=rep${i}`} alt="Avatar" />
                     </div>
                   ))}
                </div>
                <span className="text-[0.6rem] font-black uppercase tracking-widest text-emerald-100">Verified by 12 Analysts</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

const mockData = {
  enrolmentStats: {
    totalEnrollments: 1240,
    activeCourses: 42,
    avgCompletionRate: 88,
    totalCompletions: 310
  },
  studentGrowth: [
    { month: 'Jan', students: 1000, teachers: 80 },
    { month: 'Feb', students: 1050, teachers: 82 },
    { month: 'Mar', students: 1100, teachers: 85 },
    { month: 'Apr', students: 1150, teachers: 88 },
    { month: 'May', students: 1200, teachers: 90 },
    { month: 'Jun', students: 1240, teachers: 92 },
  ],
  monthlyRevenue: [
    { month: 'Jan', revenue: 12000, expenses: 8000 },
    { month: 'Feb', revenue: 13500, expenses: 8500 },
    { month: 'Mar', revenue: 14800, expenses: 9100 },
    { month: 'Apr', revenue: 15600, expenses: 8800 },
    { month: 'May', revenue: 16200, expenses: 9400 },
    { month: 'Jun', revenue: 17500, expenses: 9600 },
  ],
  subjectPerformance: [
    { subject: 'Mathematics', enrolled: 120, passRate: 92 },
    { subject: 'Physics', enrolled: 95, passRate: 88 },
    { subject: 'Chemistry', enrolled: 88, passRate: 85 },
    { subject: 'Biology', enrolled: 110, passRate: 94 },
    { subject: 'English', enrolled: 150, passRate: 98 },
  ]
};
