import React, { useEffect, useMemo, useState } from "react";
import {
  Button,
  Card,
  Typography,
  Pagination,
  Input,
  Spin,
  Empty,
  Select,
  Table,
} from "antd";
import {
  Search,
  Plus,
  Database,
  Download,
  FileSpreadsheet,
  UploadCloud,
  AlertCircle,
} from "lucide-react";
import { API_Instance } from "../../api/axios.instance";
import API_Constants from "../../constants/api.constants";
import { ISubjectQuestions } from "@/types";
import toast from "react-hot-toast";
import { getAxiosErrorMessage } from "@/utils/index.utils";
import ROUTE_CONSTANTS from "@/constants/route.constants";
import { useSearchParams, useNavigate } from "react-router-dom";
import { QuestionTreeCard } from "@/components/tree/QuestionTreeCard";
import { useDebounce } from "@/hooks/useDebounce";
import Modal from "@/components/shared/Modal";
import type { UploadFile } from "antd/es/upload/interface";
import { Upload, Tag } from "antd";

const { Text } = Typography;

const filterInitial = {
  search: "",
};

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

const QuestionBankPage: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [filterValues, setFilterValues] = useState(filterInitial);
  
  const [searchParams, setSearchParams] = useSearchParams();
  const openSubjectId = searchParams.get("subjectId");
  
  const [subjects, setSubjects] = useState<ISubjectQuestions[]>([]);
  const [totalQuestions, setTotalQuestions] = useState(0);
  const [totalTests, setTotalTests] = useState(0);
  const [pagination, setPagination] = useState(paginationInitial);
  const debouncedSearch = useDebounce(filterValues.search, 600);

  const [exams, setExams] = useState<any[]>([]);

  // 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 toggleSubject = (id: string) => {
    const newParams = new URLSearchParams(searchParams);
    if (openSubjectId === id) {
      newParams.delete("subjectId");
      newParams.delete("topicId");
    } else {
      newParams.set("subjectId", id);
      newParams.delete("topicId");
    }
    setSearchParams(newParams, { replace: true });
  };

  // Fetch subjects
  const fetchSubjects = async (page = 1, limit = 10) => {
    setLoading(true);
    try {
      const res = await API_Instance.get(
        API_Constants.subjects +
        "/questions" +
        `?page=${page}&limit=${limit}&search=${debouncedSearch}`,
      );
      setSubjects(res.data.data);
      setTotalQuestions(res.data.totalQuestions);
      setTotalTests(res.data.totalTests || 0);
      setPagination(res.data.meta || paginationInitial);
    } catch (err) {
      toast.error(getAxiosErrorMessage(err));
    } finally {
      setLoading(false);
    }
  };

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

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

  const handleDownloadTemplate = async () => {
    try {
      const response = await API_Instance.get(
        `${API_Constants.questionBank}/template`,
        { responseType: "blob" },
      );
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement("a");
      link.href = url;
      link.setAttribute("download", "question_bank_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.questionBank}/preview-bulk`,
        formData,
        { headers: { "Content-Type": "multipart/form-data" } },
      );

      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.questionBank}/confirm-bulk`,
        payload,
      );
      toast.success(
        `${validQuestions.length} Questions imported successfully.`,
      );
      closeBulkUploadModal();
      fetchSubjects(pagination.page, pagination.limit);
    } 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">
            <Database className="text-blue-600" /> Question Bank
          </h2>
          <p className="text-slate-500 text-sm mt-1">
            Add/Manage MCQ Questions & Answers.
          </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>
          {/* <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.Subjects}`)}
          >
            Add New Subject
          </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 subject..."
              prefix={<Search size={16} className="text-slate-400" />}
              allowClear
              value={filterValues.search}
              onChange={(e) => {
                setFilterValues({
                  ...filterValues,
                  search: e.target.value,
                });
              }}
            />
          </div>
          <div className="flex items-center gap-6 text-slate-500 text-sm">
            <div>
              Total Subjects:{" "}
              <span className="font-semibold text-slate-800">
                {pagination.total}
              </span>
            </div>
            <div>
              Total Tests:{" "}
              <span className="font-semibold text-slate-800">
                {totalTests}
              </span>
            </div>
            <div>
              Total Questions:{" "}
              <span className="font-semibold text-slate-800">
                {totalQuestions}
              </span>
            </div>
          </div>
        </div>

        <Spin spinning={loading}>
          {subjects.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">
                <Database size={32} className="text-slate-300" />
              </div>
              <p>
                {filterValues.search
                  ? "No subjects found matching your search"
                  : "No questions available"}
              </p>
            </div>
          ) : (
            <div className="space-y-3 min-h-[200px]">
              {subjects.map((quest: ISubjectQuestions) => (
                <QuestionTreeCard
                  key={quest.id}
                  subject={quest}
                  isOpen={openSubjectId === quest.id}
                  onToggle={() => toggleSubject(quest.id)}
                  disabled={quest.topicsCount === 0}
                />
              ))}
            </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,
              });
              fetchSubjects(p, pageSize);
            }}
            showSizeChanger
            showTotal={(total) => `Total ${total} items`}
          />
        </div>
      </Card>

      {/* Bulk Upload Modal */}
      <Modal
        isOpen={isBulkUploadModalOpen}
        onClose={closeBulkUploadModal}
        title="Question Bank Bulk Upload"
        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: "Subject",
                    dataIndex: "subjectName",
                  },
                  {
                    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"
                    loading={bulkUploading}
                    onClick={handleConfirmBulkUpload}
                  >
                    Confirm & Import Questions
                  </Button>
                </div>
              </div>
            </div>
          )}

          {/* {bulkStep === 2 && (
            <div className="space-y-6">
              <div className="bg-blue-50 p-4 rounded-xl border border-blue-100 flex gap-3 text-blue-800">
                <AlertCircle className="shrink-0" />
                <div>
                  <p className="font-bold">Batch Configuration</p>
                  <p className="text-sm">
                    Assign shared attributes to the{" "}
                    {previewQuestions.filter((q) => q.isValid).length} valid
                    questions.
                  </p>
                </div>
              </div>

              <div className="space-y-4">
                <div className="space-y-1.5">
                  <label className="text-sm font-semibold text-slate-700">
                    Select Exams
                  </label>
                  <Select
                    mode="multiple"
                    className="w-full"
                    placeholder="Apply to these exams"
                    value={batchSettings.exams}
                    onChange={(v) =>
                      setBatchSettings({ ...batchSettings, exams: v })
                    }
                    options={exams.map((e) => ({
                      label: e.examName,
                      value: e.id,
                    }))}
                  />
                </div>

                <div className="space-y-1.5">
                  <label className="text-sm font-semibold text-slate-700">
                    Override Subject (Optional)
                  </label>
                  <Select
                    className="w-full"
                    placeholder="Keep from Excel or select new"
                    allowClear
                    value={batchSettings.subject}
                    onChange={(v) =>
                      setBatchSettings({ ...batchSettings, subject: v })
                    }
                    options={subjects.map((s) => ({
                      label: s.subjectName,
                      value: s.id,
                    }))}
                  />
                  <p className="text-[10px] text-slate-400">
                    If left empty, the subject mentioned in each Excel row will
                    be used.
                  </p>
                </div>
              </div>

              <div className="flex justify-between pt-4 border-t">
                <Button onClick={() => setBulkStep(1)}>Back to Preview</Button>
                <Button
                  type="primary"
                  size="large"
                  loading={bulkUploading}
                  onClick={handleConfirmBulkUpload}
                >
                  Confirm & Import Questions
                </Button>
              </div>
            </div>
          )} */}
        </div>
      </Modal>
    </div>
  );
};

export default QuestionBankPage;

