import React, { useState, useEffect } from "react";
import { useParams, useNavigate } from "react-router-dom";
import axiosInstance from "../../../../utils/axiosConfig";
import {
  QUESTIONS_URL,
  QUESTION_TYPE_URL,
} from "../../../../utils/config";
import SuccessPopup from "../../../common/SuccessPopup";
import QuestionForm from "./QuestionForm";
import "../styles/QuestionProfile.css";

const QuestionUpdations = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [formData, setFormData] = useState({
    id: null,
    question: "",
    question_type_id: "",
    allows_media: false,
    options: [],
  });
  const [questionTypes, setQuestionTypes] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingData, setLoadingData] = useState(true);
  const [error, setError] = useState(null);
  const [showPopup, setShowPopup] = useState(false);
  const [popupMessage, setPopupMessage] = useState("");

  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")
    );
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoadingData(true);
        setError(null);

        const [questionRes, typesRes] = await Promise.all([
          axiosInstance.get(`${QUESTIONS_URL}/${id}`),
          axiosInstance.get(QUESTION_TYPE_URL),
        ]);

        if (typesRes.data.success) {
          setQuestionTypes(typesRes.data.data || []);
        }

        if (questionRes.data.success) {
          const question = questionRes.data.data;
          const optionsArr = Array.isArray(question.options) ? question.options : [];
          setFormData({
            id: question.question_id || question.id,
            question: question.question || "",
            question_type_id: question.question_type_id || "",
            allows_media: !!question.allows_media,
            options: optionsArr,
          });
        } else {
          setError("Question not found");
        }
      } catch (err) {
        console.error("Error fetching data:", err);
        setError(err.response?.data?.message || "Failed to load question data");
      } finally {
        setLoadingData(false);
      }
    };

    if (id) {
      fetchData();
    }
  }, [id]);

  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 {
      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}/${id}`, payload);

      if (response.data.success) {
        setPopupMessage("Question updated successfully!");
        setShowPopup(true);
      }
    } catch (err) {
      setError(err.response?.data?.message || "Failed to update question");
      console.error("Error updating question:", err);
    } finally {
      setLoading(false);
    }
  };

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

  if (loadingData) {
    return (
      <div className="form-section question-profile-loading">
        <p>Loading question data...</p>
      </div>
    );
  }

  return (
    <>
      <SuccessPopup
        show={showPopup}
        message={popupMessage}
        onClose={() => setShowPopup(false)}
        onOk={() => {
          setShowPopup(false);
          navigate("/questions");
        }}
      />

      <QuestionForm
        formData={formData}
        questionTypes={questionTypes}
        loading={loading}
        error={error}
        onSubmit={handleSubmit}
        onInputChange={handleInputChange}
        onOptionsChange={handleOptionsChange}
        onClearForm={resetForm}
      />
    </>
  );
};

export default QuestionUpdations;

