import dayjs from "dayjs";
import toast from "react-hot-toast";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import React, { useEffect, useMemo, useState } from "react";
import { ArrowLeft, FileText, UploadCloud, ExternalLink, BookOpen, Plus, Trash2, Download, Edit2, Search } from "lucide-react";
import { Button, Form, Modal, Pagination, Select, Table, Tabs, Tag, Typography, Card, Popconfirm, Space, Spin, Tooltip, Input } from "antd";

import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import NotesAndLinksUpload from "./NotesAndLinksUpload";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import { useDebounce } from "@/hooks/useDebounce";
import ROUTE_CONSTANTS from "@/constants/route.constants";

const { Text } = Typography;

const NotesAndLinksSubjectPage: React.FC = () => {
    const { subjectId } = useParams<{ subjectId: string }>();
    const navigate = useNavigate();

    const [subject, setSubject] = useState<any>(null);
    const [pdfMaterials, setPdfMaterials] = useState<any[]>([]);
    const [linkMaterials, setLinkMaterials] = useState<any[]>([]);
    const [allExams, setAllExams] = useState<any[]>([]);
    const [selectedExamId, setSelectedExamId] = useState<string | null>(null);
    const [searchParams, setSearchParams] = useSearchParams();
    const activeTab = searchParams.get("tab") || "pdf-notes";

    const [loadingSubject, setLoadingSubject] = useState(false);
    const [loadingMaterials, setLoadingMaterials] = useState(false);
    const [loadingExams, setLoadingExams] = useState(false);
    const [assigningExam, setAssigningExam] = useState(false);

    const [modalOpen, setModalOpen] = useState(false);
    const [uploadType, setUploadType] = useState<"pdf" | "link">("pdf");
    const [loadingUpload, setLoadingUpload] = useState(false);
    const [fileList, setFileList] = useState<any[]>([]);
    const [pdfPage, setPdfPage] = useState(1);
    const [pdfPageSize, setPdfPageSize] = useState(10);
    const [linkPage, setLinkPage] = useState(1);
    const [linkPageSize, setLinkPageSize] = useState(10);
    const [examPage, setExamPage] = useState(1);
    const [examPageSize, setExamPageSize] = useState(10);

    const [editModalOpen, setEditModalOpen] = useState(false);
    const [editingItem, setEditingItem] = useState<any>(null);
    const [loadingEdit, setLoadingEdit] = useState(false);

    const [reasonModalOpen, setReasonModalOpen] = useState(false);
    const [selectedRejectedItem, setSelectedRejectedItem] = useState<any>(null);

    const [reportModalOpen, setReportModalOpen] = useState(false);
    const [selectedReportItem, setSelectedReportItem] = useState<any>(null);
    const [selectedReports, setSelectedReports] = useState<any[]>([]);
    const [loadingReports, setLoadingReports] = useState(false);

    const [verificationFilter, setVerificationFilter] = useState<string>("");
    const [pdfSearchText, setPdfSearchText] = useState("");
    const [linkSearchText, setLinkSearchText] = useState("");

    const debouncedPdfSearch = useDebounce(pdfSearchText, 600);
    const debouncedLinkSearch = useDebounce(linkSearchText, 600);

    const [pdfForm] = Form.useForm();
    const [linkForm] = Form.useForm();
    const [editForm] = Form.useForm();

    const fetchSubject = async () => {
        if (!subjectId) return;
        setLoadingSubject(true);
        try {
            const res = await API_Instance.get(`${API_Constants.subjects}/${subjectId}`);
            setSubject(res.data);
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setLoadingSubject(false);
        }
    };

    const fetchPdfMaterials = async (search = debouncedPdfSearch) => {
        if (!subjectId) return;
        setLoadingMaterials(true);
        try {
            const params: Record<string, any> = {
                subjectId,
                limit: 100,
                search,
                type: "PDF",
            };
            const res = await API_Instance.get(API_Constants.notesLinks, { params });
            setPdfMaterials(res.data.data || []);
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setLoadingMaterials(false);
        }
    };

    const fetchLinkMaterials = async (search = debouncedLinkSearch) => {
        if (!subjectId) return;
        setLoadingMaterials(true);
        try {
            const params: Record<string, any> = {
                subjectId,
                limit: 100,
                search,
                type: "LINK",
            };
            const res = await API_Instance.get(API_Constants.notesLinks, { params });
            setLinkMaterials(res.data.data || []);
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setLoadingMaterials(false);
        }
    };

    const fetchMaterials = () => {
        fetchPdfMaterials();
        fetchLinkMaterials();
    };

    const fetchExams = async () => {
        setLoadingExams(true);
        try {
            const res = await API_Instance.get(`${API_Constants.exams}?limit=100`);
            setAllExams(res.data.data || []);
        } catch (_err) {
            setAllExams([]);
        } finally {
            setLoadingExams(false);
        }
    };

    useEffect(() => {
        fetchSubject();
        fetchExams();
    }, [subjectId]);

    useEffect(() => {
        fetchPdfMaterials(debouncedPdfSearch);
    }, [debouncedPdfSearch, subjectId]);

    useEffect(() => {
        fetchLinkMaterials(debouncedLinkSearch);
    }, [debouncedLinkSearch, subjectId]);

    const handleOpenUploadModal = (type: "pdf" | "link") => {
        setUploadType(type);
        setFileList([]);
        pdfForm.resetFields();
        linkForm.resetFields();
        setModalOpen(true);
    };

    const handleOpenReasonModal = (item: any) => {
        setSelectedRejectedItem(item);
        setReasonModalOpen(true);
    };

    const handleOpenReportsModal = async (item: any) => {
        if (!item?.id) return;
        setSelectedReportItem(item);
        setReportModalOpen(true);
        setLoadingReports(true);
        try {
            const res = await API_Instance.get(`${API_Constants.notesLinks}/${item.id}`);
            setSelectedReports(res.data?.data?.reports || []);
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
            setSelectedReports([]);
        } finally {
            setLoadingReports(false);
        }
    };

    const filteredLinkMaterials = useMemo(
        () =>
            linkMaterials.filter((item) =>
                verificationFilter ? item.verification === verificationFilter : true
            ),
        [linkMaterials, verificationFilter]
    );

    const totalPdfFiles = useMemo(() => {
        return pdfMaterials.reduce((acc, curr) => {
            let count = 0;
            if (Array.isArray(curr.files) && curr.files.length > 0) {
                count = curr.files.length;
            } else if (curr.fileUrl) {
                if (Array.isArray(curr.fileUrl)) {
                    count = curr.fileUrl.length;
                } else {
                    count = 1;
                }
            }
            return acc + count;
        }, 0);
    }, [pdfMaterials]);

    const paginatedPdfMaterials = useMemo(
        () => pdfMaterials.slice((pdfPage - 1) * pdfPageSize, pdfPage * pdfPageSize),
        [pdfMaterials, pdfPage, pdfPageSize]
    );

    const paginatedLinkMaterials = useMemo(
        () => filteredLinkMaterials.slice((linkPage - 1) * linkPageSize, linkPage * linkPageSize),
        [filteredLinkMaterials, linkPage, linkPageSize]
    );

    const mappedExams = useMemo(() => {
        return subject?.exams || subject?.assignedExams || [];
    }, [subject]);

    const paginatedMappedExams = useMemo(
        () => mappedExams.slice((examPage - 1) * examPageSize, examPage * examPageSize),
        [mappedExams, examPage, examPageSize]
    );

    const availableExamsToMap = useMemo(() => {
        const mappedIds = new Set(mappedExams.map((e: any) => e.id));
        return allExams.filter((exam) => !mappedIds.has(exam.id) && exam.isPublished === true);
    }, [allExams, mappedExams]);

    const handleAssignExam = async () => {
        if (!selectedExamId || !subjectId) return;

        const hasContent = pdfMaterials.length > 0 || linkMaterials.length > 0;

        if (!hasContent) {
            toast.error(
                "Cannot publish to exam! This subject must have at least one note or link before publishing."
            );
            return;
        }

        setAssigningExam(true);
        try {
            const existingExamIds = mappedExams.map((exam) => exam.id);
            const nextExamIds = Array.from(new Set([...existingExamIds, selectedExamId]));

            await API_Instance.put(`${API_Constants.subjects}/${subjectId}`, {
                examIds: nextExamIds,
            });

            toast.success("Subject published to exam successfully.");
            setSelectedExamId(null);
            fetchSubject();
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setAssigningExam(false);
        }
    };

    const handleUnassignExam = async (examIdToUnassign: string) => {
        if (!subjectId) return;
        try {
            const nextExamIds = mappedExams
                .filter((exam) => exam.id !== examIdToUnassign)
                .map((exam) => exam.id);

            await API_Instance.put(`${API_Constants.subjects}/${subjectId}`, {
                examIds: nextExamIds,
            });

            toast.success("Exam publish removed successfully.");
            fetchSubject();
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        }
    };

    const handleDeleteMaterial = async (id: string) => {
        try {
            await API_Instance.delete(`${API_Constants.notesLinks}/${id}`);
            toast.success("Material deleted successfully.");
            fetchMaterials();
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        }
    };

    const handleOpenEdit = (item: any) => {
        setEditingItem(item);
        editForm.setFieldsValue({
            title: item.title,
        });
        setEditModalOpen(true);
    };

    const handleEditSubmit = async (values: any) => {
        if (!editingItem) return;
        setLoadingEdit(true);
        try {
            await API_Instance.put(`${API_Constants.notesLinks}/${editingItem.id}`, {
                title: values.title,
            });
            toast.success("Updated successfully.");
            setEditModalOpen(false);
            fetchMaterials();
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setLoadingEdit(false);
        }
    };

    const handleUploadSubmit = async (values: any) => {
        if (!subjectId) return;
        setLoadingUpload(true);
        try {
            if (uploadType === "pdf") {
                if (!fileList.length) {
                    toast.error("Please choose a PDF file to upload.");
                    setLoadingUpload(false);
                    return;
                }
                const file = fileList[0].originFileObj;
                const formData = new FormData();
                formData.append("title", values.title);
                formData.append("subjectId", subjectId);
                formData.append("type", "PDF");
                formData.append("file", file);

                await API_Instance.post(API_Constants.notesLinks, formData, {
                    headers: { "Content-Type": "multipart/form-data" },
                });
                toast.success("PDF uploaded successfully.");
            } else {
                await API_Instance.post(API_Constants.notesLinks, {
                    title: values.title,
                    type: "LINK",
                    linkUrl: values.linkUrl,
                    subjectId,
                });
                toast.success("Link submitted successfully.");
            }
            setModalOpen(false);
            fetchMaterials();
        } catch (err) {
            toast.error(getAxiosErrorMessage(err));
        } finally {
            setLoadingUpload(false);
        }
    };

    const pdfColumns = [
        {
            title: "Title",
            dataIndex: "title",
            key: "title",
            className: "!pl-4",
            render: (title: string) => (
                <div className="max-w-[250px] truncate text-sm font-medium text-slate-800" title={title}>
                    {title || "Untitled"}
                </div>
            ),
        },
        {
            title: "Files",
            dataIndex: "files",
            key: "files",
            render: (_: any, record: any) => {
                const extractFileName = (pathOrUrl: string) => {
                    if (!pathOrUrl) return null;
                    const name = pathOrUrl.split(/[\/\\]/).pop();
                    return name ? decodeURIComponent(name) : null;
                };

                const files = Array.isArray(record.files) && record.files.length > 0 
                  ? record.files 
                  : (record.fileUrl ? [{ name: record.fileName || extractFileName(record.fileUrl) || "Document.pdf", url: record.fileUrl }] : []);
                
                if (files.length === 0) return <span className="text-xs text-slate-400">No files</span>;

                return (
                    <div className="flex flex-col gap-2 max-w-[320px]">
                        {files.map((file: any, idx: number) => {
                           const finalFileName = file.name || extractFileName(file.url) || "Document.pdf";
                           
                           const publicFileUrl = (() => {
                               if (!file.url) return "";
                               const cleaned = file.url.replace(/\\/g, "/").replace(/^\.\/+/g, "").replace(/^\/+/g, "").replace(/\//g, "/");
                               const uploadsIndex = cleaned.lastIndexOf("uploads/");
                               const pathSegment = uploadsIndex !== -1 ? `/${cleaned.substring(uploadsIndex)}` : cleaned.startsWith("/") ? cleaned : `/${cleaned}`;
                               return new URL(pathSegment, window.location.origin).toString();
                           })();

                           return (
                             <div key={idx} className="flex items-center justify-between gap-2 border border-slate-100 rounded p-1 bg-slate-50">
                               <div className="truncate text-sm font-medium text-slate-700 flex items-center gap-2">
                                   <FileText size={16} className="text-red-500 shrink-0" />
                                   <span title={finalFileName} className="truncate font-mono text-xs">
                                       {finalFileName}
                                   </span>
                               </div>
                               <a
                                   href={publicFileUrl}
                                   download
                                   target="_blank"
                                   rel="noreferrer"
                                   className="text-blue-600 hover:text-blue-800 p-1"
                                   title="Download"
                               >
                                   <Download size={14} />
                               </a>
                             </div>
                           );
                        })}
                    </div>
                );
            },
        },
        {
            title: "Topics",
            dataIndex: "topics",
            key: "topics",
            render: (topics: any) => {
                const topicsList = Array.isArray(topics) ? topics : [];
                if (topicsList.length === 0) return <span className="text-xs text-slate-400">No topics</span>;
                return (
                    <div className="flex flex-wrap gap-1 max-w-[200px]">
                        {topicsList.map((t: string, i: number) => (
                            <span key={i} className="px-2 py-0.5 bg-blue-50 text-blue-600 rounded text-[10px] font-medium border border-blue-100">
                                {t}
                            </span>
                        ))}
                    </div>
                );
            },
        },
        {
            title: "Uploaded On",
            dataIndex: "createdAt",
            key: "createdAt",
            render: (_, record) => (
                <span className="text-xs text-slate-500 italic">
                    {dayjs(record.createdAt).format("DD-MM-YYYY HH:mm:ss A")}
                </span>
            ),
        },
        // {
        //     title: "Student Reports",
        //     key: "studentReports",
        //     render: (_: any, record: any) => {
        //         const reportCount = record._count?.reports || record.reportsCount || 0;
        //         if (!reportCount) {
        //             return <span className="text-xs text-slate-400">0</span>;
        //         }

        //         return (
        //             <Button
        //                 type="link"
        //                 size="small"
        //                 className="p-0 h-auto text-blue-600"
        //                 onClick={() => handleOpenReportsModal(record)}
        //             >
        //                 {reportCount} Report{reportCount > 1 ? "s" : ""}
        //             </Button>
        //         );
        //     },
        // },
        {
            title: "Actions",
            key: "actions",
            render: (_: any, record: any) => {
                return (
                    <Space size="small">

                        <Tooltip title={record.verification === "REJECTED" ? "Rejected files cannot be edited" : "Edit"}>
                            <span>
                                <Button
                                    type="default"
                                    size="small"
                                    icon={<Edit2 size={14} />}
                                    onClick={() => handleOpenEdit(record)}
                                    className="flex items-center justify-center p-1.5"
                                    disabled={record.verification === "REJECTED"}
                                />
                            </span>
                        </Tooltip>

                        <Tooltip title={record.verification === "REJECTED" ? "Rejected files cannot be deleted" : "Delete"}>
                            <span>
                                {record.verification === "REJECTED" ? (
                                    <Button
                                        type="default"
                                        danger
                                        size="small"
                                        icon={<Trash2 size={14} />}
                                        className="flex items-center justify-center p-1.5"
                                        disabled={true}
                                    />
                                ) : (
                                    <Popconfirm
                                        title="Delete PDF"
                                        description="Are you sure you want to delete this PDF?"
                                        onConfirm={() => handleDeleteMaterial(record.id)}
                                        okText="Yes, Delete"
                                        cancelText="Cancel"
                                        okButtonProps={{ danger: true }}
                                    >
                                        <Button
                                            type="default"
                                            danger
                                            size="small"
                                            icon={<Trash2 size={14} />}
                                            className="flex items-center justify-center p-1.5"
                                        />
                                    </Popconfirm>
                                )}
                            </span>
                        </Tooltip>
                    </Space>
                );
            }
        }
    ]

    const linkColumns = [
        {
            title: "Title",
            dataIndex: "title",
            key: "title",
            className: "!pl-4",
            render: (title: string) => (
                <div className="max-w-[320px] truncate text-sm font-medium text-slate-800">
                    {title}
                </div>
            ),
        },
        {
            title: "URL",
            dataIndex: "linkUrl",
            key: "linkUrl",
            render: (linkUrl: string) => (
                <div className="max-w-[200px] truncate text-sm">
                    {linkUrl ? (
                        <a href={linkUrl} target="_blank" rel="noreferrer" className="text-blue-600 hover:underline" title={linkUrl}>
                            {linkUrl}
                        </a>
                    ) : (
                        <span className="text-slate-400">No URL</span>
                    )}
                </div>
            ),
        },
        {
            title: "Topics",
            dataIndex: "topics",
            key: "topics",
            render: (topics: any) => {
                const topicsList = Array.isArray(topics) ? topics : [];
                if (topicsList.length === 0) return <span className="text-xs text-slate-400">No topics</span>;
                return (
                    <div className="flex flex-wrap gap-1 max-w-[200px]">
                        {topicsList.map((t: string, i: number) => (
                            <span key={i} className="px-2 py-0.5 bg-blue-50 text-blue-600 rounded text-[10px] font-medium border border-blue-100">
                                {t}
                            </span>
                        ))}
                    </div>
                );
            },
        },
        {
            title: "Admin Verification",
            dataIndex: "verification",
            key: "verification",
            render: (verification: string, record: any) => {
                if (mappedExams.length === 0) {
                    return (
                        <span className="text-xs text-slate-400 italic">Not published yet</span>
                    );
                }

                if (verification === "REJECTED") {
                    return (
                        <div className="flex flex-col items-start gap-1">
                            <Tag color="red" className="rounded-full px-2.5 py-0.5 text-xs font-semibold">
                                REJECTED
                            </Tag>
                            <button
                                type="button"
                                onClick={() => handleOpenReasonModal(record)}
                                className="text-[11px] text-blue-600 hover:underline font-medium cursor-pointer"
                            >
                                View Details
                            </button>
                        </div>
                    );
                }

                return (
                    <Tag
                        className="rounded-full px-3 py-1 text-xs font-semibold"
                        color={verification === "VERIFIED" ? "green" : "orange"}
                    >
                        {verification || "PENDING"}
                    </Tag>
                );
            },
        },
        {
            title: "Uploaded On",
            dataIndex: "createdAt",
            key: "createdAt",
            render: (_, record) => (
                <span className="text-xs text-slate-500 italic">
                    {dayjs(record.createdAt).format("DD-MM-YYYY HH:mm:ss A")}
                </span>
            ),
        },
        // {
        //     title: "Student Reports",
        //     key: "studentReports",
        //     render: (_: any, record: any) => {
        //         const reportCount = record._count?.reports || record.reportsCount || 0;
        //         if (!reportCount) {
        //             return <span className="text-xs text-slate-400">0</span>;
        //         }
        //         return (
        //             <Button
        //                 type="link"
        //                 size="small"
        //                 className="p-0 h-auto text-blue-600"
        //                 onClick={() => handleOpenReportsModal(record)}
        //             >
        //                 {reportCount} Report{reportCount > 1 ? "s" : ""}
        //             </Button>
        //         );
        //     },
        // },
        {
            title: "Actions",
            key: "actions",
            render: (_: any, record: any) => (
                <Space size="small">
                    <a
                        href={record.linkUrl}
                        target="_blank"
                        rel="noreferrer"
                        className="inline-flex items-center justify-center text-blue-600 hover:text-blue-800 border border-blue-200 bg-white p-1.5 rounded-md"
                        title="Open Link"
                    >
                        <ExternalLink size={14} />
                    </a>

                    <Tooltip title={record.verification === "REJECTED" ? "Rejected links cannot be edited" : "Edit"}>
                        <span>
                            <Button
                                type="default"
                                size="small"
                                icon={<Edit2 size={14} />}
                                onClick={() => handleOpenEdit(record)}
                                className="flex items-center justify-center p-1.5"
                                disabled={record.verification === "REJECTED"}
                            />
                        </span>
                    </Tooltip>

                    <Tooltip title={record.verification === "REJECTED" ? "Rejected link cannot be deleted" : "Delete"}>
                        <span>
                            {record.verification === "REJECTED" ? (
                                <Button
                                    type="default"
                                    danger
                                    size="small"
                                    icon={<Trash2 size={14} />}
                                    className="flex items-center justify-center p-1.5"
                                    disabled={true}
                                />
                            ) : (
                                <Popconfirm
                                    title="Delete Link"
                                    description="Are you sure you want to delete this link?"
                                    onConfirm={() => handleDeleteMaterial(record.id)}
                                    okText="Yes, Delete"
                                    cancelText="Cancel"
                                    okButtonProps={{ danger: true }}
                                >
                                    <Button
                                        type="default"
                                        danger
                                        size="small"
                                        icon={<Trash2 size={14} />}
                                        className="flex items-center justify-center p-1.5"
                                    />
                                </Popconfirm>
                            )}
                        </span>
                    </Tooltip>
                </Space>
            ),
        },
    ];

    const mappedExamColumns = [
        {
            title: "Exam Name",
            dataIndex: "examName",
            key: "examName",
            className: "!pl-4",
            render: (text: string, record: any) => (
                <span className="font-semibold text-slate-800">
                    {text || record.title || record.name}
                </span>
            ),
        },
        {
            title: "Action",
            key: "action",
            render: (_: any, record: any) => (
                <Popconfirm
                    title="Remove Exam"
                    description="Are you sure you want to remove?"
                    onConfirm={() => handleUnassignExam(record.id)}
                    okText="Yes, Remove"
                    cancelText="Cancel"
                    okButtonProps={{ danger: true }}
                >
                    <Button
                        type="text"
                        danger
                        icon={<Trash2 size={16} />}
                        className="flex items-center gap-1 text-red-500 hover:text-red-700 hover:bg-red-50"
                    >
                        Remove
                    </Button>
                </Popconfirm>
            ),
        },
    ];

    return (
        <div className="flex flex-col gap-4 px-4 py-6">
            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
                        <Button
                            type="text"
                            icon={<ArrowLeft size={22} />}
                            onClick={() => navigate(ROUTE_CONSTANTS.NotesAndLinks)}
                            className="!w-12 !h-12 rounded-full bg-white shadow-sm border border-slate-200 text-slate-600 p-0 hover:bg-slate-50 hover:text-blue-600 hover:border-blue-200 transition-all shrink-0"
                            title="Back"
                            classNames={{ icon: "flex items-center justify-center" }}
                        />
                        <BookOpen className="text-blue-600" />{" "}
                        {loadingSubject ? "Loading..." : subject?.subjectName || "Subject Details"}
                    </h2>
                    <p className="text-slate-500 text-sm mt-1">
                        Manage study materials and publish materials to exams.
                    </p>
                </div>
            </div>

            <Card className="shadow-sm border border-slate-200 rounded-xl">
                <Tabs
                    defaultActiveKey="materials"
                    items={[
                        {
                            key: "materials",
                            label: "Subject Materials",
                            children: (
                                <Tabs
                                    type="card"
                                    activeKey={activeTab}
                                    onChange={(key) => setSearchParams({ tab: key })}
                                    items={[
                                        {
                                            key: "pdf-notes",
                                            label: `PDF Notes ( ${totalPdfFiles} )`,
                                            children: (
                                                <div className="space-y-4 pt-2">
                                                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                                        <div>
                                                            <h3 className="text-base font-semibold text-slate-800">
                                                                Search PDF Notes
                                                            </h3>
                                                            <p className="text-xs text-slate-500">
                                                                Search titles of PDF notes uploaded for this subject.
                                                            </p>
                                                        </div>

                                                        <div className="flex flex-col sm:flex-row items-center gap-3 w-full sm:w-auto mt-4 sm:mt-0">
                                                            <Input
                                                                placeholder="Search title..."
                                                                value={pdfSearchText}
                                                                onChange={(e) => {
                                                                    setPdfSearchText(e.target.value);
                                                                    setPdfPage(1); // Reset page on search
                                                                }}
                                                                prefix={<Search className="text-slate-400" size={16} />}
                                                                className="w-full sm:w-64"
                                                                allowClear
                                                            />
                                                            <Button
                                                                type="primary"
                                                                icon={<UploadCloud size={16} />}
                                                                onClick={() => handleOpenUploadModal("pdf")}
                                                                className="bg-blue-600 hover:bg-blue-700 rounded-lg h-9 flex items-center gap-2 font-medium w-full sm:w-auto"
                                                            >
                                                                Upload PDF
                                                            </Button>
                                                        </div>
                                                    </div>

                                                    <Table
                                                        dataSource={paginatedPdfMaterials}
                                                        columns={pdfColumns}
                                                        rowKey="id"
                                                        loading={loadingMaterials}
                                                        pagination={false}
                                                        scroll={{ x: 800 }}
                                                        size="middle"
                                                        locale={{
                                                            emptyText: "No PDF notes available for this subject.",
                                                        }}
                                                    />
                                                    <div className="flex justify-end mt-4">
                                                        <Pagination
                                                            current={pdfPage}
                                                            total={pdfMaterials.length}
                                                            pageSize={pdfPageSize}
                                                            onChange={(page, pageSize) => {
                                                                setPdfPage(page);
                                                                setPdfPageSize(pageSize);
                                                            }}
                                                            showSizeChanger
                                                            pageSizeOptions={["10", "20", "50", "100"]}
                                                            showTotal={(total) => `Total ${total} items`}
                                                        />
                                                    </div>
                                                </div>
                                            ),
                                        },
                                        {
                                            key: "resource-links",
                                            label: `Resource Links ( ${filteredLinkMaterials.length} )`,
                                            children: (
                                                <div className="space-y-4 pt-2">
                                                    <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
                                                        <div>
                                                            <h3 className="text-base font-semibold text-slate-800">
                                                                External Links Search
                                                            </h3>
                                                            <p className="text-xs text-slate-500">
                                                                Search and review external links submitted for this subject.
                                                            </p>
                                                        </div>

                                                        <div className="flex flex-col sm:flex-row items-center gap-3 w-full sm:w-auto mt-4 sm:mt-0">
                                                            <Input
                                                                placeholder="Search title..."
                                                                value={linkSearchText}
                                                                onChange={(e) => {
                                                                    setLinkSearchText(e.target.value);
                                                                    setLinkPage(1); // Reset page on search
                                                                }}
                                                                prefix={<Search className="text-slate-400" size={16} />}
                                                                className="w-full sm:w-64"
                                                                allowClear
                                                            />
                                                            <Select
                                                                value={verificationFilter}
                                                                onChange={(v) => { setVerificationFilter(v); }}
                                                                className="w-40"
                                                                options={[
                                                                    { label: "All", value: "" },
                                                                    { label: "Pending", value: "PENDING" },
                                                                    { label: "Verified", value: "VERIFIED" },
                                                                    { label: "Rejected", value: "REJECTED" },
                                                                ]}
                                                                placeholder="Filter by status"
                                                            />
                                                            <Button
                                                                type="primary"
                                                                icon={<Plus size={16} />}
                                                                onClick={() => handleOpenUploadModal("link")}
                                                                className="bg-blue-600 hover:bg-blue-700 rounded-lg h-9 flex items-center gap-2 font-medium self-start sm:self-auto"
                                                            >
                                                                Add Link
                                                            </Button>
                                                        </div>
                                                    </div>

                                                    <Table
                                                        dataSource={paginatedLinkMaterials}
                                                        columns={linkColumns}
                                                        rowKey="id"
                                                        loading={loadingMaterials}
                                                        pagination={false}
                                                        scroll={{ x: 800 }}
                                                        size="middle"
                                                        locale={{
                                                            emptyText: "No links available for this subject.",
                                                        }}
                                                    />
                                                    <div className="flex justify-end mt-4">
                                                        <Pagination
                                                            current={linkPage}
                                                            total={filteredLinkMaterials.length}
                                                            pageSize={linkPageSize}
                                                            onChange={(page, pageSize) => {
                                                                setLinkPage(page);
                                                                setLinkPageSize(pageSize);
                                                            }}
                                                            showSizeChanger
                                                            pageSizeOptions={["10", "20", "50", "100"]}
                                                            showTotal={(total) => `Total ${total} items`}
                                                        />
                                                    </div>
                                                </div>
                                            ),
                                        },
                                    ]}
                                />
                            ),
                        },
                        {
                            key: "exams",
                            label: `Published To ( ${mappedExams.length} )`,
                            children: (
                                <div className="space-y-6">
                                    <div className="flex flex-col md:flex-row md:items-center justify-between gap-4 p-4 bg-slate-50 border border-slate-200 rounded-xl">
                                        <div>
                                            <h3 className="text-base font-semibold text-slate-800">
                                                Publish with New Exam
                                            </h3>
                                            <p className="text-xs text-slate-500">
                                                Select an exam to link this subject and its resources.
                                            </p>
                                        </div>

                                        <div className="flex items-center gap-2 w-full md:w-auto">
                                            <Select
                                                placeholder="Select Exam to Publish to..."
                                                value={selectedExamId}
                                                onChange={(val) => setSelectedExamId(val)}
                                                options={availableExamsToMap.map((exam) => ({
                                                    label: exam.examName || exam.title,
                                                    value: exam.id,
                                                }))}
                                                loading={loadingExams}
                                                allowClear
                                                className="w-full md:w-80 h-10 rounded-lg"
                                            />
                                            <Button
                                                type="primary"
                                                icon={<Plus size={16} />}
                                                onClick={handleAssignExam}
                                                loading={assigningExam}
                                                disabled={!selectedExamId}
                                                className="bg-blue-600 hover:bg-blue-700 font-medium w-full md:w-auto h-10 px-6 rounded-lg shadow-sm"
                                            >
                                                Publish to Exam
                                            </Button>
                                        </div>
                                    </div>

                                    <div>
                                        <h3 className="text-base font-semibold text-slate-800 mb-2">
                                            Currently Published Exams
                                        </h3>
                                        <Table
                                            dataSource={paginatedMappedExams}
                                            columns={mappedExamColumns}
                                            rowKey="id"
                                            loading={loadingSubject}
                                            pagination={false}
                                            size="middle"
                                            locale={{ emptyText: "Not published to any exams yet." }}
                                            className="border border-slate-200 rounded-xl overflow-hidden"
                                        />
                                        <div className="flex justify-end pt-4 border-t border-slate-100">
                                            <Pagination
                                                current={examPage}
                                                pageSize={examPageSize}
                                                total={mappedExams.length}
                                                showSizeChanger
                                                pageSizeOptions={["10", "20", "50", "100"]}
                                                onChange={(newPage, newSize) => {
                                                    setExamPage(newPage);
                                                    setExamPageSize(newSize);
                                                }}
                                                showTotal={(totalItems, range) =>
                                                    `${range[0]}-${range[1]} of ${totalItems} published exams`
                                                }
                                            />
                                        </div>
                                    </div>
                                </div>
                            ),
                        },
                    ]}
                />
            </Card>

            <Modal
                title={uploadType === "pdf" ? "Upload PDF Note" : "Add Resource Link"}
                open={modalOpen}
                onCancel={() => setModalOpen(false)}
                footer={null}
                width={550}
                destroyOnClose
            >
                <div className="mt-4">
                    <NotesAndLinksUpload
                        subjectId={subjectId!}
                        subjectTopics={subject?.topics || []}
                        onSuccess={() => {
                            setModalOpen(false);
                            fetchMaterials();
                        }}
                        onCancel={() => setModalOpen(false)}
                        defaultTab={uploadType}
                    />
                </div>
            </Modal>

            {/* Admin rejected reason modal  */}
            <Modal
                open={reasonModalOpen}
                onCancel={() => setReasonModalOpen(false)}
                footer={null}
                width={380}
                centered
            >
                <div className="pt-2 space-y-3">
                    <div>
                        <h3 className="text-base font-semibold text-slate-800">Rejection Details</h3>
                        <p className="text-xs text-slate-400">Admin feedback for this submission</p>
                    </div>

                    <div className="bg-red-50 border border-red-100 rounded-lg p-3">
                        <span className="text-[10px] font-bold text-red-600 uppercase tracking-wider block mb-1">
                            Reason
                        </span>
                        <p className="text-xs font-medium text-red-900 leading-relaxed break-words">
                            {selectedRejectedItem?.rejectReason ||
                                selectedRejectedItem?.rejectedReason ||
                                selectedRejectedItem?.reason ||
                                "No reason specified by admin."}
                        </p>
                    </div>

                    <div className="flex items-center justify-between text-[11px] text-slate-500 bg-slate-50 p-2.5 rounded-lg border border-slate-100">
                        <span>
                            <strong className="text-slate-700">Date:</strong>{" "}
                            {selectedRejectedItem?.updatedAt
                                ? dayjs(selectedRejectedItem.updatedAt).format("DD MMM YYYY")
                                : "N/A"}
                        </span>
                        <span>
                            <strong className="text-slate-700">Time:</strong>{" "}
                            {selectedRejectedItem?.updatedAt
                                ? dayjs(selectedRejectedItem.updatedAt).format("hh:mm A")
                                : "N/A"}
                        </span>
                    </div>
                </div>
            </Modal>

            <Modal
                title={
                    <div className="flex items-center gap-2 text-blue-600">
                        <FileText size={18} />
                        <span>Student Reports</span>
                    </div>
                }
                open={reportModalOpen}
                onCancel={() => setReportModalOpen(false)}
                footer={[
                    <Button key="close" type="primary" onClick={() => setReportModalOpen(false)}>
                        Close
                    </Button>
                ]}
                width={650}
            >
                <div className="space-y-3 pt-2">
                    <div className="bg-blue-50 border border-blue-200 rounded-lg px-3 py-2 text-xs text-blue-800">
                        <span className="font-semibold">Material:</span>{" "}
                        {selectedReportItem?.title || "Untitled"}
                    </div>

                    {loadingReports ? (
                        <div className="py-8 flex justify-center">
                            <Spin />
                        </div>
                    ) : selectedReports.length === 0 ? (
                        <div className="text-sm text-slate-500">No student reports available for this material.</div>
                    ) : (
                        <div className="space-y-3 max-h-[420px] overflow-y-auto pr-1">
                            {selectedReports.map((report: any, index: number) => {
                                const studentName = [
                                    report?.student?.user?.firstName,
                                    report?.student?.user?.lastName,
                                ]
                                    .filter(Boolean)
                                    .join(" ") || report?.student?.user?.email || "Unknown Student";

                                return (
                                    <div key={report.id || index} className="border border-slate-200 rounded-lg p-3 bg-slate-50">
                                        <div className="flex items-center justify-between gap-2 mb-2">
                                            <div className="flex flex-col gap-1">
                                                <span className="text-xs font-semibold text-slate-700 uppercase tracking-wide">
                                                    Student Report #{index + 1}
                                                </span>
                                                <span className="text-xs text-slate-600">
                                                    <span className="font-medium">Student:</span> {studentName}
                                                </span>
                                            </div>
                                            <span className="text-[11px] text-slate-500">
                                                {report.createdAt ? dayjs(report.createdAt).format("DD MMM YYYY, hh:mm A") : "N/A"}
                                            </span>
                                        </div>
                                        <p className="text-sm text-slate-700 leading-relaxed">
                                            {report.message || "No message provided."}
                                        </p>
                                    </div>
                                );
                            })}
                        </div>
                    )}
                </div>
            </Modal>

            <Modal
                title="Edit Material"
                open={editModalOpen}
                onCancel={() => setEditModalOpen(false)}
                footer={null}
                width={550}
                destroyOnClose
            >
                <div className="mt-4">
                    {editingItem && (
                        <NotesAndLinksUpload
                            subjectId={subjectId!}
                            subjectTopics={subject?.topics || []}
                            initialData={editingItem}
                            onSuccess={() => {
                                setEditModalOpen(false);
                                fetchMaterials();
                            }}
                            onCancel={() => setEditModalOpen(false)}
                        />
                    )}
                </div>
            </Modal>
        </div>
    );
};

export default NotesAndLinksSubjectPage;