import React, { useEffect, useMemo, useState } from "react";
import {
  Button,
  Card,
  Typography,
  Pagination,
  Input,
  Spin,
  Empty,
  Select,
  Table,
  Popconfirm,
} from "antd";
import {
  Search,
  Plus,
  Database,
  Download,
  FileSpreadsheet,
  UploadCloud,
  AlertCircle,
  History,
  ChevronDown,
  ChevronRight,
  ClipboardList,
  Clock,
  Trash2,
  CheckCircle,
  Info,
  Pencil,
} from "lucide-react";
import { API_Instance } from "../../api/axios.instance";
import API_Constants from "../../constants/api.constants";
import { IExam, IOldQuestions } from "@/types";
import toast from "react-hot-toast";
import { difficultyColor, getAxiosErrorMessage } from "@/utils/index.utils";
import { useNavigate, useSearchParams } from "react-router-dom";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { OldQuestionBankTreeCard } from "@/components/tree/OldQuestionBankTreeCard";
import { useDebounce } from "@/hooks/useDebounce";
import Modal from "@/components/shared/Modal";
import type { UploadFile } from "antd/es/upload/interface";
import { Upload, Tag } from "antd";
import { AccordionRow } from "@/components/shared/Accordion";
import dayjs from "dayjs";

const filterInitial = {
  search: "",
};

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

const OldQuestionBankPage: React.FC = () => {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [loading, setLoading] = useState(false);
  const [filterValues, setFilterValues] = useState(filterInitial);
  const openExamId = searchParams.get("examId");
  const [questions, setQuestions] = useState<IOldQuestions[]>([]);
  const [openQuestionId, setOpenQuestionId] = useState<string | null>(null);
  const [totalQuestions, setTotalQuestions] = useState(0);
  const [pagination, setPagination] = useState(paginationInitial);
  const debouncedSearch = useDebounce(filterValues.search, 600);

  // Bulk Upload State
  const [isBulkUploadModalOpen, setIsBulkUploadModalOpen] = useState(false);
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [bulkUploading, setBulkUploading] = useState(false);
  const [bulkStep, setBulkStep] = useState(0); // 0: Upload, 1: Preview, 2: Setup
  const [previewQuestions, setPreviewQuestions] = useState<any[]>([]);

  const toggleExam = (id: string) => {
    const newParams = new URLSearchParams(searchParams);
    if (openExamId === id) {
      newParams.delete("examId");
      newParams.delete("yearId");
    } else {
      newParams.set("examId", id);
      newParams.delete("yearId");
    }
    setSearchParams(newParams, { replace: true });
  };

  const fetchQuestions = async (page = 1, limit = 10) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(
        API_Constants.oldQuestions +
          `?page=${page}&limit=${limit}&search=${debouncedSearch}`,
      );
      setQuestions(res.data.data);
      setTotalQuestions(res.data.totalQuestions);
      setPagination(res.data.meta || paginationInitial);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    fetchQuestions(1, pagination.limit);
  }, [debouncedSearch]);

  const handleDownloadTemplate = async () => {
    try {
      const response = await API_Instance.get(
        `${API_Constants.oldQuestions}/template`,
        { responseType: "blob" },
      );
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "old_question_template.xlsx");
      document.body.appendChild(link);
      link.click();
      link.remove();
      toast.success("Template downloaded successfully");
    } catch (err) {
      toast.error("Failed to download template");
    }
  };

  const openBulkUploadModal = () => {
    setIsBulkUploadModalOpen(true);
    setFileList([]);
    setBulkStep(0);
    setPreviewQuestions([]);
  };

  const closeBulkUploadModal = () => {
    setIsBulkUploadModalOpen(false);
    setFileList([]);
  };

  const handleBulkUploadPreview = async () => {
    if (fileList.length === 0) {
      toast.error("Please select a file");
      return;
    }
    setBulkUploading(true);
    try {
      const formData = new FormData();
      const fileObj = (fileList[0] as any).originFileObj || fileList[0];
      formData.append("file", fileObj);

      const response = await API_Instance.post(
        `${API_Constants.oldQuestions}/preview-bulk`,
        formData,
      );
      setPreviewQuestions(response.data.data.questions);
      setBulkStep(1);
      toast.success("File parsed successfully. Please preview the questions.");
    } catch (err: any) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setBulkUploading(false);
    }
  };

  const handleConfirmBulkUpload = async () => {
    const validQuestions = previewQuestions.filter((q) => q.isValid);
    if (validQuestions.length === 0) {
      toast.error("No valid questions to upload");
      return;
    }
    setBulkUploading(true);
    try {
      const payload = {
        questions: validQuestions,
      };
      await API_Instance.post(
        `${API_Constants.oldQuestions}/confirm-bulk`,
        payload,
      );
      toast.success(
        `${validQuestions.length} Questions imported successfully.`,
      );
      closeBulkUploadModal();
      fetchQuestions(pagination.page, pagination.limit);
    } catch (err: any) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setBulkUploading(false);
    }
  };

  return (
    <div className="flex flex-col gap-4 px-4 py-6">
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
        <div>
          <h2 className="text-2xl font-bold text-slate-800 flex items-center gap-2">
            <History className="text-blue-600" /> Previous Year Questions
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Browse and manage individual questions from previous years.
          </p>
        </div>
        <div className="flex gap-3">
          <Button
            onClick={handleDownloadTemplate}
            icon={<Download size={16} />}
          >
            Template
          </Button>
          <Button
            onClick={openBulkUploadModal}
            icon={<FileSpreadsheet size={16} />}
          >
            Bulk Upload
          </Button>
          <Button
            type="primary"
            icon={<Plus className="h-4 w-4" />}
            className="!bg-brand-green hover:!bg-brand-green/80 flex items-center gap-2"
            onClick={() =>
              navigate(`${ROUTE_CONSTANTS.OldQuestionsBankCreate}`)
            }
          >
            Add Old Question
          </Button>
        </div>
      </div>

      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="flex justify-between items-center mb-4">
          <div className="w-full md:w-72">
            <Input
              placeholder="Search Old Questions..."
              prefix={<Search size={16} className="text-slate-400" />}
              allowClear
              value={filterValues.search}
              onChange={(e) => {
                setFilterValues({
                  ...filterValues,
                  search: e.target.value,
                });
              }}
            />
          </div>
          <div className="text-slate-500 text-sm">
            Total Questions:{" "}
            <span className="font-semibold text-slate-800">
              {totalQuestions}
            </span>
          </div>
        </div>

        <Spin spinning={loading}>
          {questions.length === 0 && !loading ? (
            <div className="min-h-[300px] flex flex-col items-center justify-center text-slate-400 border-2 border-dashed border-slate-100 rounded-xl">
              <div className="bg-slate-50 p-4 rounded-full mb-4">
                <History size={32} className="text-slate-300" />
              </div>
              <p>
                {filterValues.search
                  ? "No old questions found matching your search"
                  : "No old questions available"}
              </p>
            </div>
          ) : (
            <div className="space-y-3 min-h-[200px]">
              {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>
                          <div className="w-full flex flex-col gap-4">
                            <div className="w-full flex items-center gap-4 justify-between">
                              <div className="xl:col-span-6 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>

                              <div className="xl:col-span-6 flex flex-wrap xl:justify-end items-center gap-x-2 gap-y-2 mt-2 xl:mt-0">
                                {q.marks && (
                                  <span className="hidden lg:inline-block text-xs font-semibold text-slate-500 text-center min-w-[50px]">
                                    {q.marks} Mark
                                  </span>
                                )}
                                <Tag
                                  color={
                                    q.difficulty === "Easy"
                                      ? "green"
                                      : q.difficulty === "Medium"
                                        ? "orange"
                                        : "red"
                                  }
                                  className="rounded-full"
                                >
                                  {q.difficulty}
                                </Tag>
                                <Tag color="blue" className="rounded-full">
                                  {q.language}
                                </Tag>
                                <div
                                  className="flex items-center gap-1 pl-2 border-l border-slate-200 ml-2"
                                  onClick={(e) => e.stopPropagation()}
                                >
                                  <button
                                    className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 rounded-xl transition-colors"
                                    title="Edit Question"
                                    onClick={() =>
                                      navigate(
                                        ROUTE_CONSTANTS.OldQuestionsBankEdit,
                                        {
                                          state: q,
                                        },
                                      )
                                    }
                                  >
                                    <Pencil size={15} />
                                  </button>
                                  <Popconfirm
                                    title="Delete the Question"
                                    description="Are you sure to delete this question?"
                                    // onConfirm={() => handleDeleteQuestion(q.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 Question"
                                    >
                                      <Trash2 size={15} />
                                    </button>
                                  </Popconfirm>
                                </div>
                              </div>
                            </div>
                            <div className="w-full flex items-center justify-between">
                              <Tag color="purple" className="rounded-full">
                                {q.exams
                                  .map((exam) => (exam as any).examName)
                                  .join(", ")}
                                {q.year && `, ${q.year}`}
                              </Tag>
                              {/* Last Updated */}
                              {q.updatedAt && (
                                <div className="w-max flex items-center gap-1.5 text-slate-400">
                                  <Clock size={12} />
                                  <span className="text-xs font-[400] italic">
                                    {dayjs(q.updatedAt).format(
                                      "DD-MM-YYYY hh:mm:ss A",
                                    )}
                                  </span>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      }
                      isOpen={openQuestionId === q.id}
                      onToggle={() =>
                        openQuestionId === q.id
                          ? setOpenQuestionId(null)
                          : setOpenQuestionId(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-2 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"
                              />
                            )}
                          </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 && 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">
                                {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>
                      }
                    />
                  );
                })}
            </div>
          )}
        </Spin>

        <div className="flex justify-end mt-6">
          <Pagination
            current={pagination.page}
            total={pagination.total}
            pageSize={pagination.limit}
            onChange={(p, pageSize) => {
              setPagination({
                ...pagination,
                page: p,
                limit: pageSize,
              });
              fetchQuestions(p, pageSize);
            }}
            showSizeChanger
            showTotal={(total) => `Total ${total} items`}
          />
        </div>
      </Card>

      {/* Bulk Upload Modal */}
      <Modal
        isOpen={isBulkUploadModalOpen}
        onClose={closeBulkUploadModal}
        title="Old Questions Bulk Preview"
        className={
          bulkStep === 1 ? "max-w-[1000px] w-full" : "max-w-[600px] w-full"
        }
      >
        <div className="space-y-4">
          {bulkStep === 0 && (
            <div className="py-6 flex flex-col items-center gap-4">
              <div className="w-16 h-16 bg-blue-50 text-blue-600 rounded-full flex items-center justify-center">
                <UploadCloud size={32} />
              </div>
              <div className="text-center">
                <h3 className="font-bold text-lg">Upload Excel File</h3>
                <p className="text-slate-500 text-sm">
                  Download the template, fill it with questions and upload here.
                </p>
              </div>
              <Upload
                fileList={fileList}
                beforeUpload={(file) => {
                  setFileList([file]);
                  return false;
                }}
                onRemove={() => setFileList([])}
                maxCount={1}
                accept=".xlsx, .xls"
              >
                <Button type="dashed" className="h-20 w-80">
                  Click to select file
                </Button>
              </Upload>
              <Button
                type="primary"
                size="large"
                className="w-full mt-4"
                onClick={handleBulkUploadPreview}
                loading={bulkUploading}
                disabled={fileList.length === 0}
              >
                Continue to Preview
              </Button>
            </div>
          )}

          {bulkStep === 1 && (
            <div className="space-y-4">
              <div className="flex justify-between items-center">
                <h3 className="font-bold">Parsing Result</h3>
                <div className="flex gap-2">
                  <Tag color="success">
                    Valid: {previewQuestions.filter((q) => q.isValid).length}
                  </Tag>
                  <Tag color="error">
                    Errors: {previewQuestions.filter((q) => !q.isValid).length}
                  </Tag>
                </div>
              </div>
              <Table
                dataSource={previewQuestions}
                rowKey="rowNumber"
                columns={[
                  {
                    title: "#",
                    dataIndex: "rowNumber",
                    width: 50,
                    className: "text-slate-400",
                  },
                  {
                    title: "Question",
                    dataIndex: "questionText",
                    ellipsis: true,
                    render: (text) => (
                      <span className="font-medium text-slate-700">{text}</span>
                    ),
                  },
                  {
                    title: "Exams",
                    dataIndex: "examNames",
                    render: (names, record) =>
                      names?.join(", ") || record.examName || "-",
                  },
                  {
                    title: "Status",
                    dataIndex: "isValid",
                    render: (isValid, record) =>
                      isValid ? (
                        <Tag color="success">Valid</Tag>
                      ) : (
                        <div className="text-red-500 font-bold text-[10px]">
                          {record.errors?.map((err: string, j: number) => (
                            <div key={j}>{err}</div>
                          ))}
                        </div>
                      ),
                  },
                ]}
                pagination={{
                  pageSize: 10,
                  showSizeChanger: true,
                  size: "small",
                }}
                size="small"
                className="border rounded-xl overflow-hidden"
              />
              <div className="flex justify-between pt-4">
                <Button onClick={() => setBulkStep(0)}>Change File</Button>
                <div className="flex gap-3">
                  <Button onClick={closeBulkUploadModal}>Cancel</Button>
                  <Button
                    type="primary"
                    size="large"
                    onClick={handleConfirmBulkUpload}
                  >
                    Import via Papers Management
                  </Button>
                </div>
              </div>
            </div>
          )}
        </div>
      </Modal>
    </div>
  );
};

export default OldQuestionBankPage;

