import { useEffect, useState } from "react";
import {
  Button,
  Form,
  Input,
  Pagination,
  Spin,
  Select,
  Upload,
  InputNumber,
  Switch,
  Card,
  Tag,
  Table,
} from "antd";
import {
  Plus,
  FileSpreadsheet,
  Download,
  UploadCloud,
  FileClock,
  Search,
  AlertCircle,
} from "lucide-react";
import {
  useForm,
  Controller,
  type SubmitHandler,
  Resolver,
} from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { API_Instance } from "../../api/axios.instance";
import API_Constants from "../../constants/api.constants";
import toast from "react-hot-toast";
import Modal from "@/components/shared/Modal";
import { IPagination, IOldQuestionPaper, IExam } from "@/types";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import type { UploadFile } from "antd/es/upload/interface";
import { useLocation, useNavigate, useSearchParams } from "react-router-dom";
import { OldQuestionTreeCard } from "@/components/tree/OldQuestionTreeCard";
import { useDebounce } from "@/hooks/useDebounce";

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

export default function OldQuestions() {
  const navigate = useNavigate();
  const [searchParams, setSearchParams] = useSearchParams();
  const { state } = useLocation();
  const [exams, setExams] = useState<IExam[]>([]);
  const [totalQuestions, setTotalQuestions] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState(initialPagination);
  const [searchText, setSearchText] = useState("");
  const debouncedSearch = useDebounce(searchText, 600);
  const openExamId = searchParams.get("examId");
  const [refreshTrigger, setRefreshTrigger] = useState(0);

  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 fetchExams = async (
    page: number = 1,
    limit: number = 10,
    search: string = "",
  ) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(
        `${API_Constants.oldQuestionPapers}/exams?page=${page}&limit=${limit}&search=${search}`,
      );
      setExams(res.data.data || []);
      setTotalQuestions(res.data.totalQuestions);
      setPagination(res.data.meta || initialPagination);
    } catch (err) {
      toast.error("Failed to fetch exams");
    } finally {
      setLoading(false);
    }
  };

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

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

  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.`,
      );
      setRefreshTrigger(prev => prev + 1);
      fetchExams(1, pagination.limit, debouncedSearch);
      closeBulkUploadModal();
    } catch (err: any) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setBulkUploading(false);
    }
  };
  const [bulkPagination, setBulkPagination] = useState({
    page: 1,
    limit: 10,
    total: 0,
    totalPages: 0,
  });

  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">
            <FileClock className="text-blue-600" /> Previous Year Question Papers
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Manage and organize previous year question papers by exams.
          </p>
        </div>
        <div className="flex gap-3">
          <Button
            onClick={handleDownloadTemplate}
            icon={<Download size={16} />}
          >
            Bulk Upload Template
          </Button>
          <Button
            onClick={openBulkUploadModal}
            icon={<FileSpreadsheet size={16} />}
          >
            Bulk Upload
          </Button>
        </div>
      </div>

      <Card className="shadow-sm border border-slate-200 rounded-xl">
        <div className="flex justify-between items-center mb-6">
          <div className="w-full md:w-72">
            <Input
              placeholder="Search Exams..."
              prefix={<Search size={16} className="text-slate-400" />}
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
            />
          </div>
          <div className="text-slate-500 text-sm font-medium">
            Total Questions:{" "}
            <span className="text-slate-900">{totalQuestions}</span>
          </div>
        </div>

        <Spin spinning={loading}>
          {exams.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">
              <Search size={40} className="mb-2 opacity-20" />
              <p>No exams available</p>
            </div>
          ) : (
            <div className="space-y-3">
              {exams.map((exam) => (
                <OldQuestionTreeCard
                  key={exam.id}
                  exam={exam}
                  isOpen={openExamId === exam.id}
                  onToggle={() => toggleExam(exam.id)}
                  refreshTrigger={refreshTrigger}
                />
              ))}
            </div>
          )}
        </Spin>

        <div className="flex justify-end mt-6">
          <Pagination
            current={pagination.page}
            total={pagination.total}
            pageSize={pagination.limit}
            onChange={(p, pageSize) => {
              setPagination((prev) => ({ ...prev, page: p, limit: pageSize }));
              fetchExams(p, pageSize, debouncedSearch);
            }}
            showSizeChanger
          />
        </div>
      </Card>
      <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={{
                  current: bulkPagination.page,
                  total: bulkPagination.total,
                  pageSize: bulkPagination.limit,
                  showSizeChanger: true,
                  onChange: (page, pageSize) => {
                    setBulkPagination({
                      ...bulkPagination,
                      page,
                      limit: pageSize,
                    });
                  },
                  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>
  );
}

