import React, { useEffect, useState } from "react";
import { ClipboardClock, CirclePlus, Link, Search } from "lucide-react";
import { Button, Empty, Input, Modal as AntModal, Select, Popconfirm, Spin, Switch, Tag, Tooltip, Card, Table } from "antd";
import { Accordion, AccordionRow } from "../shared/Accordion";
import { Pagination } from "antd";
import { CheckCircle, ChevronDown, ChevronRight, ClipboardList, Clock, Info, Pencil, Trash2, Unlink } from "lucide-react";
import { difficultyColor, getAxiosErrorMessage } from "@/utils/index.utils";
import { Difficulty, IExam, IQuestion, ITest } from "@/types";
import { API_Instance } from "@/api/axios.instance";
import API_Constants from "@/constants/api.constants";
import dayjs from "dayjs";
import toast from "react-hot-toast";
import { useNavigate } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { useDebounce } from "@/hooks/useDebounce";

const initialPagination = {
  page: 1,
  limit: 10,
  total: 0,
  totalPages: 0,
};

const filterInitial = {
  testSearch: "",
  questionSearch: "",
};

export const TestTreeCard = ({
  exam,
  isOpen,
  onToggle,
}: {
  exam: IExam;
  isOpen?: boolean;
  onToggle?: () => void;
}) => {
  const [openTestId, setOpenTestId] = useState<string | null>(null);
  const [openQuestionId, setOpenQuestionId] = useState<string | null>(null);
  const [tests, setTests] = useState<ITest[]>([]);
  const [questions, setQuestions] = useState<IQuestion[]>([]);
  const [testPagination, setTestPagination] = useState(initialPagination);
  const [questionPagination, setQuestionPagination] =
    useState(initialPagination);
  const [loading, setLoading] = useState(false);
  const [topicLoading, setTopicLoading] = useState(false);
  const [filterValues, setFilterValues] = useState(filterInitial);
  const debouncedTestSearch = useDebounce(filterValues.testSearch, 600);
  const debouncedQuestionSearch = useDebounce(filterValues.questionSearch, 600);
  const navigate = useNavigate();

  // Map Test Modal State
  const [isMapModalOpen, setIsMapModalOpen] = useState(false);
  const [selectedTestIds, setSelectedTestIds] = useState<string[]>([]);
  const [mapLoading, setMapLoading] = useState(false);
  const [mapTestsLoading, setMapTestsLoading] = useState(false);
  const [mapLoadingMore, setMapLoadingMore] = useState(false);
  const [mapFilter, setMapFilter] = useState<"all" | "used" | "available">("all");
  const [mapPage, setMapPage] = useState(1);
  const [mapLimit, setMapLimit] = useState(10);
  const [mapTotal, setMapTotal] = useState(0);
  const [mapHasMore, setMapHasMore] = useState(false);
  const [mapOptions, setMapOptions] = useState<any[]>([]);
  const [subjectsList, setSubjectsList] = useState<any[]>([]);
  const [selectedSubjectId, setSelectedSubjectId] = useState<string | undefined>(undefined);
  const [mapStats, setMapStats] = useState<{ totalCount: number; mappedCount: number; availableCount: number } | null>(null);
  const [selectedTests, setSelectedTests] = useState<any[]>([]);

  const handleTestSelectionChange = (newIds: string[]) => {
    setSelectedTestIds(newIds);
    const updated = [...selectedTests];
    newIds.forEach((id) => {
      if (!updated.some((u) => u.id === id)) {
        const found = mapOptions.find((opt) => opt.id === id);
        if (found) {
          updated.push(found);
        }
      }
    });
    const filtered = updated.filter((u) => newIds.includes(u.id));
    setSelectedTests(filtered);
  };

  const handleRemoveSelectedTest = (testId: string) => {
    const newIds = selectedTestIds.filter(id => id !== testId);
    setSelectedTestIds(newIds);
    setSelectedTests(prev => prev.filter(t => t.id !== testId));
  };

  const toggleTest = (testId: string) => {
    const isSame = openTestId === testId;

    if (isSame) {
      setOpenTestId(null);
      setOpenQuestionId(null);
      setQuestions([]);
      return;
    }

    setOpenTestId(testId);
    setQuestions([]);
    setFilterValues((prev) => ({ ...prev, questionSearch: "" }));
    setQuestionPagination(initialPagination);
    getQuestions(1, initialPagination.limit, testId);
  };

  const toggleQuestion = (id: string) => {
    const isSame = openQuestionId === id;
    setOpenQuestionId(isSame ? null : id);
  };

  const getTests = async (
    page: number = initialPagination.page,
    limit: number = initialPagination.limit,
    search: string = debouncedTestSearch,
  ) => {
    setTopicLoading(true);
    try {
      const response = await API_Instance.get(
        `${API_Constants.practiceTests}?page=${page}&limit=${limit}&exam=${exam.id}&search=${search}`,
      );
      const data = await response.data;
      setTests(data.data || []);
      setTestPagination(data.meta || initialPagination);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setTopicLoading(false);
    }
  };

  const getQuestions = async (
    page: number = initialPagination.page,
    limit: number = initialPagination.limit,
    testId: string,
  ) => {
    if (!testId) return;
    setLoading(true);
    try {
      const response = await API_Instance.get(
        `${API_Constants.practiceTests}/questions/${testId}`,
        {
          params: {
            page,
            limit,
            search: debouncedQuestionSearch,
          },
        },
      );
      const data = response.data;
      setQuestions(data.questions || []);
      setQuestionPagination(data.meta || initialPagination);
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setLoading(false);
    }
  };

  const handlePublishToggle = async (id: string, publish: boolean) => {
    try {
      await API_Instance.put(`${API_Constants.practiceTests}/${id}`, {
        publish,
      });
      toast.success(
        `Test ${publish ? "published" : "un-published"} successfully`,
      );
      getTests(testPagination.page, testPagination.limit, debouncedTestSearch);
    } catch (error: any) {
      toast.error(getAxiosErrorMessage(error));
    }
  };

  const handleUnmapTest = async (id: string) => {
    try {
      await API_Instance.delete(`${API_Constants.practiceTests}/${id}`);
      toast.success("Test unmapped successfully");
      getTests(testPagination.page, testPagination.limit, debouncedTestSearch);
    } catch (error: any) {
      toast.error(getAxiosErrorMessage(error));
    }
  };

  const loadMapTests = async (
    page = 1,
    limit = mapLimit,
    filter: "all" | "used" | "available" = mapFilter,
    append = false,
    subjectId: string | null | undefined = selectedSubjectId,
  ) => {
    if (page === 1 && !append) {
      setMapOptions([]);
      setSelectedTestIds([]);
    }

    if (page === 1) {
      setMapTestsLoading(true);
    } else {
      setMapLoadingMore(true);
    }

    try {
      const testsRes = await API_Instance.get(API_Constants.tests, {
        params: {
          page,
          limit,
          examId: exam.id,
          mapped: filter,
          subjectId: subjectId === null ? undefined : (subjectId || undefined),
        },
      });

      const fetchedTests = testsRes.data.data || [];
      const meta = testsRes.data.meta || {};
      const stats = testsRes.data.stats || null;

      setMapOptions((prev) => (append ? [...prev, ...fetchedTests] : fetchedTests));
      setMapPage(meta.page || page);
      setMapLimit(limit);
      setMapTotal(meta.total || 0);
      setMapHasMore((meta.page || page) * limit < (meta.total || 0));
      if (stats) {
        setMapStats(stats);
      }
    } catch (error) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setMapTestsLoading(false);
      setMapLoadingMore(false);
    }
  };

  const loadMapSubjects = async (filter: string) => {
    try {
      const subRes = await API_Instance.get(API_Constants.subjects, {
        params: { page: 1, limit: 100, includeShared: true, testExamId: exam.id, mapFilter: filter }
      });
      setSubjectsList(subRes.data.data || subRes.data || []);
    } catch (err) {
      console.error("Failed to load subjects for mapping modal", err);
    }
  };

  const openMapModal = async () => {
    setSelectedTestIds([]);
    setSelectedTests([]);
    setIsMapModalOpen(true);
    setMapFilter("all");
    setSelectedSubjectId(undefined);
    setMapStats(null);
    setMapPage(1);
    setMapTotal(0);
    setMapHasMore(false);
    setMapOptions([]);

    await loadMapSubjects("all");

    await loadMapTests(1, 10, "all", false, undefined);
  };

  const handleMapTest = async () => {
    if (!selectedTestIds || selectedTestIds.length === 0) {
      toast.error("Please select at least one test to map");
      return;
    }
    setMapLoading(true);
    try {
      await Promise.all(
        selectedTestIds.map(testId => 
          API_Instance.post(
            `${API_Constants.practiceTests}/map-test-to-exam`,
            { testId, examId: exam.id }
          )
        )
      );
      toast.success("Tests mapped successfully!");
      setIsMapModalOpen(false);
      getTests(testPagination.page, testPagination.limit, debouncedTestSearch);
    } catch (error: any) {
      toast.error(getAxiosErrorMessage(error));
    } finally {
      setMapLoading(false);
    }
  };

  useEffect(() => {
    getQuestions(
      questionPagination?.page || initialPagination.page,
      questionPagination?.limit || initialPagination.limit,
      openTestId!,
    );
  }, [debouncedQuestionSearch, openTestId]);

  useEffect(() => {
    if (isOpen) {
      getTests(1, testPagination?.limit || initialPagination.limit, debouncedTestSearch);
    }
  }, [debouncedTestSearch, isOpen]);

  return (
    <>
    <Accordion
      defaultExpanded={false}
      leftIcon={<ClipboardClock size={24} />}
      title={
        <div>
          <h2 className="text-md font-semibold text-slate-900">
            {exam.examName}
          </h2>
          <p className="text-xs text-slate-500 mt-0.5 flex items-center gap-2">
            <span>{exam.testCount} Tests</span>
          </p>
        </div>
      }
      rightActions={
        <div
          className="flex items-center gap-1 pl-2 border-slate-200 ml-2"
          onClick={(e) => e.stopPropagation()}
        >
          <Button
            type="primary"
            ghost
            onClick={openMapModal}
          >
            Map Test
          </Button>
          {/* <Button
            onClick={() =>
              navigate(ROUTE_CONSTANTS.PracticeTestCreate, {
                state: { examId: exam.id, examName: exam.examName },
              })
            }
          >
            Add New Test
          </Button> */}
        </div>
      }
      isOpen={isOpen}
      onToggle={() => {
        onToggle();
        setOpenTestId(null);
        setOpenQuestionId(null);
        setQuestions([]);
        setFilterValues(filterInitial);

        if (!isOpen) {
          // If opening
          // getTests(); // Handled by useEffect now
        }
      }}
      content={
        <>
          <div className="mt-2 flex gap-3 items-end w-[18rem]">
            <Input
              placeholder={"Search Tests"}
              prefix={<Search size={16} />}
              autoComplete="off"
              allowClear
              value={filterValues.testSearch}
              onChange={(e) => {
                setFilterValues({
                  ...filterValues,
                  testSearch: e.target.value,
                });
              }}
            />
          </div>

          <Spin spinning={topicLoading}>
            {(!tests || tests.length === 0) && !topicLoading ? (
              <div className="min-h-[100px] flex items-center justify-center">
                <Empty
                  description={
                    debouncedTestSearch
                      ? "No tests found for your search"
                      : "No tests available"
                  }
                />
              </div>
            ) : (
              <div className="pt-4 pl-2 border-l-2 border-slate-200 ml-6 space-y-1">
                {tests && tests.length > 0 &&
                  tests.map((test) => (
                    <AccordionRow
                      key={test.id}
                      title={
                        <div className="w-full flex items-center justify-between gap-3">
                          <div className="flex items-center gap-2">
                            <h2 className="text-md font-semibold text-slate-900">
                              {test.title}
                            </h2>
                            <p className="text-xs text-slate-500 mt-0.5 flex items-center gap-2">
                              <span>{test.questions?.length || 0} Questions</span>
                            </p>
                            {(test as any).referenceSourceId && (
                              <span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 flex items-center gap-1 shrink-0 ml-2">
                                <Link size={10} />
                                Shared by Exam Infra
                              </span>
                            )}
                          </div>

                          {/* Action Buttons */}
                          <div
                            className="flex items-center gap-1 pl-2 border-l border-slate-200 ml-2"
                            onClick={(e) => e.stopPropagation()}
                          >
                            <Switch
                              checkedChildren="Published"
                              unCheckedChildren="Yet to publish"
                              checked={test.publish}
                              onChange={(val) =>
                                handlePublishToggle(test.id, val)
                              }
                            />
                            {/* <button
                              className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
                              title="Edit Test"
                              onClick={() =>
                                navigate(ROUTE_CONSTANTS.PracticeTestEdit, {
                                  state: {
                                    ...test,
                                    examId: exam.id,
                                    examName: exam.examName,
                                  },
                                })
                              }
                            >
                              <Pencil size={15} />
                            </button>
                            <Popconfirm
                              title="Are you sure you want to delete this test?"
                              onConfirm={() => handleDeleteTest(test.id)}
                              okText="Yes"
                              cancelText="No"
                            >
                              <button
                                className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 rounded-xl transition-colors"
                                title="Delete Test"
                              >
                                <Trash2 size={15} />
                              </button>
                            </Popconfirm> */}
                            <Popconfirm
                              title="Are you sure you want to unmap this test?"
                              onConfirm={() => handleUnmapTest(test.id)}
                              okText="Yes"
                              cancelText="No"
                              disabled={test.hasResults}
                            >
                              <Tooltip title={test.hasResults ? "Cannot unmap this test because students have already taken it." : ""}>
                                <div style={{ display: 'inline-block' }}>
                                  <Button
                                    type="text"
                                    danger
                                    size="small"
                                    disabled={test.hasResults}
                                    className={`text-xs font-semibold border rounded ${test.hasResults ? 'border-red-200 text-red-300' : 'border-red-500'}`}
                                  >
                                    Unmap
                                  </Button>
                                </div>
                              </Tooltip>
                            </Popconfirm>
                          </div>
                        </div>
                      }
                      isOpen={openTestId === test.id}
                      onToggle={() => {
                        toggleTest(test.id);
                      }}
                      disabled={test.questions.length === 0}
                      content={
                        <>
                          <div className="mt-2 flex gap-3 items-end w-[18rem]">
                            <Input
                              placeholder={"Search Questions"}
                              prefix={<Search size={16} />}
                              autoComplete="off"
                              allowClear
                              value={filterValues.questionSearch}
                              onChange={(e) => {
                                setFilterValues({
                                  ...filterValues,
                                  questionSearch: e.target.value,
                                });
                              }}
                            />
                          </div>
                          <Spin spinning={loading}>
                            {questions.length === 0 && !loading ? (
                              <div className="min-h-[100px] flex items-center justify-center">
                                <Empty
                                  description={
                                    debouncedQuestionSearch
                                      ? "No question found for your search"
                                      : "No question available"
                                  }
                                />
                              </div>
                            ) : (
                              <>
                                {questions?.length > 0 &&
                                  questions?.map((q) => {
                                    const isQuestionOpen =
                                      openQuestionId === q.id;
                                    return (
                                      <AccordionRow
                                        key={q.id}
                                        hideIcon
                                        className="bg-white shadow-sm border border-slate-100 overflow-hidden my-2"
                                        title={
                                          <div
                                            className={`
                                  flex items-center gap-4 p-0 cursor-pointer transition-colors duration-200
                                `}
                                          >
                                            <div className="text-slate-400 transition-transform duration-200">
                                              {isQuestionOpen ? (
                                                <ChevronDown size={14} />
                                              ) : (
                                                <ChevronRight size={14} />
                                              )}
                                            </div>

                                            {/* Content Grid - Matching Header from App.tsx */}
                                            <div className="flex-1 grid grid-cols-1 xl:grid-cols-12 gap-4 items-center">
                                              {/* Question Text Column */}
                                              <div className="xl:col-span-4 flex items-center gap-3">
                                                <div className="hidden sm:flex items-center justify-center p-1 rounded bg-slate-100 text-brand-blue shrink-0">
                                                  <ClipboardList size={20} />
                                                </div>
                                                <h3
                                                  className={`text-sm font-medium text-left leading-relaxed line-clamp-1 ${
                                                    isQuestionOpen
                                                      ? "text-brand-blue"
                                                      : "text-slate-700"
                                                  }`}
                                                >
                                                  {q.questionText}
                                                </h3>
                                              </div>

                                              {/* Metadata Columns */}
                                              <div className="xl:col-span-8 flex flex-wrap xl:justify-end items-center gap-x-3 gap-y-2 mt-2 xl:mt-0">
                                                {/* Subject */}
                                                {q.subject && (
                                                  <span className="text-[11px] px-2 py-0.5 rounded bg-purple-50 text-purple-600 border border-purple-100">
                                                    {typeof q.subject ===
                                                    "object"
                                                      ? (q.subject as any)
                                                          .subjectName
                                                      : q.subject}
                                                  </span>
                                                )}

                                                {/* Topic */}
                                                {q.topic && (
                                                  <span className="text-[11px] px-2 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100">
                                                    {q.topic}
                                                  </span>
                                                )}

                                                {/* Language */}
                                                {q.language && (
                                                  <span className="text-[11px] px-2 py-0.5 rounded bg-amber-50 text-amber-600 border border-amber-100">
                                                    {q.language}
                                                  </span>
                                                )}

                                                {/* Last Updated */}
                                                {q.updatedAt && (
                                                  <div className="hidden 2xl:flex items-center gap-1.5 text-[11px] text-slate-400 min-w-[80px] justify-end">
                                                    <Clock size={12} />
                                                    <span>
                                                      {dayjs(
                                                        q.updatedAt,
                                                      ).format("DD-MM-YYYY")}
                                                    </span>
                                                  </div>
                                                )}

                                                {/* Difficulty Badge */}
                                                <span
                                                  className={`text-[10px] px-2.5 py-0.5 rounded-full font-semibold border min-w-[60px] text-center ${difficultyColor(
                                                    q.difficulty === "Easy"
                                                      ? Difficulty.Easy
                                                      : q.difficulty ===
                                                          "Medium"
                                                        ? Difficulty.Medium
                                                        : Difficulty.Hard,
                                                  )}`}
                                                >
                                                  {q.difficulty}
                                                </span>
                                              </div>
                                            </div>
                                          </div>
                                        }
                                        isOpen={openQuestionId === q.id}
                                        onToggle={() => toggleQuestion(q.id)}
                                        content={
                                          <div className="pt-2 pb-6 px-4 sm:px-8 bg-slate-50 border-t border-slate-100">
                                            <div className="mb-4 flex flex-col items-start gap-2">
                                              <div className="text-sm font-medium text-left leading-relaxed text-slate-700 text-wrap">
                                                {q.questionText}
                                              </div>
                                              {q.questionImage && (
                                                <img
                                                  src={q.questionImage}
                                                  alt="Question Image"
                                                  className="h-[5rem] object-contain rounded-md mt-2"
                                                />
                                              )}
                                            </div>
                                            <div className="space-y-3">
                                              {q.options.map((option, idx) => {
                                                const isCorrect =
                                                  idx === q.correctAnswer;

                                                let optionClass =
                                                  "w-full text-left p-3 rounded-xl border text-sm font-medium flex justify-between items-center transition-all duration-200 cursor-default ";

                                                if (isCorrect) {
                                                  optionClass +=
                                                    "bg-green-50 border-green-500 text-green-800 shadow-sm ring-1 ring-green-500/20";
                                                } else {
                                                  optionClass +=
                                                    "bg-white border-slate-200 text-slate-500 opacity-80";
                                                }

                                                return (
                                                  <div
                                                    key={idx}
                                                    className={optionClass}
                                                  >
                                                    <div className="flex items-center gap-3">
                                                      <span
                                                        className={`flex items-center justify-center w-6 h-6 rounded-full text-xs font-bold border ${
                                                          isCorrect
                                                            ? "border-green-600 bg-green-100 text-green-700"
                                                            : "border-slate-300 bg-slate-50 text-slate-500"
                                                        }`}
                                                      >
                                                        {String.fromCharCode(
                                                          65 + idx,
                                                        )}
                                                      </span>
                                                      {option.option !== "" && (
                                                        <span>
                                                          {option.option}
                                                        </span>
                                                      )}
                                                      {option.optionImage && (
                                                        <img
                                                          src={
                                                            option.optionImage
                                                          }
                                                          alt="Option Image"
                                                          className="h-[5rem] w-auto object-contain rounded-xl ml-5"
                                                        />
                                                      )}
                                                    </div>
                                                    {isCorrect && (
                                                      <CheckCircle
                                                        className="text-green-600"
                                                        size={18}
                                                      />
                                                    )}
                                                  </div>
                                                );
                                              })}
                                            </div>

                                            <div className="mt-6 space-y-4">
                                              <div className="p-4 rounded-xl border bg-blue-50 border-blue-100">
                                                <h4 className="text-xs font-bold uppercase tracking-wider mb-2 flex items-center gap-2 text-blue-700">
                                                  <Info size={14} />
                                                  Explanation
                                                </h4>
                                                <p className="text-sm text-slate-700 leading-relaxed font-medium whitespace-pre-line">
                                                  {q.explanation}
                                                </p>
                                                {q.explanationImage && (
                                                  <img
                                                    src={q.explanationImage}
                                                    alt="Explanation Image"
                                                    className="h-[5rem] w-auto object-contain rounded-xl ml-5"
                                                  />
                                                )}
                                              </div>
                                            </div>
                                          </div>
                                        }
                                      />
                                    );
                                  })}

                                {/* Pagination */}
                                <div className="flex justify-end pb-2">
                                  <Pagination
                                    current={questionPagination.page || 1}
                                    total={questionPagination.total}
                                    pageSize={questionPagination.limit}
                                    onChange={(p, pageSize) => {
                                      setQuestionPagination({
                                        ...questionPagination,
                                        page: p,
                                        limit: pageSize,
                                      });
                                      getQuestions(p, pageSize, openTestId!);
                                    }}
                                    showSizeChanger
                                  />
                                </div>
                              </>
                            )}
                          </Spin>
                        </>
                      }
                    />
                  ))}
                <div className="flex justify-end pb-2">
                  <Pagination
                    current={testPagination.page}
                    total={testPagination.total}
                    pageSize={testPagination.limit}
                    onChange={(p, pageSize) => {
                      setTestPagination({
                        ...testPagination,
                        page: p,
                        limit: pageSize,
                      });
                      getTests(p, pageSize);
                    }}
                    showSizeChanger
                  />
                </div>
              </div>
            )}
          </Spin>
        </>
      }
    />
    
    {/* Map Test Modal */}
    <AntModal
      title={
        <div className="flex items-center gap-2">
          <CirclePlus className="text-brand-blue" size={20} />
          <span>Map Test to Practice Test ( {exam.examName} )</span>
        </div>
      }
      open={isMapModalOpen}
      onCancel={() => setIsMapModalOpen(false)}
      onOk={handleMapTest}
      okText="Map Test"
      confirmLoading={mapLoading}
      okButtonProps={{ disabled: !selectedTestIds || selectedTestIds.length === 0, className: "bg-brand-blue" }}
      width={1000}
      centered
      className="custom-modal"
    >
      <div className="py-4 space-y-5">
          {/* Stats Cards */}
          <div className="grid grid-cols-3 gap-4">
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                Total Tests
              </div>
              <div className="text-2xl font-bold text-slate-700 mt-1">
                {mapStats ? mapStats.totalCount : 0}
              </div>
            </Card>
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                Already Mapped Tests
              </div>
              <div className="text-2xl font-bold text-brand-blue mt-1">
                {mapStats ? mapStats.mappedCount : 0}
              </div>
            </Card>
            <Card size="small" className="bg-[#f8fafc] border-slate-100 rounded-xl shadow-sm text-center">
              <div className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                Available Tests
              </div>
              <div className="text-2xl font-bold text-emerald-600 mt-1">
                {mapStats ? mapStats.availableCount : 0}
              </div>
            </Card>
          </div>
          <div className="grid grid-cols-2 gap-4">
        <div>
          <label className="text-sm font-semibold text-slate-700 mb-1.5 block">Filter Status</label>
          <Select
            placeholder="Select filter..."
            className="w-full"
            value={mapFilter}
            allowClear
            options={[
              { value: "all", label: "All Tests" },
              { value: "used", label: "Already Mapped Tests" },
              { value: "available", label: "Available Tests" },
            ]}
            onChange={(value) => {
              setMapFilter(value);
              loadMapSubjects(value || "all");
              loadMapTests(1, 10, value, false, selectedSubjectId);
            }}
          />
        </div>
        <div>
          <label className="text-sm font-semibold text-slate-700 mb-1.5 block">Filter Subject</label>
          <Select
            placeholder="Select subject..."
                className="w-full"
                value={selectedSubjectId}
                allowClear
                showSearch
                optionFilterProp="label"
                options={subjectsList.map((sub: any) => ({
                  value: sub.id,
                  label: sub.subjectName,
                }))}
                onChange={(value) => {
                  setSelectedSubjectId(value);
                  loadMapTests(1, 10, mapFilter, false, value || null);
                }}
              />
            </div>
        </div>
        <div>
          <label className="text-sm font-semibold text-slate-700 mb-1.5 block">Select Tests to Map</label>
          <Select
            mode="multiple"
            placeholder="Search and select tests..."
            className="w-full mb-4"
            loading={mapTestsLoading}
            value={selectedTestIds}
            onChange={handleTestSelectionChange}
            allowClear
            virtual={true}
            listHeight={350}
            showSearch
            optionFilterProp="title"
            optionLabelProp="title"
            filterOption={(input, option) =>
              (option?.title ?? "").toLowerCase().includes(input.toLowerCase())
            }
            onPopupScroll={(e) => {
              const target = e.currentTarget;
              const reachedBottom = target.scrollTop + target.offsetHeight >= target.scrollHeight - 8;
              if (reachedBottom && mapHasMore && !mapTestsLoading && !mapLoadingMore) {
                loadMapTests(mapPage + 1, 10, mapFilter, true, selectedSubjectId);
              }
            }}
            options={mapOptions.map((test: any) => ({
              value: test.id,
              disabled: test.isAlreadyMapped,
              title: test.title,
              label: (
                <div className="flex items-center justify-between w-full pr-2 py-1">
                  <div className="flex items-center gap-2 truncate">
                    <span className="truncate font-medium text-slate-700">{test.title}</span>
                    {test.referenceSourceId && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-blue-50 text-blue-600 border border-blue-100 flex items-center gap-1 shrink-0">
                        <Link size={10} />
                        Shared by Exam Infra
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 shrink-0">
                    {test.subject?.subjectName && (
                      <span className="px-2 py-0.5 text-[10px] font-medium text-slate-600 bg-slate-100 border border-slate-200/60 rounded shrink-0">
                        {test.subject.subjectName}
                      </span>
                    )}
                    {test.isAlreadyMapped && (
                      <span className="text-[10px] px-1.5 py-0.5 rounded bg-amber-50 text-amber-600 border border-amber-100 shrink-0">
                        Already Mapped
                      </span>
                    )}
                  </div>
                </div>
              ),
            }))}
          />

            {selectedTests.length > 0 && (
              <div>
                <label className="text-sm font-semibold text-slate-700 mb-1.5 block">Selected Tests ({selectedTests.length})</label>
                <Table
                  dataSource={selectedTests}
                  rowKey="id"
                  pagination={{
                    pageSizeOptions: ["10", "20"],
                    showSizeChanger: true,
                    defaultPageSize: 10,
                  }}
                  size="small"
                  columns={[
                    {
                      title: "Test Name",
                      dataIndex: "title",
                      key: "title",
                      render: (text: string, record: any) => (
                        <div className="flex flex-col gap-0.5">
                          <span className="font-semibold text-slate-800">{text}</span>
                          {record.referenceSourceId && (
                            <span className="text-[9px] text-blue-600 bg-blue-50 border border-blue-100 rounded px-1 py-0.2 w-fit flex items-center gap-0.5">
                              <Link size={8} />
                              Shared by Exam Infra
                            </span>
                          )}
                        </div>
                      ),
                    },
                    {
                      title: "Subject",
                      dataIndex: ["subject", "subjectName"],
                      key: "subject",
                      render: (subName: string) => subName || "N/A",
                    },
                    {
                      title: "Question Count",
                      dataIndex: ["_count", "testQuestions"],
                      key: "questions",
                      render: (count: number) => `${count || 0} Qs`,
                    },
                    {
                      title: "Duration",
                      dataIndex: "duration",
                      key: "duration",
                      render: (dur: number) => dur ? `${dur} mins` : "N/A",
                    },
                    {
                      title: "Action",
                      key: "action",
                      render: (_, record: any) => (
                        <Button
                          type="text"
                          danger
                          size="small"
                          onClick={() => handleRemoveSelectedTest(record.id)}
                        >
                          Remove
                        </Button>
                      ),
                    },
                  ]}
                />
              </div>
            )}
        </div>
      </div>
    </AntModal>
    </>
  );
};

