import toast from "react-hot-toast";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { Card, Pagination, Skeleton, Empty } from "antd";
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { BookOpen, ChartNoAxesColumnDecreasing, ChartNoAxesColumnIncreasing, Share2 } from "lucide-react";

interface ISubjectPerformance {
    subjectId: string;
    subjectName: string;
    percentage: number | null;
}

interface PracticeTestSubjectPerformanceProps {
    selectedExamId: string;
    selectedExamName: string;
}

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

const SubjectBarChart: React.FC<{ data: any[] }> = ({ data }) => {
    const maxPercentage = 100;

    if (!data || data.length === 0) {
        return (
            <div className="flex items-center justify-center h-full">
                <Empty description="No analytical metrics captured for this period" />
            </div>
        );
    }

    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: "1px 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",
                                }}
                            >
                                <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 hasAttempts = !!item.hasAttempts;

                    const rowTitle = hasAttempts ? `${percentage}%` : "No submissions";

                    return (
                        <div
                            key={`subject-${index}`}
                            title={rowTitle}
                            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.subjectName}
                                >
                                    <div className="flex items-center gap-1.5">
                                        {item.isShared && (
                                            <span title={`Shared by Exam Infra`} className="flex-shrink-0 flex items-center">
                                                <Share2 size={12} className="text-purple-500" />
                                            </span>
                                        )}
                                        <span className="truncate">{item.subjectName}</span>
                                    </div>
                                </div>
                            </div>

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

const PracticeTestSubjectPerformance: React.FC<PracticeTestSubjectPerformanceProps> = ({ selectedExamId, selectedExamName }) => {
    const [data, setData] = useState<ISubjectPerformance[]>([]);
    const [loading, setLoading] = useState(false);

    const [page, setPage] = useState(1);
    const [limit, setLimit] = useState(5);
    const [total, setTotal] = useState(0);
    const [sortOrder, setSortOrder] = useState<"desc" | "asc">("desc");

    const fetchData = useCallback(async () => {
        if (!selectedExamId) {
            setData([]);
            setTotal(0);
            return;
        }

        setLoading(true);
        try {
            const res = await API_Instance.get(`${API_Constants.reports}/overall/practice-test-subjects`, {
                params: {
                    examId: selectedExamId,
                    page,
                    limit,
                    sortOrder
                }
            });
            setData(res.data?.data || []);
            setTotal(res.data?.pagination?.totalSubjects || 0);
        } catch (e) {
            toast.error(getAxiosErrorMessage(e));
        } finally {
            setLoading(false);
        }
    }, [selectedExamId, page, limit, sortOrder]);

    useEffect(() => {
        fetchData();
    }, [fetchData]);

    const toggleSortOrder = () => {
        setSortOrder((prev) => (prev === "desc" ? "asc" : "desc"));
        setPage(1);
    };

    const processedData = useMemo(() => {
        return data.map((item) => ({
            ...item,
            displayPercentage: item.percentage === null ? 0 : item.percentage,
            hasAttempts: item.percentage !== null,
        }));
    }, [data]);

    return (
        <div className="w-full">
            <Card className="shadow-sm border border-slate-200/80 rounded-2xl w-full">
                <div className="flex flex-col md:flex-row justify-between items-start md:items-center mb-6 gap-4">
                    <div>
                        <h3 className="text-lg font-bold text-slate-800 flex items-center gap-2">
                            <BookOpen size={18} className="text-[#1677ff]" />
                            Subject-Wise Performance Analysis ( All Students )
                        </h3>
                        <p className="text-xs font-medium text-slate-400 mt-0.5">
                            Overall Practice Test Performance by Subject • Last 90 Days
                        </p>
                        {selectedExamName && (
                            <p className="text-xs font-semibold text-indigo-600 mt-2 uppercase tracking-wide bg-indigo-50 px-2.5 py-1 rounded-md w-fit">
                                Exam: {selectedExamName}
                            </p>
                        )}
                    </div>

                    <div className="flex flex-row items-center gap-3 w-full md:w-auto justify-end">
                        {selectedExamId && (
                            <button
                                type="button"
                                onClick={toggleSortOrder}
                                className={`inline-flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-xl border text-xs font-semibold transition-all duration-200 cursor-pointer select-none whitespace-nowrap shadow-sm h-8
                                    ${sortOrder === "desc"
                                        ? "bg-indigo-50/70 text-indigo-600 border-indigo-200/80 hover:bg-indigo-100/80"
                                        : "bg-rose-50/70 text-rose-600 border-rose-200/80 hover:bg-rose-100/80"
                                    }`}
                            >
                                {sortOrder === "desc" ? (
                                    <>
                                        <ChartNoAxesColumnDecreasing size={18} /> Highest to Lowest
                                    </>
                                ) : (
                                    <>
                                        <ChartNoAxesColumnIncreasing size={18} /> Lowest to Highest
                                    </>
                                )}
                            </button>
                        )}
                    </div>
                </div>

                {!selectedExamId ? (
                    <div className="h-64 flex flex-col items-center justify-center text-slate-400 gap-2">
                        <BookOpen size={48} className="text-slate-200" />
                        <p>Please select an exam to view subject performance.</p>
                    </div>
                ) : loading ? (
                    <div className="p-4">
                        <Skeleton active paragraph={{ rows: 6 }} />
                    </div>
                ) : processedData.length === 0 ? (
                    <div className="h-64 flex items-center justify-center">
                        <Empty description="No subject data available" />
                    </div>
                ) : (
                    <div className="flex flex-col gap-0">
                        <div style={{ height: "330px", overflow: "hidden" }}>
                            <SubjectBarChart
                                data={processedData}
                            />
                        </div>
                        <div className="flex items-center justify-end px-4 py-3 border-t border-slate-100">
                            <Pagination
                                current={page}
                                total={total}
                                pageSize={limit}
                                onChange={(p) => setPage(p)}
                                onShowSizeChange={(current, size) => {
                                    setLimit(size);
                                    setPage(1);
                                }}
                                showSizeChanger
                                pageSizeOptions={[5, 10, 50, 100]}
                                disabled={loading}
                                showQuickJumper={false}
                            />
                        </div>
                    </div>
                )}
            </Card>
        </div>
    );
};

export default PracticeTestSubjectPerformance;