import toast from "react-hot-toast";
import { Card, Select, Empty, Pagination } from "antd";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { TrendingUp, BarChart2, Calendar, ChartNoAxesColumnDecreasing, ChartNoAxesColumnIncreasing, Share2 } from "lucide-react";
import React, { useState, useCallback, useMemo, useRef, useLayoutEffect, useEffect } from "react";
import { ResponsiveContainer, LineChart, Line, BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend, LabelList } from "recharts";

interface IGraphPoint {
    week: string;
    percentage: number | null;
}

interface ISubjectPoint {
    subject: string;
    percentage: number | null;
}

interface OverviewTabProps {
    studentId: string;
    enrolledExamId?: string;
    enrolledExamName?: string;
}

const formatWeekLabel = (label: string): string => {
    if (!label) return "";
    const formattedLabel = label.replace(/From\s+/i, "");
    const parts = formattedLabel.split(/\s+to\s+/i);
    if (parts.length !== 2) return label;

    const formatDate = (dateStr: string, includeMonth: boolean) => {
        const date = new Date(dateStr);
        if (isNaN(date.getTime())) return dateStr;
        return date.toLocaleDateString("en-US", {
            month: includeMonth ? "short" : undefined,
            day: "numeric",
        });
    };

    const firstDate = new Date(parts[0]);
    const secondDate = new Date(parts[1]);
    if (isNaN(firstDate.getTime()) || isNaN(secondDate.getTime())) return label;

    const sameMonthAndYear =
        firstDate.getFullYear() === secondDate.getFullYear() &&
        firstDate.getMonth() === secondDate.getMonth();

    const firstFormatted = formatDate(parts[0], true);
    const secondFormatted = sameMonthAndYear ? formatDate(parts[1], false) : formatDate(parts[1], true);

    return `${firstFormatted} - ${secondFormatted}`;
};

const ChartTooltip = ({ active, payload, label, isSubject = false }: any) => {
    if (!active || !payload?.[0]) return null;
    const data = payload[0].payload;
    const formattedLabel = isSubject ? label : formatWeekLabel(label);

    return (
        <div className="bg-white rounded-xl p-3 shadow-xl border border-slate-100 min-w-[160px]">
            <p className="font-bold text-slate-700 text-xs mb-1.5 flex items-center gap-1">
                {!isSubject && <Calendar size={12} className="text-slate-400" />}
                {formattedLabel}
            </p>
            {!data.hasSubmissions ? (
                <p className="text-slate-400 text-xs italic">No Submissions</p>
            ) : (
                <p className="text-brand-blue text-xs font-medium flex items-center gap-1.5">
                    <span className="w-2 h-2 rounded-full bg-brand-blue inline-block" />
                    Percentage: <span className="font-bold text-slate-800">{data.percentage}%</span>
                </p>
            )}
        </div>
    );
};

const CHART_HEIGHT = 330;
const CHART_TOP = 15;
const CHART_BOTTOM = 44;

const SUBJECT_BAR_HEIGHT = 48;
const SUBJECT_LABEL_WIDTH = 140;
const X_AXIS_HEIGHT = 50;

const SubjectBarChart: React.FC<{ data: any[] }> = ({ data }) => {
    if (data.length === 0) {
        return (
            <div className="flex items-center justify-center h-full">
                <Empty description="No analytical metrics captured for this period" />
            </div>
        );
    }

    const maxPercentage = 100;

    return (
        <div className="flex flex-col h-full">
            <div className="flex" style={{ minHeight: `${X_AXIS_HEIGHT}px`, flexShrink: 0 }}>
                <div style={{ width: SUBJECT_LABEL_WIDTH, flexShrink: 0 }} />

                <div
                    style={{
                        flex: 1,
                        position: "relative",
                        borderBottom: "2px solid #e2e8f0",
                        paddingRight: "12px",
                    }}
                >
                    {[0, 25, 50, 75, 100].map((tick) => {
                        const isFirst = tick === 0;
                        const isLast = tick === 100;
                        return (
                            <div
                                key={tick}
                                style={{
                                    position: "absolute",
                                    bottom: 0,
                                    left: `${tick}%`,
                                    transform: isFirst
                                        ? "translateX(0%)"
                                        : isLast
                                            ? "translateX(-100%)"
                                            : "translateX(-50%)",
                                    display: "flex",
                                    flexDirection: "column",
                                    alignItems: isFirst ? "flex-start" : isLast ? "flex-end" : "center",
                                }}
                            >
                                <div style={{ width: "1px", height: "6px", backgroundColor: "#cbd5e1", marginBottom: "2px" }} />
                                <span
                                    style={{
                                        fontSize: "11px",
                                        fontWeight: 500,
                                        color: "#94a3b8",
                                        lineHeight: 1,
                                        whiteSpace: "nowrap",
                                        paddingBottom: "6px",
                                    }}
                                >
                                    {tick}%
                                </span>
                            </div>
                        );
                    })}
                </div>
            </div>

            <div className="flex-1 overflow-y-auto border-b border-slate-100 custom-scrollbar">
                {data.map((item, index) => {
                    const percentage = item.displayPercentage || 0;
                    const barWidthPercent = (percentage / maxPercentage) * 100;
                    const hasSubmissions = item.hasSubmissions;

                    return (
                        <div
                            key={`subject-${index}`}
                            title={hasSubmissions ? `${percentage}%` : "No Submissions"}
                            className="flex items-center border-b border-slate-100 hover:bg-slate-50 transition-colors"
                            style={{
                                height: `${SUBJECT_BAR_HEIGHT}px`,
                                minHeight: `${SUBJECT_BAR_HEIGHT}px`,
                            }}
                        >
                            <div
                                style={{
                                    width: `${SUBJECT_LABEL_WIDTH}px`,
                                    flexShrink: 0,
                                    paddingLeft: "12px",
                                    paddingRight: "12px",
                                }}
                                className="flex items-center"
                            >
                                <div
                                    className="text-sm font-medium text-slate-700 truncate"
                                    title={item.subject}
                                >
                                    <div className="flex items-center gap-1.5">
                                        {item.isShared && (
                                            <span title={`Shared by Exam Infra`} className="flex flex-shrink-0 items-center">
                                                <Share2 size={12} className="text-purple-500" />
                                            </span>
                                        )}
                                        <span className="truncate">{item.subject}</span>
                                    </div>
                                </div>
                            </div>

                            <div
                                style={{
                                    flex: 1,
                                    height: "100%",
                                    position: "relative",
                                    display: "flex",
                                    alignItems: "center",
                                    paddingRight: "12px",
                                    gap: "8px",
                                }}
                            >
                                {/* Bar */}
                                <div
                                    style={{
                                        width: percentage === 0 ? "8px" : `${barWidthPercent}%`,
                                        height: "28px",
                                        borderRadius: "0 6px 6px 0",
                                        backgroundColor: hasSubmissions ? "#1677ff" : "transparent",
                                        minWidth: percentage === 0 ? "8px" : (barWidthPercent > 5 ? "auto" : "35px"),
                                        flexShrink: 0,
                                        transition: "width 0.3s ease",
                                    }}
                                />
                                {hasSubmissions && (
                                    <span
                                        style={{
                                            color: "#1677ff",
                                            fontSize: "12px",
                                            fontWeight: "700",
                                            minWidth: "45px",
                                            textAlign: "right",
                                        }}
                                    >
                                        {percentage}%
                                    </span>
                                )}
                            </div>
                        </div>
                    );
                })}
            </div>
        </div>
    );
};

const OverviewTab: React.FC<OverviewTabProps> = ({ studentId, enrolledExamId, enrolledExamName }) => {
    const [testTypeFilter, setTestTypeFilter] = useState<string>("PRACTICE");
    const [graphData, setGraphData] = useState<IGraphPoint[]>([]);
    const [secondaryData, setSecondaryData] = useState<any[]>([]);
    const [trendLoading, setTrendLoading] = useState(false);
    const [secondaryLoading, setSecondaryLoading] = useState(false);
    const [subjectSort, setSubjectSort] = useState<"desc" | "asc">("desc");
    const [selectedSubjectId, setSelectedSubjectId] = useState<string>("all");
    const [subjects, setSubjects] = useState<{ subjectId: string; subject: string; isShared?: boolean; sharedInstitutionName?: string }[]>([]);

    const [subjectPage, setSubjectPage] = useState(1);
    const [totalSubjectPages, setTotalSubjectPages] = useState(0);
    const [subjectPageSize, setSubjectPageSize] = useState(5);

    const [examList, setExamList] = useState<{ id: string; examName: string }[]>([]);
    const [examPage, setExamPage] = useState(1);
    const [hasMoreExams, setHasMoreExams] = useState(true);
    const [examLoading, setExamLoading] = useState(false);
    const [examSearch, setExamSearch] = useState("");
    const [debouncedExamSearch, setDebouncedExamSearch] = useState("");
    const [localExamId, setLocalExamId] = useState<string | undefined>(enrolledExamId);
    const [hasInitializedExam, setHasInitializedExam] = useState(false);

    const activeExamName = useMemo(() => {
        const found = examList.find(e => e.id === localExamId);
        return found ? found.examName : enrolledExamName || "All Exams";
    }, [localExamId, examList, enrolledExamName]);

    useEffect(() => {
        if (enrolledExamId && !hasInitializedExam) {
            setLocalExamId(enrolledExamId);
            setHasInitializedExam(true);
        }
    }, [enrolledExamId, hasInitializedExam]);

    useEffect(() => {
        if (!enrolledExamId || !enrolledExamName) return;

        setExamList((prev) => {
            const alreadyExists = prev.some((exam) => exam.id === enrolledExamId);
            if (alreadyExists) return prev;
            return [{ id: enrolledExamId, examName: enrolledExamName }, ...prev];
        });
    }, [enrolledExamId, enrolledExamName]);

    useEffect(() => {
        const t = setTimeout(() => setDebouncedExamSearch(examSearch), 400);
        return () => clearTimeout(t);
    }, [examSearch]);

    const fetchExams = useCallback(async (search: string, page: number) => {
        setExamLoading(true);
        try {
            const res = await API_Instance.get("/exams", { params: { search, page, limit: 10 } });
            const items: { id: string; examName: string }[] = res.data?.data || [];
            setExamList((prev) => {
                if (page === 1) {
                    if (enrolledExamId && enrolledExamName && !items.some((exam) => exam.id === enrolledExamId)) {
                        return [{ id: enrolledExamId, examName: enrolledExamName }, ...items];
                    }
                    return items;
                }
                return [...prev, ...items.filter((item) => !prev.some((exam) => exam.id === item.id))];
            });
            setHasMoreExams(items.length === 10);
        } catch {
            console.error("Failed to fetch exams");
        } finally {
            setExamLoading(false);
        }
    }, [enrolledExamId, enrolledExamName]);

    useEffect(() => {
        setExamPage(1);
        fetchExams(debouncedExamSearch, 1);
    }, [debouncedExamSearch, fetchExams]);

    useEffect(() => {
        if (examPage > 1) fetchExams(debouncedExamSearch, examPage);
    }, [examPage, debouncedExamSearch, fetchExams]);

    useEffect(() => {
        if (!studentId) return;

        const fetchWeeklyTrend = async () => {
            setTrendLoading(true);
            try {
                let trendUrl = "";
                const examParam = localExamId ? `examId=${localExamId}` : "";

                if (testTypeFilter === "PRACTICE") {
                    const subjectParam = selectedSubjectId && selectedSubjectId !== "all" ? `&subjectId=${selectedSubjectId}` : "";
                    trendUrl = `${API_Constants.reports}/${studentId}/practice-test-weekly?${examParam}${subjectParam}`;
                } else if (testTypeFilter === "MOCK") {
                    trendUrl = `${API_Constants.reports}/${studentId}/mock-test-weekly?${examParam}`;
                } else if (testTypeFilter === "PYQ") {
                    trendUrl = `${API_Constants.reports}/${studentId}/pyq-weekly?${examParam}`;
                }

                const trendRes = await API_Instance.get(trendUrl);
                const trendRaw = trendRes.data?.data?.graphData || [];
                setGraphData(trendRaw);

                if (testTypeFilter !== "PRACTICE") {
                    setSecondaryData(trendRaw);
                    setSubjects([]);
                }
            } catch (e) {
                toast.error(getAxiosErrorMessage(e));
            } finally {
                setTrendLoading(false);
            }
        };

        fetchWeeklyTrend();
    }, [studentId, testTypeFilter, selectedSubjectId, localExamId]);

    useEffect(() => {
        if (!studentId) return;
        if (testTypeFilter !== "PRACTICE") return;

        const fetchSecondaryData = async () => {
            setSecondaryLoading(true);
            try {
                const examParam = localExamId ? `&examId=${localExamId}` : "";
                const secondaryUrl = `${API_Constants.reports}/${studentId}/practice-test-subjects?sort=${subjectSort}${examParam}&page=${subjectPage}&limit=${subjectPageSize}`;

                const subRes = await API_Instance.get(secondaryUrl);
                const subRaw: ISubjectPoint[] = subRes.data?.data?.chartData || [];
                const paginationInfo = subRes.data?.pagination;

                setSecondaryData(subRaw);
                if (paginationInfo) {
                    setTotalSubjectPages(paginationInfo.totalPages || 0);
                }

                const subjectList = subRaw
                    .filter((s: any) => s.subjectId)
                    .map((s: any) => ({ 
                        subjectId: s.subjectId, 
                        subject: s.subject,
                        isShared: s.isShared,
                        sharedInstitutionName: s.sharedInstitutionName
                    }));
                setSubjects(subjectList);
            } catch (e) {
                toast.error(getAxiosErrorMessage(e));
            } finally {
                setSecondaryLoading(false);
            }
        };

        fetchSecondaryData();
    }, [studentId, testTypeFilter, subjectSort, localExamId, subjectPage, subjectPageSize]);

    const processedGraphData = useMemo(() => {
        return graphData.map((item) => ({
            ...item,
            displayPercentage: item.percentage === null || item.percentage === undefined ? 0 : item.percentage,
            hasSubmissions: item.percentage !== null && item.percentage !== undefined,
        }));
    }, [graphData]);

    const processedSecondaryData = useMemo(() => {
        return secondaryData.map((item) => ({
            ...item,
            displayPercentage: item.percentage === null || item.percentage === undefined ? 0 : item.percentage,
            hasSubmissions: item.percentage !== null && item.percentage !== undefined,
        }));
    }, [secondaryData]);

    const tabs = [
        { label: "Practice Tests", value: "PRACTICE", activeClass: "bg-brand-blue text-white shadow-md shadow-brand-blue" },
        { label: "Mock Tests", value: "MOCK", activeClass: "bg-brand-blue text-white shadow-md shadow-brand-blue" },
        { label: "PYQs", value: "PYQ", activeClass: "bg-brand-blue text-white shadow-md shadow-brand-blue" },
    ];

    return (
        <div className="flex flex-col gap-6">
            <div className="flex items-center gap-3">
                <Select
                    size="middle"
                    className="w-72"
                    value={localExamId}
                    onChange={(val) => {
                        setLocalExamId(val);
                        setSelectedSubjectId("all");
                        setSubjectPage(1);
                    }}
                    onSearch={(val) => setExamSearch(val)}
                    onDropdownVisibleChange={(open) => { if (!open) setExamSearch(""); }}
                    showSearch
                    filterOption={false}
                    placeholder="Filter by Exam"
                    loading={examLoading}
                    options={examList.map((e) => ({ label: e.examName, value: e.id }))}
                    onPopupScroll={(e) => {
                        const target = e.target as HTMLElement;
                        if (target.scrollTop + target.clientHeight >= target.scrollHeight - 20 && hasMoreExams && !examLoading) {
                            setExamPage((prev) => prev + 1);
                        }
                    }}
                />

                <div className="flex w-1/3 items-center bg-slate-100/80 p-1.5 rounded-xl border border-slate-200/60">
                    {tabs.map((tab) => {
                        const isActive = testTypeFilter === tab.value;
                        return (
                            <button
                                key={tab.value}
                                onClick={() => { setTestTypeFilter(tab.value); setSelectedSubjectId("all"); }}
                                className={`flex-1 text-center py-2 px-4 rounded-lg text-sm font-semibold transition-all duration-200 ${isActive ? tab.activeClass : "text-slate-600 hover:text-slate-900 hover:bg-slate-200/50"}`}
                            >
                                {tab.label}
                            </button>
                        );
                    })}
                </div>
            </div>

            <div className="grid grid-cols-1 xl:grid-cols-2 gap-6 p-1">
                <div className="flex flex-col gap-6">
                    <Card className="shadow-sm border border-slate-200/80 rounded-2xl relative overflow-hidden">
                        {trendLoading && (
                            <div className="absolute inset-0 bg-white/40 backdrop-blur-[1px] z-10 flex items-center justify-center transition-all duration-200">
                                <div className="flex flex-col items-center gap-2">
                                    <span className="w-8 h-8 rounded-full border-2 border-slate-200 border-t-brand-blue animate-spin" />
                                    <span className="text-xs font-medium text-slate-500">Updating trend...</span>
                                </div>
                            </div>
                        )}

                        <div className="flex justify-between items-start mb-6">
                            <div>
                                <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                                    <TrendingUp size={18} className="text-brand-blue" />
                                    Weekly Performance Trend
                                </h3>
                                <p className="text-xs font-medium text-slate-400 mt-0.5">
                                    {testTypeFilter === "PRACTICE" && "Overall Practice Test Performance • Last 90 Days"}
                                    {testTypeFilter === "MOCK" && "Overall Mock Test Insights • Last 90 Days"}
                                    {testTypeFilter === "PYQ" && "Previous Year Papers • Last 90 Days"}
                                </p>
                            </div>
                            <div className="flex items-center gap-2 mt-2">
                                {testTypeFilter === "PRACTICE" && subjects.length > 0 && (
                                    <Select
                                        size="small"
                                        className="w-48"
                                        value={selectedSubjectId}
                                        onChange={(val) => setSelectedSubjectId(val)}
                                        optionLabelProp="name"
                                        options={[
                                            { 
                                                label: "All Subjects", 
                                                name: "All Subjects", 
                                                value: "all" 
                                            },
                                            ...subjects.map((s) => ({ 
                                                label: (
                                                    <div className="flex items-center justify-between w-full gap-2">
                                                        <span className="font-medium text-slate-700 truncate">{s.subject}</span>
                                                        {s.isShared && (
                                                            <span title={`Shared by Exam Infra`}>
                                                                <Share2 size={14} className="text-purple-500 flex-shrink-0" />
                                                            </span>
                                                        )}
                                                    </div>
                                                ),
                                                name: s.subject,
                                                value: s.subjectId 
                                            }))
                                        ]}
                                    />
                                )}
                                <BarChart2 size={20} className="text-slate-300" />
                            </div>
                        </div>

                        {processedGraphData.length === 0 && !trendLoading ? (
                            <div className="h-64 flex items-center justify-center">
                                <Empty description="No performance data available" />
                            </div>
                        ) : (
                            <div style={{ width: "100%", height: 330 }}>
                                <ResponsiveContainer width="100%" height="100%">
                                    <LineChart data={processedGraphData} margin={{ top: 25, right: 20, left: 15, bottom: 40 }}>
                                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                                        <XAxis
                                            dataKey="week"
                                            tickFormatter={(val) => formatWeekLabel(val)}
                                            tick={{ fill: "#94a3b8", fontSize: 11, fontWeight: 500 }}
                                            axisLine={false}
                                            tickLine={false}
                                            dy={10}
                                            label={{ value: "Weeks", position: "bottom", offset: 25, fill: "#64748b", fontSize: 12, fontWeight: 600 }}
                                        />
                                        <YAxis
                                            tick={{ fill: "#94a3b8", fontSize: 11 }}
                                            axisLine={false}
                                            tickLine={false}
                                            domain={[0, 100]}
                                            ticks={[0, 25, 50, 75, 100]}
                                            tickFormatter={(v) => `${v}%`}
                                            label={{ value: "Percentage", angle: -90, position: "left", offset: 10, fill: "#64748b", fontSize: 12, fontWeight: 600 }}
                                        />
                                        <Tooltip content={<ChartTooltip />} cursor={{ stroke: '#f1f5f9', strokeWidth: 2 }} />
                                        <Line
                                            type="monotone"
                                            dataKey="displayPercentage"
                                            name="Percentage %"
                                            stroke="#1677ff"
                                            strokeWidth={3}
                                            connectNulls={true}
                                            isAnimationActive={false}
                                            dot={(props: any) => {
                                                const { cx, cy, payload } = props;
                                                const hasSubmissions = payload?.hasSubmissions;
                                                const value = payload?.displayPercentage;

                                                if (!hasSubmissions || value === null || value === undefined) {
                                                    return (
                                                        <circle
                                                            key={props.key}
                                                            cx={cx}
                                                            cy={cy}
                                                            r={3}
                                                            fill="#cbd5e1"
                                                            stroke="none"
                                                        />
                                                    );
                                                }

                                                return (
                                                    <g key={props.key}>
                                                        <circle
                                                            cx={cx}
                                                            cy={cy}
                                                            r={4}
                                                            fill="#1677ff"
                                                            stroke="#fff"
                                                            strokeWidth={2}
                                                        />
                                                        <text
                                                            x={cx}
                                                            y={cy - 10}
                                                            textAnchor="middle"
                                                            fill="#1677ff"
                                                            fontSize={11}
                                                            fontWeight={700}
                                                        >
                                                            {`${value}%`}
                                                        </text>
                                                    </g>
                                                );
                                            }}
                                            activeDot={{ r: 6, strokeWidth: 0 }}
                                        />
                                    </LineChart>
                                </ResponsiveContainer>
                            </div>
                        )}
                    </Card>
                </div>

                <div className="flex flex-col gap-6">
                    <Card className="shadow-sm border border-slate-200/80 rounded-2xl h-full flex flex-col relative overflow-hidden">

                        {((secondaryLoading) || (testTypeFilter !== "PRACTICE" && trendLoading)) && (
                            <div className="absolute inset-0 bg-white/40 backdrop-blur-[1px] z-10 flex items-center justify-center transition-all duration-200">
                                <div className="flex flex-col items-center gap-2">
                                    <span className="w-8 h-8 rounded-full border-2 border-slate-200 border-t-brand-blue animate-spin" />
                                    <span className="text-xs font-medium text-slate-500">Updating statistics...</span>
                                </div>
                            </div>
                        )}

                        <div className="flex justify-between items-center mb-6">
                            <div>
                                <div className="flex items-center gap-2">
                                    <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                                        <BarChart2 size={18} className="text-brand-blue" />
                                        {testTypeFilter === "PRACTICE" ? "Subject Wise Breakdown" : "Weekly Performance Chart"}
                                    </h3>
                                </div>
                                <p className="text-xs font-medium text-slate-400 mt-0.5">
                                    {testTypeFilter === "PRACTICE" && "Subject-wise Average Scores (90 Days)"}
                                    {testTypeFilter === "MOCK" && "Mock Performance Weight Distribution (90 Days)"}
                                    {testTypeFilter === "PYQ" && "PYQ Progress Bar Distribution (90 Days)"}
                                </p>
                            </div>
                            {testTypeFilter === "PRACTICE" && (
                                <div className="flex items-center gap-2">
                                    <span className="text-xs bg-brand-blue border border-brand-blue text-white font-semibold px-3 py-1.5 rounded-md truncate max-w-[150px]">
                                        {activeExamName}
                                    </span>
                                    <button
                                        onClick={() => {
                                            setSubjectSort(prev => prev === "desc" ? "asc" : "desc");
                                            setSubjectPage(1);
                                        }}
                                        className="flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold text-slate-600 bg-slate-100 hover:bg-slate-200 rounded-lg transition-colors border border-slate-200"
                                    >
                                        {subjectSort === "desc" ? (
                                            <>
                                                <ChartNoAxesColumnDecreasing size={18} /> Highest to Lowest
                                            </>
                                        ) : (
                                            <>
                                                <ChartNoAxesColumnIncreasing size={18} /> Lowest to Highest
                                            </>
                                        )}
                                    </button>
                                </div>
                            )}
                        </div>

                        {processedSecondaryData.length === 0 && !secondaryLoading ? (
                            <div className="flex-1 flex items-center justify-center min-h-[300px]">
                                <Empty description="No analytical metrics captured for this period" />
                            </div>
                        ) : testTypeFilter === "PRACTICE" ? (
                            <div className="flex flex-col gap-0">
                                <div style={{ height: "330px", overflow: "hidden" }}>
                                    <SubjectBarChart
                                        data={processedSecondaryData}
                                    />
                                </div>
                                <div className="flex items-center justify-end px-4 py-3 -mb-6 border-t border-slate-100">
                                    <Pagination
                                        current={subjectPage}
                                        total={totalSubjectPages * subjectPageSize}
                                        pageSize={subjectPageSize}
                                        onChange={(page) => setSubjectPage(page)}
                                        onShowSizeChange={(current, size) => {
                                            setSubjectPageSize(size);
                                            setSubjectPage(1);
                                        }}
                                        showSizeChanger
                                        pageSizeOptions={[5, 10, 15, 20]}
                                        disabled={secondaryLoading}
                                        showQuickJumper={false}
                                    />
                                </div>
                            </div>
                        ) : (
                            <div className="flex-1 min-h-[330px]">
                                <ResponsiveContainer width="100%" height={330}>
                                    <BarChart
                                        data={processedSecondaryData}
                                        margin={{ top: 15, right: 20, left: 15, bottom: 40 }}
                                    >
                                        <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="#f1f5f9" />
                                        <XAxis
                                            dataKey="week"
                                            tickFormatter={(val) => formatWeekLabel(val)}
                                            tick={{ fill: "#94a3b8", fontSize: 11, fontWeight: 500 }}
                                            axisLine={false}
                                            tickLine={false}
                                            dy={10}
                                            label={{ value: "Weeks", position: "bottom", offset: 25, fill: "#64748b", fontSize: 12, fontWeight: 600 }}
                                        />
                                        <YAxis
                                            tick={{ fill: "#94a3b8", fontSize: 11 }}
                                            axisLine={false}
                                            tickLine={false}
                                            domain={[0, 100]}
                                            ticks={[0, 25, 50, 75, 100]}
                                            tickFormatter={(v) => `${v}%`}
                                            label={{ value: "Percentage", angle: -90, position: "left", offset: 10, fill: "#64748b", fontSize: 12, fontWeight: 600 }}
                                        />
                                        <Tooltip content={<ChartTooltip isSubject={false} />} cursor={{ fill: "#f8fafc" }} />
                                        <Bar
                                            dataKey="displayPercentage"
                                            name="Percentage %"
                                            fill="#1677ff"
                                            radius={[6, 6, 0, 0]}
                                            maxBarSize={50}
                                            isAnimationActive={false}
                                        >
                                            {processedSecondaryData.map((entry, index) => (
                                                <Cell
                                                    key={`cell-${index}`}
                                                    fill={entry.hasSubmissions ? "#1677ff" : "transparent"}
                                                />
                                            ))}
                                            <LabelList
                                                dataKey="displayPercentage"
                                                position="insideTop"
                                                offset={8}
                                                fill="#ffffff"
                                                fontSize={11}
                                                fontWeight={600}
                                                formatter={(value: number) => value > 0 ? `${value}%` : ""}
                                            />
                                        </Bar>
                                    </BarChart>
                                </ResponsiveContainer>
                            </div>
                        )}
                    </Card>
                </div>
            </div>
        </div>
    );
};

export default OverviewTab;