import * as yup from "yup";
import toast from "react-hot-toast";
import { useEffect, useState, useCallback } from "react";
import Modal from "@/components/shared/Modal";
import { useDebounce } from "@/hooks/useDebounce";
import { yupResolver } from "@hookform/resolvers/yup";
import { API_Instance } from "../../api/axios.instance";
import API_Constants from "../../constants/api.constants";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import QuestionCard from "@/components/shared/QuestionCard";
import { useLocation, useNavigate } from "react-router-dom";
import { useForm, Controller, Resolver } from "react-hook-form";
import { getAxiosErrorMessage, getOptionLabel } from "@/utils/index.utils";
import { ExamFormValues, IOptionsList, IQuestion } from "@/types";
import { fetchLanguageOptions } from "@/hooks/useLanguageOptions";
import { Check, CheckCircle, Clock, Eye, Hash, RotateCcw, Search, Shuffle, Trash2, Wand2 } from "lucide-react";
import { Button, Form, Input, Select, Card, Col, Row, Tag, Pagination, Steps, Alert, Spin } from "antd";

const filterInitial = {
  subject: undefined,
  topic: [],
  difficulty: undefined,
  exam: undefined,
  language: "English",
  search: "",
  usageFilter: "all" as "all" | "used" | "available",
};

const initialFormValues = {
  title: "",
  exam: "",
  language: "English",
  questions: [],
  marks: 0,
  duration: 30,
};

const testMapSchema = yup.object({
  title: yup.string().required("Title is required"),
  language: yup.string().required("Language is required"),
  questions: yup.array().of(yup.string()).min(1, "Select at least 1 question"),
  marks: yup.number().min(1).required("Marks required"),
  duration: yup.number().min(1).required("Duration required"),
});

export default function TestAddEdit() {
  const { state, pathname } = useLocation();
  const isEdit = pathname === ROUTE_CONSTANTS.TestsEdit;
  const navigate = useNavigate();

  const [languageOptions, setLanguageOptions] = useState<any[]>([]);
  const [options, setOptions] = useState<IOptionsList>({
    subjects: state?.subject ? [{ label: state.subjectName, value: state.subject, topics: [] }] : [],
    languages: [],
    difficulty: ["Easy", "Medium", "Hard"].map((diff) => ({
      label: diff,
      value: diff,
    })),
  });

  const [questions, setQuestions] = useState<IQuestion[]>([]);
  const [selectedQuestions, setSelectedQuestions] = useState<IQuestion[]>([]);
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(0);
  const [subjectPage, setSubjectPage] = useState(1);
  const [subjectTotal, setSubjectTotal] = useState(0);
  const [subjectLoading, setSubjectLoading] = useState(false);
  const [topicPage, setTopicPage] = useState(1);
  const [topicTotal, setTopicTotal] = useState(0);
  const [topicLoading, setTopicLoading] = useState(false);
  const [currentTopics, setCurrentTopics] = useState<any[]>([]);
  const [filterValues, setFilterValues] = useState({
    ...filterInitial,
    subject: state?.subject || filterInitial.subject,
    language: state?.subjectLanguage || filterInitial.language,
  });
  const [previewQuestion, setPreviewQuestion] = useState<IQuestion | null>(
    null,
  );

  const [sequencePage, setSequencePage] = useState(1);
  const [sequenceLimit, setSequenceLimit] = useState(10);
  const [mode, setMode] = useState<"manual" | "auto">("manual");
  const [autoGenerated, setAutoGenerated] = useState<any[]>([]);
  const [autoLoading, setAutoLoading] = useState(false);
  const [autoCount, setAutoCount] = useState<number | null>(null);
  const [autoCountError, setAutoCountError] = useState("");
  const [autoGenPage, setAutoGenPage] = useState(1);
  const [autoGenLimit, setAutoGenLimit] = useState(10);
  const [availableCount, setAvailableCount] = useState<number | null>(null);
  const [usedCount, setUsedCount] = useState<number | null>(null);
  const [totalCount, setTotalCount] = useState<number | null>(null);
  const [autoPoolTotal, setAutoPoolTotal] = useState<number | null>(null);
  const [shufflingId, setShufflingId] = useState<string | null>(null);
  const [availableCountLoading, setAvailableCountLoading] = useState(false);
  const MAX_QUESTIONS = 200;

  const fetchAvailableCount = useCallback(async () => {
    setAvailableCountLoading(true);
    try {
      const res = await API_Instance.post(
        `${API_Constants.tests}/available-questions-count`,
        {
          subjectId: filterValues.subject,
          topics: filterValues.topic,
          difficulty: filterValues.difficulty || undefined,
          language: filterValues.language || undefined,
          currentTestId: isEdit ? state?.id : undefined,
        }
      );
      const availCount = res.data.available ?? res.data.count ?? 0;
      const usedCnt = res.data.used ?? 0;
      const totalCnt = res.data.total ?? availCount + usedCnt;
      setAvailableCount(availCount);
      setUsedCount(usedCnt);
      setTotalCount(totalCnt);
      if (mode === "auto") setAutoPoolTotal(availCount);
    } catch {
      setAvailableCount(null);
      setUsedCount(null);
      setTotalCount(null);
    } finally {
      setAvailableCountLoading(false);
    }
  }, [filterValues, isEdit, state, mode]);

  useEffect(() => {
    if (current === 0) {
      fetchAvailableCount();
    }
  }, [filterValues, current, fetchAvailableCount]);

  useEffect(() => {
    if (current === 0 && mode === "manual") {
      setPage(1);
      fetchQuestions(1, limit, filterValues);
    }
  }, [mode, current]);

  const handleModeChange = (newMode: "manual" | "auto") => {
    if (newMode !== mode) {
      setMode(newMode);
      setSelectedQuestions([]);
      setAutoGenerated([]);
      if (newMode === "auto") {
        setAutoCount(null);
        setAutoCountError("");
      }
    }
  };
  
  const shuffleQuestion = async (questionId: string) => {
    setShufflingId(questionId);
    try {
      const existingIds = selectedQuestions.map((q) => q.id);
      const res = await API_Instance.post(
        `${API_Constants.tests}/replace-question`,
        {
          subjectIds: filterValues.subject ? [filterValues.subject] : [],
          topics: filterValues.topic,
          difficulty: filterValues.difficulty || undefined,
          language: filterValues.language || undefined,
          currentTestId: isEdit ? state?.id : undefined,
          existingQuestionIds: existingIds,
          isAlreadyUsed: "0",
        }
      );
      const replacement: IQuestion = res.data.data;

      setAutoGenerated((prev) =>
        prev.map((q) =>
          q.id === questionId
            ? ({ ...replacement, sourceType: "auto" } as any)
            : q
        )
      );
      setSelectedQuestions((prev) =>
        prev.map((q) =>
          q.id === questionId
            ? ({ ...replacement, sourceType: "auto" } as any)
            : q
        )
      );
    } catch (err) {
      const msg = getAxiosErrorMessage(err);
      if (msg.includes("No alternative")) {
        toast.error("No more questions available to replace with your current filters.");
      } else {
        toast.error(msg);
      }
    } finally {
      setShufflingId(null);
    }
  };

  const handleAutoGenerate = async () => {
    if (!autoCount || autoCount <= 0) {
      setAutoCountError("Please enter a valid number of questions");
      return;
    }
    if (autoCount > MAX_QUESTIONS) {
      setAutoCountError(`Maximum allowed is ${MAX_QUESTIONS}`);
      return;
    }
    if (autoPoolTotal !== null && autoCount > autoPoolTotal) {
      setAutoCountError(`Only ${autoPoolTotal} questions available based on your filters`);
      return;
    }

    setAutoCountError("");
    setAutoLoading(true);
    try {
      const payload = {
          subjectId: filterValues.subject,
          topics: filterValues.topic,
          difficulty: filterValues.difficulty || undefined,
          language: filterValues.language || undefined,
          currentTestId: isEdit ? state?.id : undefined,
          count: autoCount,
          isAlreadyUsed: "0",
      };

      const res = await API_Instance.post(`${API_Constants.tests}/generate-questions`, payload);
      
      const newGenerated = res.data.data;
      setAutoGenerated(newGenerated);
      
      setSelectedQuestions(newGenerated.map((q: any) => ({ ...q, sourceType: "auto" })));
      
      toast.success(`Successfully generated ${newGenerated.length} questions`);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setAutoLoading(false);
    }
  };

  const buildQuery = (filters: any, page: number, limit: number) => {
    const params = new URLSearchParams();

    params.append("page", page.toString());
    params.append("limit", limit.toString());

    Object.entries(filters).forEach(([key, val]) => {
      if (key === "usageFilter") return;
      if (val !== "" && val !== undefined && val !== null) {
        if (Array.isArray(val)) {
          if (val.length > 0) {
            val.forEach(v => params.append(key, v.toString()));
          }
        } else {
          params.append(key, val.toString());
        }
      }
    });

    if (filters.usageFilter === "used") {
      params.append("isAlreadyUsed", "1");
    } else if (filters.usageFilter === "available") {
      params.append("isAlreadyUsed", "0");
    }

    return params.toString();
  };

  const {
    control,
    trigger,
    handleSubmit,
    watch,
    setValue,
    reset,
    formState: { errors },
  } = useForm<ExamFormValues>({
    resolver: yupResolver(testMapSchema) as unknown as Resolver<ExamFormValues>,
    defaultValues: initialFormValues,
  });

  const steps = [
    { title: <span className="text-sm">Test Details & Questions</span> },
    { title: <span className="text-sm">Save</span> },
  ];

  const fetchViewTest = async (id: string) => {
    try {
      const res = await API_Instance.get(`${API_Constants.tests}/${id}`);
      const data = res.data.data;
      reset({
        title: data.title,
        language: data.language || "English",
        duration: data.duration || 30,
        marks: data.marks || 0,
        questions: data.testQuestions?.map((tq: any) => tq.questionId) || [],
      });
      if (data.testQuestions) {
        setSelectedQuestions(data.testQuestions.map((tq: any) => tq.question));
      }
      setFilterValues({
        ...filterInitial,
        subject: data.subjectId,
      });
      if (data.subjectId) {
        setOptions((prev) => {
          const hasSub = prev.subjects.some((s: any) => s.value === data.subjectId);
          if (!hasSub && data.subject) {
            return {
              ...prev,
              subjects: [
                ...prev.subjects,
                {
                  label: data.subject.subjectName,
                  value: data.subject.id,
                  language: data.subject.language,
                  topics: [],
                }
              ]
            };
          }
          return prev;
        });
        fetchTopics(data.subjectId, 1);
      }
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    }
  };

  const fetchQuestions = async (
    page = 1,
    limit = 10,
    filter = filterValues,
  ) => {
    setLoading(true);
    try {
      const query = buildQuery(
        {
          ...filter,
          subject: filter.subject,
          testId: isEdit ? state?.id : undefined,
        },
        page,
        limit,
      );

      const res = await API_Instance.get(
        `${API_Constants.questionBank}?${query}`,
      );
      setQuestions(res.data.data);
      setTotal(res.data.meta.total);
      setPage(res.data.meta.page);
      setLimit(res.data.meta.limit);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

  const fetchSubjects = async (page = 1) => {
    try {
      setSubjectLoading(true);
      const res = await API_Instance.get(API_Constants.subjects, {
        params: { page, limit: 10 }
      });
      const fetchedSubjects = res.data.data
        .map((s: any) => ({
          label: s.subjectName,
          value: s.id,
          language: s.language,
          topics: s.topics.sort().map((sub: string) => ({
            label: sub,
            value: sub,
          })),
        }));

      setOptions((prev) => {
        let newSubjects = page === 1 ? fetchedSubjects : [...prev.subjects, ...fetchedSubjects];
        if (state?.subject && !newSubjects.find((s: any) => s.value === state.subject)) {
          newSubjects = [{ label: state.subjectName, value: state.subject, language: state.subjectLanguage, topics: [] }, ...newSubjects];
        }
        return {
          ...prev,
          subjects: newSubjects,
        };
      });
      setSubjectTotal(res.data.meta.total);
      setSubjectPage(page);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setSubjectLoading(false);
    }
  };

  const fetchTopics = async (subjectId: string, page = 1) => {
    try {
      setTopicLoading(true);
      const res = await API_Instance.get(`${API_Constants.subjects}/${subjectId}/topics`, {
        params: { page, limit: 10 }
      });
      const fetchedTopics = res.data.topics.map((t: any) => ({
        label: t.topic,
        value: t.topic,
      }));
      setCurrentTopics((prev) => page === 1 ? fetchedTopics : [...prev, ...fetchedTopics]);
      setTopicTotal(res.data.meta.total);
      setTopicPage(page);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setTopicLoading(false);
    }
  };

  const selectedSubject = options.subjects.find((s: any) => s.value === filterValues.subject) as any;
  const subjectLanguage = selectedSubject?.language || (filterValues.subject === state?.subject ? state?.subjectLanguage : undefined);

  useEffect(() => {
    if (subjectLanguage) {
      setValue("language", subjectLanguage);
      setFilterValues((prev) => ({
        ...prev,
        language: subjectLanguage,
      }));
    }
  }, [subjectLanguage, setValue]);

  const debouncedSearch = useDebounce(filterValues.search, 600);

  useEffect(() => {
    const loadLanguages = async () => {
      try {
        const options = await fetchLanguageOptions();
        setLanguageOptions(options);
        setOptions((prev) => ({ ...prev, languages: options }));
      } catch {
        setLanguageOptions([]);
        setOptions((prev) => ({ ...prev, languages: [] }));
      }
    };

    void loadLanguages();
  }, []);

  useEffect(() => {
    if (current === 0) {
      setPage(1);
      fetchQuestions(1, limit, { ...filterValues, search: debouncedSearch });
    }
  }, [
    debouncedSearch,
    current,
    filterValues.subject,
    filterValues.topic,
    filterValues.difficulty,
    filterValues.usageFilter,
    filterValues.language,
    limit,
  ]);

  useEffect(() => {
    fetchSubjects();
    if (!isEdit) {
      reset({
        ...initialFormValues,
        language: state?.subjectLanguage || "English",
      });
      if (state?.subject) {
        fetchTopics(state.subject, 1);
      }
    }
    if (isEdit) {
      fetchViewTest(state.id);
    }
  }, [state, isEdit]);

  useEffect(() => {
    setValue(
      "questions",
      selectedQuestions.map((question) => question.id),
    );
    setValue(
      "marks",
      selectedQuestions.reduce((total, question) => total + (question.marks || 0), 0),
    );
  }, [selectedQuestions, setValue]);

  const handleResetQuestion = () => {
    setValue("questions", []);
    setValue("marks", 0);
    setSelectedQuestions([]);
  };

  const toggleQuestion = (q: IQuestion) => {
    const exists = selectedQuestions.some((s) => s.id === q.id);

    let updated = [];
    if (exists) {
      updated = selectedQuestions.filter((s) => s.id !== q.id);
    } else {
      updated = [...selectedQuestions, q];
    }

    setSelectedQuestions(updated);
    setValue(
      "questions",
      updated.map((q) => q.id),
    );
    setValue(
      "marks",
      updated.reduce((acc, q) => acc + q.marks, 0),
    );
  };

  const removeSelectedQuestion = (id: string) => {
    const updated = selectedQuestions.filter((sel) => sel.id !== id);
    setSelectedQuestions(updated);
    setValue(
      "questions",
      updated.map((q) => q.id),
    );
    setValue(
      "marks",
      updated.reduce((acc, q) => acc + q.marks, 0),
    );
  };

  const onSubmit = async (data: ExamFormValues, publish: boolean) => {
    if (!filterValues.subject) {
      toast.error("Please select a subject before creating a test");
      return;
    }

    const calculatedTopics = Array.from(new Set(selectedQuestions.map(q => q.topic).filter(Boolean)));
    const testTopic = calculatedTopics.length > 0 ? calculatedTopics : filterValues.topic;

    try {
      if (state?.id) {
        await API_Instance.put(`${API_Constants.tests}/${state.id}`, {
          title: data.title,
          questionIds: data.questions,
          language: data.language,
          duration: data.duration,
          marks: data.marks,
          subjectId: filterValues.subject,
          topic: testTopic,
        });
        toast.success("Test updated successfully");
      } else {
        await API_Instance.post(API_Constants.tests, {
          title: data.title,
          questionIds: data.questions,
          language: data.language,
          duration: data.duration,
          marks: data.marks,
          subjectId: filterValues.subject,
          topic: testTopic,
        });
        toast.success("Test created successfully");
      }
      navigate(ROUTE_CONSTANTS.Tests);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    }
  };

  const eligiblePageQuestions = questions.filter(
    (q) => {
      const otherTests = q.usedInTests?.filter(t => t.id !== state?.id) || [];
      return otherTests.length === 0;
    }
  );

  const isAllCurrentPageSelected =
    eligiblePageQuestions.length > 0 &&
    eligiblePageQuestions.every((q) =>
      selectedQuestions.some((item) => item.id === q.id)
    );

  const handleSelectAllPage = () => {
    if (isAllCurrentPageSelected) {
      const eligibleIds = eligiblePageQuestions.map((q) => q.id);
      setSelectedQuestions((prev) => prev.filter((item) => !eligibleIds.includes(item.id)));
    } else {
      setSelectedQuestions((prev) => {
        const missingQuestions = eligiblePageQuestions.filter(
          (q) => !prev.some((item) => item.id === q.id)
        );
        return [...prev, ...missingQuestions];
      });
    }
  };

  return (
    <div className="flex flex-col gap-3 px-4">
      <div className="flex justify-between items-center my-4 mb-6">
        <h2 className="text-xl font-bold text-[#1677ff]">
          {isEdit ? "Edit Test" : `Create New Test${state?.subjectName ? ` - ${state.subjectName}` : ""}`}
        </h2>
      </div>
      <Steps current={current} items={steps} className="mb-5" />
      <Card
        title={
          current === 0
            ? "Test Details & Questions"
            : "Save & Publish"
        }
      >
        <Form layout="vertical">
          {/* Step 2 */}
          {current === 0 && (
            <div className="flex flex-col gap-4">
              <Row gutter={[18, 18]} style={{ rowGap: 0 }}>
                {/* TITLE */}
                <Col span={24}>
                  <Form.Item
                    label="Test Title"
                    validateStatus={errors.title ? "error" : ""}
                    help={errors.title?.message}
                    required
                  >
                    <Controller
                      name="title"
                      control={control}
                      render={({ field }) => (
                        <Input {...field} placeholder="Test Title" />
                      )}
                    />
                  </Form.Item>
                </Col>

                {/* LANGUAGE */}
                <Col span={12}>
                  <Form.Item
                    label="Language"
                    validateStatus={errors.language ? "error" : ""}
                    help={errors.language?.message}
                    required
                  >
                    <Controller
                      name="language"
                      control={control}
                      render={({ field }) => (
                        <Select
                          options={options.languages}
                          {...field}
                          value={field.value === "" ? undefined : field.value}
                          placeholder="Select Language"
                          disabled={Boolean(subjectLanguage)}
                          onChange={(value) => {
                            field.onChange(value);
                            setFilterValues((prev) => ({
                              ...prev,
                              language: value,
                            }));
                            handleResetQuestion();
                          }}
                        />
                      )}
                    />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="Duration (Minutes)"
                    validateStatus={errors.duration ? "error" : ""}
                    help={errors.duration?.message}
                    required
                  >
                    <Controller
                      name="duration"
                      control={control}
                      render={({ field }) => (
                        <Input
                          {...field}
                          type="number"
                          placeholder="Test Duration"
                        />
                      )}
                    />
                  </Form.Item>
                </Col>

              </Row>

            <div className="flex gap-4">
              {/* Left Filter Panel */}
              <div className="w-full lg:w-72 flex-shrink-0 bg-white border border-slate-200 rounded-xl flex flex-col overflow-hidden">
                <div className="flex flex-col p-4">
                  
                    {/* Mode Toggle */}
                    <div className="flex items-center justify-center gap-2 mb-4">
                      <button
                        type="button"
                        onClick={() => handleModeChange("manual")}
                        className={`flex items-center justify-center gap-2 px-2 py-2 w-full rounded-xl text-xs font-semibold border-2 transition-all ${
                          mode === "manual"
                            ? "bg-[#1677ff] text-white border-[#1677ff] shadow"
                            : "bg-white text-slate-600 border-slate-200 hover:border-[#1677ff] hover:text-[#1677ff]"
                        }`}
                      >
                        Manual Select
                      </button>
                      <button
                        type="button"
                        onClick={() => handleModeChange("auto")}
                        className={`flex items-center justify-center gap-2 px-2 py-2 w-full rounded-xl text-xs font-semibold border-2 transition-all ${
                          mode === "auto"
                            ? "bg-green-600 text-white border-green-600 shadow"
                            : "bg-white text-slate-600 border-slate-200 hover:border-green-600 hover:text-green-600"
                        }`}
                      >
                        Auto Generate
                      </button>
                    </div>



                  {mode === "manual" && <Form.Item label="Search Questions">
                    <Input
                      placeholder="Search questions..."
                      prefix={<Search size={16} className="text-slate-400" />}
                      value={filterValues.search}
                      onChange={(e) =>
                        setFilterValues((prev) => ({
                          ...prev,
                          search: e.target.value,
                        }))
                      }
                      allowClear
                    />
                  </Form.Item>}

                  <Form.Item label="Subject">
                    <Select
                      placeholder={"Select Subject"}
                      options={options.subjects}
                      value={filterValues.subject || undefined}
                      allowClear
                      loading={subjectLoading}
                      disabled={!!state?.subject}
                      onPopupScroll={(e) => {
                        const target = e.currentTarget;
                        if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight) {
                          if (options.subjects.length < subjectTotal && !subjectLoading) {
                            fetchSubjects(subjectPage + 1);
                          }
                        }
                      }}
                      onSelect={(value) => {
                        setFilterValues((prev) => ({
                          ...prev,
                          subject: value,
                          topic: undefined,
                        }));
                        fetchTopics(value, 1);
                      }}
                      onClear={() => {
                        setFilterValues((prev) => ({
                          ...prev,
                          subject: undefined,
                          topic: undefined,
                        }));
                        setCurrentTopics([]);
                      }}
                    />
                  </Form.Item>

                  {filterValues.subject && (
                    <Form.Item label="Topic">
                      <Select
                        mode="multiple"
                        placeholder={"Select Topic"}
                        options={currentTopics}
                        value={filterValues.topic || []}
                        allowClear
                        loading={topicLoading}
                        onPopupScroll={(e) => {
                          const target = e.currentTarget;
                          if (Math.ceil(target.scrollTop + target.offsetHeight) >= target.scrollHeight) {
                            if (currentTopics.length < topicTotal && !topicLoading) {
                              fetchTopics(filterValues.subject as string, topicPage + 1);
                            }
                          }
                        }}
                        onChange={(value) =>
                          setFilterValues((prev) => ({
                            ...prev,
                            topic: value,
                          }))
                        }
                      />
                    </Form.Item>
                  )}

                  <Form.Item label="Difficulty">
                    <Select
                      placeholder={"Select Difficulty"}
                      options={[
                        { label: "All", value: "" },
                        ...options.difficulty,
                      ]}
                      allowClear
                      onSelect={(value) =>
                        setFilterValues((prev) => ({
                          ...prev,
                          difficulty: value,
                        }))
                      }
                      value={filterValues["difficulty"] || undefined}
                      onClear={() => {
                        setFilterValues((prev) => ({
                          ...prev,
                          difficulty: undefined,
                        }));
                      }}
                    />
                  </Form.Item>

                  {/* Usage Filter */}
                  {mode === "manual" && (
                    <Form.Item label="Question Usage">
                      <Select
                        placeholder="All Questions"
                        allowClear
                        value={filterValues.usageFilter === "all" ? undefined : filterValues.usageFilter}
                        onChange={(value: "used" | "available") => {
                          setFilterValues((prev) => ({ ...prev, usageFilter: value ?? "all" }));
                        }}
                        onClear={() => {
                          setFilterValues((prev) => ({ ...prev, usageFilter: "all" }));
                        }}
                        options={[
                          { label: "Used Questions", value: "used" },
                          { label: "Available Questions", value: "available" },
                        ]}
                      />
                    </Form.Item>
                  )}

                  <div className="flex gap-2 mb-6">
                    <Button
                      className="w-full"
                      icon={<RotateCcw size={16} />}
                      onClick={() => {
                        setFilterValues({
                          ...filterInitial,
                          search: "",
                          language: watch("language"),
                        });
                      }}
                    >
                      Reset Filters
                    </Button>
                  </div>

                  {mode === "auto" && (
                    <>
                      <div className="mt-1 flex flex-col gap-3 mb-6">
                        <div className="text-sm font-medium text-slate-700">
                          Number of Questions
                        </div>

                        <input
                          type="number"
                          min={1}
                          max={autoPoolTotal !== null ? Math.min(autoPoolTotal, MAX_QUESTIONS) : MAX_QUESTIONS}
                          value={autoCount ?? ""}
                          onChange={(e) => {
                            const val = e.target.value;
                            if (val === "") {
                              setAutoCount(null);
                              setAutoCountError("");
                            } else {
                              const num = parseInt(val, 10);
                              if (!isNaN(num)) {
                                setAutoCount(num);
                                if (num > MAX_QUESTIONS) {
                                  setAutoCountError(`Maximum allowed is ${MAX_QUESTIONS}`);
                                } else if (autoPoolTotal !== null && num > autoPoolTotal) {
                                  setAutoCountError(`Only ${autoPoolTotal} questions available based on your filters`);
                                } else {
                                  setAutoCountError("");
                                }
                              }
                            }
                          }}
                          className={`w-full border rounded-lg px-3 py-1.5 text-sm outline-none transition-colors ${autoCountError
                            ? "border-red-400 bg-red-50"
                            : "border-slate-300 focus:border-blue-400"
                            }`}
                          placeholder="Enter number of questions"
                        />
                        
                        {!autoCountError && autoCount !== null && (
                          <span className="text-xs text-slate-500 leading-snug">
                            {autoPoolTotal !== null && autoPoolTotal < MAX_QUESTIONS
                              ? `Only ${autoPoolTotal} questions available for your filters.`
                              : `Up to ${MAX_QUESTIONS} questions allowed per test.`
                            }
                          </span>
                        )}

                        {autoCountError && (
                          <div className="bg-red-50 border border-red-200 rounded px-2.5 py-1.5">
                            <span className="text-xs text-red-700 font-medium">{autoCountError}</span>
                          </div>
                        )}
                        
                        <div className="flex gap-2 mt-4">
                          <Button onClick={() => {
                            setAutoCount(null);
                            setAutoCountError("");
                            setAutoGenerated([]);
                            setSelectedQuestions([]);
                          }} className="flex-1">
                            Clear
                          </Button>
                          <Button
                            type="primary"
                            icon={<Wand2 size={15} />}
                            loading={autoLoading}
                            disabled={!!autoCountError || !autoCount || autoCount < 1}
                            onClick={handleAutoGenerate}
                            className="flex-[2] bg-brand-green hover:bg-brand-green! border-brand-green!"
                            style={{ backgroundColor: '#16a34a', borderColor: '#16a34a' }}
                          >
                            Generate
                          </Button>
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* Main List */}
              <div className="flex-1 flex flex-col gap-4 min-w-0">
                <div className="mt-4 grid grid-cols-5 bg-[#1677ff] text-white rounded-xl shadow-md divide-x divide-white/10 p-3.5 items-center text-center">
                  <div className="flex flex-col gap-1.5 px-2">
                    <span className="text-[10px] font-medium text-indigo-100 uppercase tracking-wide leading-tight">
                      Total Questions
                    </span>
                    {availableCountLoading ? (
                      <div className="flex justify-center items-center h-6 mt-1">
                        <Spin size="small" className="brightness-0 invert scale-75" />
                      </div>
                    ) : (
                      <span className="text-xl font-bold leading-none mt-1">
                        {totalCount !== null ? totalCount.toLocaleString() : 0}
                      </span>
                    )}
                  </div>

                  <div className="flex flex-col gap-1.5 px-2">
                    <span className="text-[10px] font-medium text-indigo-100 uppercase tracking-wide leading-tight">
                      Available Questions
                    </span>
                    {availableCountLoading ? (
                      <div className="flex justify-center items-center h-6 mt-1">
                        <Spin size="small" className="brightness-0 invert scale-75" />
                      </div>
                    ) : (
                      <span className="text-xl font-bold leading-none mt-1">
                        {availableCount !== null ? availableCount.toLocaleString() : 0}
                      </span>
                    )}
                  </div>

                  <div className="flex flex-col gap-1.5 px-2">
                    <span className="text-[10px] font-medium text-indigo-100 uppercase tracking-wide leading-tight">
                      {mode === "auto" ? "Generated" : "Selected"}
                    </span>
                    <span className="text-xl font-bold leading-none mt-1">
                      {mode === "auto" ? autoGenerated.length : selectedQuestions.length}
                    </span>
                  </div>

                  <div className="flex flex-col gap-1.5 px-2">
                    <span className="text-[10px] font-medium text-indigo-100 uppercase tracking-wide leading-tight">
                      Balance Questions
                    </span>
                    {availableCountLoading ? (
                      <div className="flex justify-center items-center h-6 mt-1">
                        <Spin size="small" className="brightness-0 invert scale-75" />
                      </div>
                    ) : (
                      <span className="text-xl font-bold leading-none mt-1">
                        {availableCount !== null ? Math.max(0, availableCount - (mode === "auto" ? autoGenerated.length : selectedQuestions.length)).toLocaleString() : 0}
                      </span>
                    )}
                  </div>

                  <div className="flex flex-col gap-1.5 px-2">
                    <span className="text-[10px] font-medium text-indigo-100 uppercase tracking-wide leading-tight">
                      Total Marks
                    </span>
                    <span className="text-xl font-bold leading-none mt-1">
                      {mode === "auto" ? autoGenerated.length : selectedQuestions.length}
                    </span>
                  </div>
                </div>

                <div>
                  {mode === "manual" ? (
                    <>
                      {/* Select All */}
                      {!loading && questions.length > 0 && eligiblePageQuestions.length > 0 && (
                    <div className={`flex items-center gap-3 px-4 py-3 border-2 rounded-xl mb-3 transition-all ${isAllCurrentPageSelected
                      ? "bg-blue-50/50 border-blue-500 shadow-sm"
                      : "bg-slate-50/80 border-slate-200 hover:bg-slate-50 hover:border-blue-300"
                      }`}>
                      <button
                        type="button"
                        onClick={handleSelectAllPage}
                        className={`w-5 h-5 rounded border flex items-center justify-center transition-colors ${isAllCurrentPageSelected
                          ? "bg-blue-600 border-blue-600 text-white"
                          : "bg-white border-slate-400 text-transparent hover:border-blue-500"
                          }`}
                      >
                        <Check size={14} strokeWidth={3} />
                      </button>
                      <span
                        onClick={handleSelectAllPage}
                        className={`text-sm font-bold select-none cursor-pointer ${isAllCurrentPageSelected ? "text-blue-700" : "text-slate-600"
                          }`}
                      >
                        {isAllCurrentPageSelected ? "Deselect All on Current Page" : "Select All Available on Current Page"}
                      </span>
                    </div>
                  )}

                  <div className="min-h-[400px] flex-1 overflow-y-auto space-y-2 custom-scrollbar pr-1">
                    {loading ? (
                      <div className="min-h-[400px] flex justify-center items-center">
                        <Spin />
                      </div>
                    ) : (
                      <>
                        {questions.map((q) => {
                          const isSelected = selectedQuestions.some(
                            (item) => item.id === q.id,
                          );

                          const otherTests = q.usedInTests?.filter(t => t.id !== state?.id) || [];
                          const isDisableQuestion = otherTests.length > 0;

                          return (
                            <div
                              key={q.id}
                              className={`group p-4 rounded-xl border transition-all hover:shadow-md ${isDisableQuestion && !isSelected
                                ? "cursor-not-allowed opacity-50 bg-slate-50 border-slate-200"
                                : isSelected
                                  ? "bg-indigo-50 border-indigo-200"
                                  : "bg-white border-slate-200"
                                }`}
                            >
                              <div className="flex items-start gap-4">
                                <div className="pt-1">
                                  <button
                                    type="button"
                                    disabled={isDisableQuestion && !isSelected}
                                    onClick={() => toggleQuestion(q)}
                                    className={`w-5 h-5 rounded border flex items-center justify-center transition-colors ${isSelected
                                      ? "bg-indigo-600 border-indigo-600 text-white"
                                      : "bg-white border-slate-300 text-transparent hover:border-indigo-400"
                                      } ${isDisableQuestion && !isSelected ? "cursor-not-allowed" : ""}`}
                                  >
                                    <Check size={14} strokeWidth={3} />
                                  </button>
                                </div>
                                <div className="flex-1 min-w-0">
                                  <div className="flex items-start justify-between gap-2">
                                    <p
                                      className={`text-sm font-medium ${isSelected
                                        ? "text-indigo-900"
                                        : "text-slate-800"
                                        } line-clamp-2`}
                                    >
                                      {q.questionText}
                                    </p>
                                    <button
                                      type="button"
                                      onClick={() => setPreviewQuestion(q)}
                                      className="text-slate-400 hover:text-indigo-600 opacity-0 group-hover:opacity-100 transition-opacity"
                                    >
                                      <Eye size={18} />
                                    </button>
                                  </div>
                                  <div className="flex flex-wrap items-center gap-1 mt-2">
                                    <Tag
                                      color={
                                        q.difficulty === "Easy"
                                          ? "green"
                                          : q.difficulty === "Medium"
                                            ? "blue"
                                            : "red"
                                      }
                                      className="rounded-lg"
                                    >
                                      {q.difficulty}
                                    </Tag>
                                    {q.language && (
                                      <Tag
                                        color="purple"
                                        className="rounded-lg"
                                      >
                                        {q.language}
                                      </Tag>
                                    )}
                                    {q.topic && (
                                      <Tag
                                        color="purple"
                                        className="rounded-lg"
                                      >
                                        {q.topic}
                                      </Tag>
                                    )}
                                    {isDisableQuestion && (
                                      <Tag color="red" className="rounded-lg">
                                        Already used in the test - {otherTests.map(t => t.title).join(", ")}
                                      </Tag>
                                    )}
                                  </div>
                                </div>
                              </div>
                            </div>
                          );
                        })}

                        {questions.length === 0 && (
                          <div className="text-center py-12 text-slate-400">
                            No questions match your filters. Please try different filters or add questions to this exam.
                          </div>
                        )}
                      </>
                    )}
                  </div>
                  {total > 0 && (
                    <div className="flex justify-end mt-3">
                      <Pagination
                        current={page}
                        total={total}
                        pageSize={limit}
                        showSizeChanger
                        pageSizeOptions={["10", "20", "50", "100"]}
                        onChange={(p, s) => {
                          setPage(p);
                          setLimit(s);
                          fetchQuestions(p, s, filterValues);
                        }}
                      />
                    </div>
                  )}
                    </>
                  ) : (
                    <div className="flex-1 flex flex-col min-h-0">
                      {autoLoading ? (
                        <div className="flex-1 flex flex-col items-center justify-center min-h-[400px] text-slate-400">
                          <Spin size="large" className="mb-4" />
                          <p>Generating questions...</p>
                        </div>
                      ) : autoGenerated.length === 0 ? (
                        <div className="flex-1 flex flex-col items-center justify-center min-h-[400px] text-slate-400">
                          <Wand2 size={48} className="mb-4 opacity-20" />
                          <p className="text-lg">No questions generated yet</p>
                          <p className="text-sm mt-1">
                            Set the number of questions and click Generate
                          </p>
                        </div>
                      ) : (
                        <div className="flex-1 overflow-y-auto space-y-3 custom-scrollbar pr-1 min-h-[400px]">
                          {autoGenerated
                            .slice(
                              (autoGenPage - 1) * autoGenLimit,
                              autoGenPage * autoGenLimit
                            )
                            .map((q, index) => {
                              const globalIndex = (autoGenPage - 1) * autoGenLimit + index + 1;
                              const isShuffling = shufflingId === q.id;

                              return (
                                <div
                                  key={q.id}
                                  className="group p-4 rounded-xl border bg-purple-50 border-purple-200 hover:shadow-md transition-all"
                                >
                                  <div className="flex items-start gap-4">
                                    <div className="flex-1 min-w-0">
                                      <p className="text-sm font-medium text-purple-900 line-clamp-2">
                                        {q.questionText}
                                      </p>
                                      <div className="flex flex-wrap items-center gap-1 mt-2">
                                        <Tag
                                          color={
                                            q.difficulty === "Easy"
                                              ? "green"
                                              : q.difficulty === "Medium"
                                                ? "blue"
                                                : "red"
                                          }
                                          className="rounded-lg"
                                        >
                                          {q.difficulty}
                                        </Tag>
                                        {q.language && (
                                          <Tag color="purple" className="rounded-lg">
                                            {q.language}
                                          </Tag>
                                        )}
                                        {q.topic && (
                                          <Tag color="cyan" className="rounded-lg">
                                            {q.topic}
                                          </Tag>
                                        )}
                                        {(q as any).subject && (
                                          <Tag color="geekblue" className="rounded-lg">
                                            {(q as any).subject}
                                          </Tag>
                                        )}
                                      </div>
                                    </div>
                                    <button
                                      type="button"
                                      title={
                                        isShuffling
                                          ? "Shuffling..."
                                          : "Get a different question"
                                      }
                                      disabled={isShuffling}
                                      onClick={() => shuffleQuestion(q.id)}
                                      className={`flex-shrink-0 flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold border transition-all ${!isShuffling
                                        ? "bg-white border-purple-300 text-purple-700 hover:bg-purple-100 hover:border-purple-500"
                                        : "bg-slate-100 border-slate-200 text-slate-400 cursor-not-allowed"
                                        }`}
                                    >
                                      {isShuffling ? (
                                        <Spin size="small" />
                                      ) : (
                                        <Shuffle size={13} />
                                      )}
                                      {isShuffling ? "..." : "Shuffle"}
                                    </button>
                                  </div>
                                </div>
                              );
                            })}
                        </div>
                      )}
                      
                      {autoGenerated.length > 0 && (
                        <div className="flex justify-end mt-3 mb-2">
                          <Pagination
                            current={autoGenPage}
                            total={autoGenerated.length}
                            pageSize={autoGenLimit}
                            showSizeChanger
                            pageSizeOptions={["10", "20", "50", "100"]}
                            onChange={(p, s) => {
                              setAutoGenPage(p);
                              setAutoGenLimit(s);
                            }}
                          />
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
          )}

          {current === 1 && (
            <>
              {/* Summary Card */}
              <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6 grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
                <div className="col-span-2">
                  <h3 className="text-lg font-bold text-slate-800">
                    {watch("title") || "Empty Title"}
                  </h3>
                  <div className="flex flex-wrap gap-2 mt-4">
                    {watch("language") && (
                      <Tag color="green" className="rounded-lg">
                        {watch("language") || "Empty Language"}
                      </Tag>
                    )}
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex items-center space-x-3 text-slate-600">
                    <Hash size={18} className="text-indigo-500" />
                    <span className="text-sm">
                      <span className="font-semibold text-slate-900">
                        {selectedQuestions.length}
                      </span>{" "}
                      Questions
                    </span>
                  </div>
                  <div className="flex items-center space-x-3 text-slate-600">
                    <CheckCircle size={18} className="text-indigo-500" />
                    <span className="text-sm">
                      <span className="font-semibold text-slate-900">
                        {watch("marks")}
                      </span>{" "}
                      Total Marks
                    </span>
                  </div>
                </div>
                <div className="space-y-4">
                  <div className="flex items-center space-x-3 text-slate-600">
                    <Clock size={18} className="text-indigo-500" />
                    <span className="text-sm">
                      <span className="font-semibold text-slate-900">
                        {watch("duration")}
                      </span>{" "}
                      Minutes
                    </span>
                  </div>
                </div>
              </div>

              {Object.values(errors).length > 0 && (
                <Alert
                  showIcon
                  message={
                    <p className="text-[crimson]">
                      Please fill all required fields.
                    </p>
                  }
                  type="error"
                  className="mb-4"
                />
              )}

              {/* Questions List */}
              <div className="space-y-4">
                <h3 className="font-semibold text-slate-800 border-b border-slate-200 pb-2">
                  Questions Sequence
                </h3>
                {selectedQuestions.slice((sequencePage - 1) * sequenceLimit, sequencePage * sequenceLimit).map((q, idx) => (
                  <div
                    key={q.id}
                    className="bg-white border border-slate-200 rounded-lg p-4 flex gap-4 items-start group hover:border-indigo-300 transition-colors"
                  >
                    <div className="w-8 h-8 rounded-full bg-slate-100 text-slate-500 flex items-center justify-center font-bold text-sm flex-shrink-0">
                      {(sequencePage - 1) * sequenceLimit + idx + 1}
                    </div>
                    <div className="flex-1">
                      <div className="flex justify-between items-start">
                        <p className="text-slate-800 font-medium text-sm">
                          {q.questionText}
                        </p>
                        <div className="flex items-center gap-2">
                          <button
                            type="button"
                            onClick={() => setPreviewQuestion(q)}
                            className="text-slate-300 hover:text-indigo-600 transition-colors"
                          >
                            <Eye size={18} />
                          </button>
                          <button
                            type="button"
                            className="text-slate-300 hover:text-red-500 transition-colors"
                            onClick={() => removeSelectedQuestion(q.id)}
                          >
                            <Trash2 size={16} />
                          </button>
                        </div>
                      </div>
                      <div className="flex gap-2 mt-2 text-xs text-slate-500">
                        <Tag
                          color={
                            q.difficulty === "Easy"
                              ? "green"
                              : q.difficulty === "Medium"
                                ? "blue"
                                : "red"
                          }
                          className="rounded-lg"
                        >
                          {q.difficulty}
                        </Tag>
                        {q.subject && (
                          <Tag color="purple" className="rounded-lg">
                            {getOptionLabel(options.subjects, q.subject)}
                          </Tag>
                        )}
                        {q.language && (
                          <Tag color="purple" className="rounded-lg">
                            {q.language}
                          </Tag>
                        )}
                        {q.topic && (
                          <Tag color="purple" className="rounded-lg">
                            {q.topic}
                          </Tag>
                        )}
                        <Tag color="blue" className="rounded-lg">
                          {q.marks} Marks
                        </Tag>
                      </div>
                    </div>
                  </div>
                ))}
                {selectedQuestions.length === 0 && (
                  <div className="text-center py-8 text-slate-400 border-2 border-dashed border-slate-200 rounded-xl">
                    No questions selected yet. Go back to step 2.
                  </div>
                )}
                {selectedQuestions.length > 0 && (
                  <div className="flex justify-end mt-3">
                    <Pagination
                      current={sequencePage}
                      total={selectedQuestions.length}
                      pageSize={sequenceLimit}
                      showSizeChanger
                      pageSizeOptions={["10", "20", "50", "100"]}
                      onChange={(p, s) => {
                        setSequencePage(p);
                        setSequenceLimit(s);
                      }}
                    />
                  </div>
                )}
              </div>
            </>
          )}

          {/* BUTTONS */}
          <div className="flex justify-end mt-8 gap-3">
            {current > 0 && (
              <Button onClick={() => setCurrent(current - 1)}>Back</Button>
            )}
            {current < 1 && (
              <Button
                onClick={async () => {
                  if (current === 0) {
                    if (selectedQuestions.length === 0) {
                      toast.error("Please select at least 1 question.");
                      return;
                    }

                    const valid = await trigger([
                      "title",
                      "language",
                      "duration",
                      "questions",
                      "marks"
                    ]);

                    if (!valid) {
                      return;
                    }
                  }

                  setCurrent(current + 1);
                }}
                type="primary"
              >
                Next
              </Button>
            )}
            {current === 1 && (
              <Button
                type="primary"
                onClick={handleSubmit((data) => onSubmit(data, false))}
              >
                {isEdit ? "Update" : "Save"}
              </Button>
            )}
          </div>
        </Form>
      </Card>
      <Modal
        isOpen={previewQuestion !== null}
        onClose={() => setPreviewQuestion(null)}
        title="Preview Question"
      >
        <QuestionCard question={previewQuestion} />
      </Modal>
    </div>
  );
}