import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import {
    GraduationCap, BookOpen, Users, ClipboardList,
    ArrowUpRight, ArrowDownRight, Award, Calendar, CheckSquare, AlertCircle,
} from 'lucide-react';
import {
    ResponsiveContainer, BarChart, Bar, LineChart, Line,
    XAxis, YAxis, CartesianGrid, Tooltip, Legend, PieChart, Pie, Cell,
} from 'recharts';

// ─── Static demo data ─────────────────────────────────────────────────────────

const enrollmentTrend = [
    { month: 'Jan', enrolled: 240, graduated: 30 },
    { month: 'Feb', enrolled: 280, graduated: 45 },
    { month: 'Mar', enrolled: 310, graduated: 52 },
    { month: 'Apr', enrolled: 295, graduated: 38 },
    { month: 'May', enrolled: 340, graduated: 61 },
    { month: 'Jun', enrolled: 375, graduated: 74 },
    { month: 'Jul', enrolled: 360, graduated: 68 },
];

const attendanceData = [
    { week: 'W1', rate: 88 }, { week: 'W2', rate: 84 }, { week: 'W3', rate: 91 },
    { week: 'W4', rate: 87 }, { week: 'W5', rate: 93 }, { week: 'W6', rate: 89 },
    { week: 'W7', rate: 95 }, { week: 'W8', rate: 92 },
];

const courseDistribution = [
    { name: 'Computer Science', value: 28 },
    { name: 'Business', value: 22 },
    { name: 'Engineering', value: 20 },
    { name: 'Arts & Design', value: 16 },
    { name: 'Sciences', value: 14 },
];

const COLORS = ['#10b981', '#34d399', '#6ee7b7', '#a7f3d0', '#d1fae5'];

const recentCourses = [
    { title: 'Web Development Bootcamp', instructor: 'Dr. Rahman', students: 124, completion: 78, status: 'Active' },
    { title: 'Data Science Fundamentals', instructor: 'Prof. Akter', students: 98, completion: 55, status: 'Active' },
    { title: 'UI/UX Design Principles', instructor: 'Ms. Sultana', students: 76, completion: 91, status: 'Completed' },
    { title: 'Digital Marketing', instructor: 'Mr. Hossain', students: 143, completion: 34, status: 'Active' },
    { title: 'Project Management', instructor: 'Dr. Begum', students: 62, completion: 100, status: 'Completed' },
];

const upcomingAssignments = [
    { title: 'Midterm Exam — CS101', due: 'Tomorrow', course: 'Computer Science', priority: 'high' },
    { title: 'Group Project Submission', due: 'In 3 days', course: 'Business', priority: 'medium' },
    { title: 'Lab Report', due: 'In 5 days', course: 'Engineering', priority: 'low' },
    { title: 'Portfolio Review', due: 'In 7 days', course: 'Arts & Design', priority: 'medium' },
];

const priorityColors: Record<string, string> = {
    high:   'bg-red-100 text-red-700',
    medium: 'bg-yellow-100 text-yellow-700',
    low:    'bg-green-100 text-green-700',
};

// ─── Stat card ────────────────────────────────────────────────────────────────

function StatCard({
    title, value, change, changeType, icon: Icon, iconBg, iconColor,
}: {
    title: string; value: string; change: string; changeType: 'up' | 'down';
    icon: React.ElementType; iconBg: string; iconColor: string;
}) {
    const Arrow = changeType === 'up' ? ArrowUpRight : ArrowDownRight;
    return (
        <Card className="border-[#d8d8d8] shadow-sm">
            <CardContent className="p-4">
                <div className="flex items-start justify-between">
                    <div>
                        <p className="text-xs tracking-wide text-[#6d7175] uppercase">{title}</p>
                        <p className="mt-1 text-2xl font-bold text-[#202223]">{value}</p>
                        <div className={`mt-1 flex items-center gap-1 text-xs font-medium ${changeType === 'up' ? 'text-green-600' : 'text-red-500'}`}>
                            <Arrow className="h-3 w-3" />
                            {change}
                        </div>
                    </div>
                    <div className={`flex h-10 w-10 items-center justify-center rounded-xl ${iconBg}`}>
                        <Icon className={`h-5 w-5 ${iconColor}`} />
                    </div>
                </div>
            </CardContent>
        </Card>
    );
}

// ─── Component ────────────────────────────────────────────────────────────────

export default function EducationCentralDashboard() {
    return (
        <div className="space-y-6">
            {/* KPI row */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                <StatCard title="Total Students" value="2,847" change="11% vs last month" changeType="up" icon={Users} iconBg="bg-emerald-100" iconColor="text-emerald-600" />
                <StatCard title="Active Courses" value="148" change="6% vs last month" changeType="up" icon={BookOpen} iconBg="bg-teal-100" iconColor="text-teal-600" />
                <StatCard title="Graduates This Month" value="74" change="20% vs last month" changeType="up" icon={GraduationCap} iconBg="bg-green-100" iconColor="text-green-600" />
                <StatCard title="Assignments Due" value="36" change="4% vs last month" changeType="down" icon={ClipboardList} iconBg="bg-amber-100" iconColor="text-amber-600" />
            </div>

            {/* Secondary KPIs */}
            <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
                {[
                    { label: 'Avg. Completion Rate', value: '71.6%', icon: CheckSquare, bg: 'bg-blue-50', color: 'text-blue-600' },
                    { label: 'Avg. Attendance', value: '90.2%', icon: Calendar, bg: 'bg-purple-50', color: 'text-purple-600' },
                    { label: 'Top Performers', value: '312', icon: Award, bg: 'bg-yellow-50', color: 'text-yellow-500' },
                    { label: 'At-Risk Students', value: '48', icon: AlertCircle, bg: 'bg-red-50', color: 'text-red-500' },
                ].map((s) => (
                    <Card key={s.label} className="border-[#d8d8d8] shadow-sm">
                        <CardContent className="flex items-center gap-3 p-4">
                            <div className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${s.bg}`}>
                                <s.icon className={`h-4 w-4 ${s.color}`} />
                            </div>
                            <div>
                                <p className="text-xs text-[#6d7175]">{s.label}</p>
                                <p className="text-base font-semibold text-[#202223]">{s.value}</p>
                            </div>
                        </CardContent>
                    </Card>
                ))}
            </div>

            {/* Charts row */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-7">
                {/* Enrollment & graduation bar */}
                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-4">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Enrollment & Graduation</CardTitle>
                        <CardDescription>Monthly student enrollment and graduation count</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <BarChart data={enrollmentTrend}>
                                    <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                                    <XAxis dataKey="month" tick={{ fontSize: 11 }} />
                                    <YAxis tick={{ fontSize: 11 }} />
                                    <Tooltip />
                                    <Legend />
                                    <Bar dataKey="enrolled" name="Enrolled" fill="#10b981" radius={[3, 3, 0, 0]} />
                                    <Bar dataKey="graduated" name="Graduated" fill="#34d399" radius={[3, 3, 0, 0]} />
                                </BarChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                {/* Course distribution pie */}
                <Card className="col-span-1 border-[#d8d8d8] shadow-sm lg:col-span-3">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Students by Department</CardTitle>
                        <CardDescription>Enrollment distribution across departments</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-64">
                            <ResponsiveContainer width="100%" height="100%">
                                <PieChart>
                                    <Pie data={courseDistribution} cx="50%" cy="50%" innerRadius={50} outerRadius={80} dataKey="value" label={({ name, value }) => `${value}%`}>
                                        {courseDistribution.map((_, i) => (
                                            <Cell key={i} fill={COLORS[i % COLORS.length]} />
                                        ))}
                                    </Pie>
                                    <Tooltip formatter={(v) => `${v}%`} />
                                    <Legend />
                                </PieChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>
            </div>

            {/* Attendance trend + Course list + Assignments */}
            <div className="grid grid-cols-1 gap-4 lg:grid-cols-3">
                {/* Attendance trend */}
                <Card className="border-[#d8d8d8] shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Attendance Trend</CardTitle>
                        <CardDescription>Weekly attendance rate %</CardDescription>
                    </CardHeader>
                    <CardContent className="pt-4">
                        <div className="h-48">
                            <ResponsiveContainer width="100%" height="100%">
                                <LineChart data={attendanceData}>
                                    <CartesianGrid strokeDasharray="3 3" className="stroke-muted" />
                                    <XAxis dataKey="week" tick={{ fontSize: 10 }} />
                                    <YAxis tick={{ fontSize: 10 }} domain={[70, 100]} tickFormatter={(v) => `${v}%`} />
                                    <Tooltip formatter={(v) => `${v}%`} />
                                    <Line type="monotone" dataKey="rate" stroke="#10b981" strokeWidth={2} dot={{ r: 3 }} name="Attendance" />
                                </LineChart>
                            </ResponsiveContainer>
                        </div>
                    </CardContent>
                </Card>

                {/* Active courses */}
                <Card className="border-[#d8d8d8] shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Active Courses</CardTitle>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="divide-y divide-[#efefef]">
                            {recentCourses.map((c) => (
                                <div key={c.title} className="px-4 py-2.5">
                                    <div className="flex items-center justify-between gap-2">
                                        <p className="text-xs font-medium text-[#202223] line-clamp-1">{c.title}</p>
                                        <span className={`shrink-0 rounded-full px-2 py-0.5 text-xs ${c.status === 'Completed' ? 'bg-green-100 text-green-700' : 'bg-blue-100 text-blue-700'}`}>
                                            {c.status}
                                        </span>
                                    </div>
                                    <p className="mt-0.5 text-xs text-[#6d7175]">{c.instructor} · {c.students} students</p>
                                    <div className="mt-1.5 h-1.5 overflow-hidden rounded-full bg-[#e5e7eb]">
                                        <div className="h-full rounded-full bg-emerald-500" style={{ width: `${c.completion}%` }} />
                                    </div>
                                    <p className="mt-0.5 text-right text-xs text-[#6d7175]">{c.completion}%</p>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>

                {/* Upcoming assignments */}
                <Card className="border-[#d8d8d8] shadow-sm">
                    <CardHeader className="border-b border-[#e3e3e3] pb-3">
                        <CardTitle className="text-base font-semibold text-[#202223]">Upcoming Assignments</CardTitle>
                    </CardHeader>
                    <CardContent className="p-0">
                        <div className="divide-y divide-[#efefef]">
                            {upcomingAssignments.map((a) => (
                                <div key={a.title} className="flex items-start gap-3 px-4 py-3">
                                    <span className={`mt-0.5 shrink-0 rounded-full px-2 py-0.5 text-xs ${priorityColors[a.priority]}`}>
                                        {a.priority}
                                    </span>
                                    <div>
                                        <p className="text-xs font-medium text-[#202223]">{a.title}</p>
                                        <p className="text-xs text-[#6d7175]">{a.course} · Due {a.due}</p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </CardContent>
                </Card>
            </div>
        </div>
    );
}
