import React, { useEffect, useState } from "react";
import { Helmet } from "react-helmet-async";
import {
    Alert,
    Avatar,
    Box,
    Card,
    CardContent,
    CircularProgress,
    Divider,
    Grid,
    Typography,
    useTheme,
} from "@mui/material";
import {
    Area,
    AreaChart,
    Bar,
    BarChart,
    CartesianGrid,
    Cell,
    Pie,
    PieChart,
    ResponsiveContainer,
    Tooltip,
    XAxis,
    YAxis,
} from "recharts";
import {
    CheckCircle as CheckCircleIcon,
    Groups as GroupsIcon,
    Speed as SpeedIcon,
    Warning as WarningIcon,
} from "@mui/icons-material";

import { api, endpoints } from "../../services/api";

const COLORS = ["#0088FE", "#00C49F", "#FFBB28", "#FF8042", "#8884D8"];

const PERFORMANCE_LABELS = {
    "Bon performeur": "High Performer",
    "Moyenne performance": "Average Performer",
    "À risque": "At Risk",
};

const StatCard = ({ title, value, icon, color, subtitle }) => {
    return (
        <Card
            elevation={0}
            sx={{
                height: "100%",
                border: "1px solid",
                borderColor: "divider",
                borderRadius: 0,
            }}
        >
            <CardContent sx={{ p: 2, "&:last-child": { pb: 2 } }}>
                <Box display="flex" alignItems="center" gap={2}>
                    <Avatar
                        variant="square"
                        sx={{
                            bgcolor: `${color}15`,
                            color,
                            width: 48,
                            height: 48,
                            borderRadius: 0,
                        }}
                    >
                        {React.cloneElement(icon, { sx: { fontSize: 24 } })}
                    </Avatar>

                    <Box overflow="hidden">
                        <Typography
                            variant="caption"
                            color="text.secondary"
                            fontWeight="600"
                            sx={{
                                textTransform: "uppercase",
                                letterSpacing: 0.5,
                            }}
                        >
                            {title}
                        </Typography>

                        <Typography
                            variant="h5"
                            fontWeight="700"
                            noWrap
                            title={String(value)}
                            sx={{
                                lineHeight: 1.2,
                                my: 0.5,
                            }}
                        >
                            {value}
                        </Typography>

                        {subtitle && (
                            <Typography
                                variant="caption"
                                color="text.secondary"
                                noWrap
                                sx={{
                                    fontSize: "0.7rem",
                                    display: "block",
                                }}
                            >
                                {subtitle}
                            </Typography>
                        )}
                    </Box>
                </Box>
            </CardContent>
        </Card>
    );
};

const AdminDashboard = () => {
    const theme = useTheme();

    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [stats, setStats] = useState(null);
    const [subjectStats, setSubjectStats] = useState([]);

    useEffect(() => {
        const fetchAllData = async () => {
            setLoading(true);
            setError(null);

            try {
                const dashboardResponse = await api.get(endpoints.dashboard.admin);
                const dashboardData = await dashboardResponse.json();

                if (!dashboardResponse.ok || !dashboardData.success) {
                    throw new Error(
                        dashboardData.message || "Failed to load dashboard data."
                    );
                }

                setStats(dashboardData);

                const subjectsResponse = await api.get(
                    endpoints.stats.subjectSuccessRate
                );
                const subjectsData = await subjectsResponse.json();

                if (!subjectsResponse.ok) {
                    throw new Error(
                        subjectsData.message || "Failed to load subject statistics."
                    );
                }

                setSubjectStats(Array.isArray(subjectsData) ? subjectsData : []);
            } catch (err) {
                console.error("Dashboard error:", err);
                setError(err.message || "An unexpected error occurred.");
            } finally {
                setLoading(false);
            }
        };

        fetchAllData();
    }, []);

    if (loading) {
        return (
            <Box p={3} display="flex" justifyContent="center">
                <CircularProgress />
            </Box>
        );
    }

    if (error) {
        return (
            <Box p={3}>
                <Alert severity="error">{error}</Alert>
            </Box>
        );
    }

    return (
        <Box>
            <Helmet>
                <title>EduPredict - Admin Dashboard</title>
                <meta
                    name="description"
                    content="Overview of academic performance, attendance, and system-wide statistics."
                />
            </Helmet>

            <Box mb={4}>
                <Typography
                    variant="h4"
                    fontWeight="800"
                    color="primary"
                    gutterBottom
                >
                    Admin Dashboard
                </Typography>

                <Typography variant="body1" color="text.secondary">
                    Overview of academic performance and attendance.
                </Typography>

                <Divider sx={{ mt: 2 }} />
            </Box>

            <Grid container spacing={3} mb={4}>
                <Grid item xs={12} sm={6} md={3}>
                    <StatCard
                        title="Total Students"
                        value={stats?.cards?.total_students || 0}
                        icon={<GroupsIcon />}
                        color={theme.palette.primary.main}
                        subtitle="Enrolled This Year"
                    />
                </Grid>

                <Grid item xs={12} sm={6} md={3}>
                    <StatCard
                        title="Overall Average"
                        value={stats?.cards?.global_avg?.toFixed(2) || "N/A"}
                        icon={<SpeedIcon />}
                        color={theme.palette.info.main}
                        subtitle="Across All Subjects"
                    />
                </Grid>

                <Grid item xs={12} sm={6} md={3}>
                    <StatCard
                        title="Attendance Rate"
                        value={`${stats?.cards?.attendance_rate ?? 0}%`}
                        icon={<CheckCircleIcon />}
                        color={theme.palette.success.main}
                        subtitle="Overall Attendance"
                    />
                </Grid>

                <Grid item xs={12} sm={6} md={3}>
                    <StatCard
                        title="At-Risk Students"
                        value={stats?.cards?.at_risk_count || 0}
                        icon={<WarningIcon />}
                        color={theme.palette.error.main}
                        subtitle="Require Attention"
                    />
                </Grid>
            </Grid>

            <Grid container spacing={3}>
                <Grid item xs={12} md={6}>
                    <Card elevation={2} sx={{ height: 400 }}>
                        <CardContent>
                            <Typography variant="h6" fontWeight="bold" gutterBottom>
                                AI Performance Distribution
                            </Typography>

                            <Divider sx={{ mb: 2 }} />

                            <ResponsiveContainer width="100%" height={300}>
                                <PieChart>
                                    <Pie
                                        data={stats?.charts?.performance_distribution || []}
                                        cx="50%"
                                        cy="50%"
                                        innerRadius={60}
                                        outerRadius={100}
                                        paddingAngle={5}
                                        dataKey="value"
                                        label={({ name, percent }) =>
                                            `${PERFORMANCE_LABELS[name] || name
                                            } ${(percent * 100).toFixed(0)}%`
                                        }
                                    >
                                        {stats?.charts?.performance_distribution?.map(
                                            (entry, index) => (
                                                <Cell
                                                    key={`performance-cell-${index}`}
                                                    fill={COLORS[index % COLORS.length]}
                                                />
                                            )
                                        )}
                                    </Pie>

                                    <Tooltip
                                        formatter={(value, name) => [
                                            value,
                                            PERFORMANCE_LABELS[name] || name,
                                        ]}
                                    />
                                </PieChart>
                            </ResponsiveContainer>
                        </CardContent>
                    </Card>
                </Grid>

                <Grid item xs={12} md={6}>
                    <Card elevation={2} sx={{ height: 400 }}>
                        <CardContent>
                            <Typography variant="h6" fontWeight="bold" gutterBottom>
                                Monthly Attendance Trend
                            </Typography>

                            <Divider sx={{ mb: 2 }} />

                            <ResponsiveContainer width="100%" height={300}>
                                <AreaChart data={stats?.charts?.attendance_trend || []}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="month" />
                                    <YAxis domain={[0, 100]} />
                                    <Tooltip />
                                    <Area
                                        type="monotone"
                                        dataKey="rate"
                                        name="Attendance Rate"
                                        stroke={theme.palette.success.main}
                                        fill={theme.palette.success.light}
                                    />
                                </AreaChart>
                            </ResponsiveContainer>
                        </CardContent>
                    </Card>
                </Grid>

                <Grid item xs={12} md={6}>
                    <Card elevation={2} sx={{ height: 400 }}>
                        <CardContent>
                            <Typography variant="h6" fontWeight="bold" gutterBottom>
                                Subject Success Rate
                            </Typography>

                            <Divider sx={{ mb: 2 }} />

                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart data={subjectStats}>
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis dataKey="subject" tick={false} />
                                    <YAxis domain={[0, 20]} />
                                    <Tooltip />
                                    <Bar
                                        dataKey="success_rate"
                                        fill={theme.palette.primary.main}
                                        name="Average Grade"
                                    />
                                </BarChart>
                            </ResponsiveContainer>
                        </CardContent>
                    </Card>
                </Grid>

                <Grid item xs={12} md={6}>
                    <Card elevation={2} sx={{ height: 400 }}>
                        <CardContent>
                            <Typography variant="h6" fontWeight="bold" gutterBottom>
                                Top 5 Teacher Workload
                            </Typography>

                            <Divider sx={{ mb: 2 }} />

                            <ResponsiveContainer width="100%" height={300}>
                                <BarChart
                                    layout="vertical"
                                    data={stats?.charts?.teacher_workload || []}
                                >
                                    <CartesianGrid strokeDasharray="3 3" />
                                    <XAxis type="number" />
                                    <YAxis dataKey="name" type="category" width={100} />
                                    <Tooltip />
                                    <Bar
                                        dataKey="students"
                                        fill={theme.palette.secondary.main}
                                        name="Number of Students"
                                    />
                                </BarChart>
                            </ResponsiveContainer>
                        </CardContent>
                    </Card>
                </Grid>
            </Grid>
        </Box>
    );
};

export default AdminDashboard;