import React, { useState, useEffect } from "react";
import axiosInstance from "../../../utils/axiosConfig";
import {
  QUESTIONS_URL,
  QUESTION_TYPE_URL
} from "../../../utils/config";
import SuccessPopup from "../../common/SuccessPopup";
import ConfirmPopup from "../../common/ConfirmPopup";
import TabNavigation from "./pages/TabNavigation";
import QuestionForm from "./pages/QuestionForm";
import QuestionsTable from "./pages/QuestionsTable";
import "./styles/Questions.css";

const Questions = () => {
  const [activeTab, setActiveTab] = useState("all");
  const [questions, setQuestions] = useState([]);
  const [questionTypes, setQuestionTypes] = useState([]);
  const [formData, setFormData] = useState({
    id: null, // For edit mode
    question: "",
    question_type_id: "",
    allows_media: false,
    options: [],
  });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");
  const [showConfirmPopup, setShowConfirmPopup] = useState(false);
  const [questionToDelete, setQuestionToDelete] = useState(null);

  const questionTypeNeedsOptions = (questionTypeId) => {
    if (!questionTypeId) return false;
    const idNum = parseInt(questionTypeId, 10);
    if (!Number.isNaN(idNum) && (idNum === 4 || idNum === 5)) {
      return true;
    }
    const type = questionTypes.find(
      (t) => String(t.question_type_id) === String(questionTypeId)
    );
    if (!type) return false;
    const name = (type.question_type || type.type_name || type.name || "").toLowerCase();
    return (
      name.includes("dropdown") ||
      name.includes("choice") ||
      name.includes("mmcq")
    );
  };

  // Fetch initial data
  useEffect(() => {
    fetchQuestions();
    fetchQuestionTypes();
  }, []);

  const fetchQuestions = async () => {
    try {
      setLoading(true);
      const response = await axiosInstance.get(QUESTIONS_URL);
      if (response.data.success) {
        setQuestions(response.data.data || []);
      }
    } catch (err) {
      console.error("Error fetching questions:", err);
      // don't set global error here to avoid blocking UI if just list fails
    } finally {
      setLoading(false);
    }
  };

  const fetchQuestionTypes = async () => {
    try {
      const response = await axiosInstance.get(QUESTION_TYPE_URL);
      // Assuming structure { success: true, data: [...] }
      if (response.data.success) {
        setQuestionTypes(response.data.data || []);
      }
    } catch (err) {
      console.error("Error fetching question types:", err);
    }
  };

  const handleInputChange = (e) => {
    const { name, value, type, checked } = e.target;
    setFormData((prev) => {
      const next = { ...prev, [name]: type === "checkbox" ? checked : value };
      if (name === "question_type_id") {
        if (questionTypeNeedsOptions(value)) {
          next.options = prev.options?.length ? prev.options : [""];
        } else {
          next.options = [];
        }
      }
      return next;
    });
  };

  const handleOptionsChange = (options) => {
    setFormData((prev) => ({ ...prev, options: options || [] }));
  };

  const getOptionsArray = () => {
    const opts = Array.isArray(formData.options) ? formData.options : [];
    const arr = opts.map((s) => String(s).trim()).filter(Boolean);
    return arr.length ? arr : undefined;
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);

    const needsOptions = questionTypeNeedsOptions(formData.question_type_id);
    const opts = getOptionsArray();
    if (needsOptions && !opts?.length) {
      setError("Please add at least one option for Single Selection Dropdown or Multiple Dropdown questions.");
      return;
    }

    setLoading(true);

    try {
      if (formData.id) {
        // Update
        const payload = {
          question: formData.question,
          question_type_id: formData.question_type_id,
          allows_media: formData.allows_media,
        };
        const opts = getOptionsArray();
        if (opts !== undefined) payload.options = opts;
        const response = await axiosInstance.put(`${QUESTIONS_URL}/${formData.id}`, payload);
        if (response.data.success) {
          setPopupMessage("Question updated successfully!");
          setShowPopup(true);
          resetForm();
          fetchQuestions();
          setActiveTab("all");
        }
      } else {
        // Create
        const payload = {
          question: formData.question,
          question_type_id: formData.question_type_id,
          allows_media: formData.allows_media,
        };
        const opts = getOptionsArray();
        if (opts !== undefined) payload.options = opts;
        const response = await axiosInstance.post(QUESTIONS_URL, payload);
        if (response.data.success) {
          setPopupMessage("Question created successfully!");
          setShowPopup(true);
          resetForm();
          fetchQuestions();
          // Stay on create question page (do not switch to "all" tab)
        }
      }
    } catch (err) {
      console.error("Submit error:", err);
      setError(err.response?.data?.message || "Failed to save question");
    } finally {
      setLoading(false);
    }
  };

  const handleDeleteClick = (id) => {
    setQuestionToDelete(id);
    setShowConfirmPopup(true);
  };

  const handleDeleteConfirm = async () => {
    if (!questionToDelete) return;

    try {
      setLoading(true);
      setShowConfirmPopup(false);
      const response = await axiosInstance.delete(`${QUESTIONS_URL}/${questionToDelete}`);
      if (response.data.success) {
        setPopupMessage("Question deleted successfully!");
        setShowPopup(true);
        fetchQuestions();
      }
    } catch (err) {
      console.error("Delete error:", err);
      setError(err.response?.data?.message || "Failed to delete question");
    } finally {
      setLoading(false);
      setQuestionToDelete(null);
    }
  };

  const handleDeleteCancel = () => {
    setShowConfirmPopup(false);
    setQuestionToDelete(null);
  };

  const resetForm = () => {
    setFormData({
      id: null,
      question: "",
      question_type_id: "",
      allows_media: false,
      options: [],
    });
    setError(null);
  };

  const handleTabChange = (tab) => {
    if (tab === "all") {
        resetForm();
    }
    setActiveTab(tab);
  };

  return (
    <>
      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => setShowPopup(false)}
      />

      <ConfirmPopup
        show={showConfirmPopup}
        title="Delete Question"
        message="Are you sure you want to delete this question? This action cannot be undone."
        onConfirm={handleDeleteConfirm}
        onCancel={handleDeleteCancel}
      />

      <div className="questions-management-page">
      <TabNavigation activeTab={activeTab} onTabChange={handleTabChange} />

      {activeTab === "create" && (
        <QuestionForm
          formData={formData}
          questionTypes={questionTypes}
          loading={loading}
          error={error}
          onSubmit={handleSubmit}
          onInputChange={handleInputChange}
          onOptionsChange={handleOptionsChange}
          onClearForm={resetForm}
        />
      )}

      {activeTab === "all" && (
        <QuestionsTable
          questions={questions}
          questionTypes={questionTypes}
          loading={loading}
          onDelete={handleDeleteClick}
        />
      )}
      </div>
    </>
  );
};

export default Questions;
