"use client";
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { usePsychometricApi } from "@/hooks/usePsychometricApi";
import useAuth from "@/app/useAuth";

type Library = {
  id: number;
  name: string;
  title?: string;
  description?: string;
  noOfQuestions?: number;
};

const CreateExam = () => {
  const psychApi = usePsychometricApi();
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [title, setTitle] = useState("");
  const [description, setDescription] = useState("");
  const [duration, setDuration] = useState(30);
  const [selectedLibraryId, setSelectedLibraryId] = useState<number | null>(
    null,
  );
  const [loading, setLoading] = useState(false);
  const router = useRouter();
  // admin useAuth performs redirect as a side-effect and does not return auth fields
  const auth = useAuth() as any;

  // State for viewing library questions in modal
  const [viewingLibraryId, setViewingLibraryId] = useState<number | null>(null);
  const [viewingLibraryQuestions, setViewingLibraryQuestions] = useState<any[]>(
    [],
  );
  const [viewingLibraryName, setViewingLibraryName] = useState("");
  const [loadingViewQuestions, setLoadingViewQuestions] = useState(false);

  // State for editing a question
  const [editingQuestionId, setEditingQuestionId] = useState<number | null>(
    null,
  );
  const [editingQuestion, setEditingQuestion] = useState<any>(null);
  const [editTitle, setEditTitle] = useState("");
  const [editTopic, setEditTopic] = useState("");
  const [editOptions, setEditOptions] = useState<{ [key: string]: string }>({});
  const [editWeights, setEditWeights] = useState<{ [key: string]: number }>({});
  const [editAnswer, setEditAnswer] = useState<string>("");
  const [savingQuestion, setSavingQuestion] = useState(false);
  const [isAddingQuestion, setIsAddingQuestion] = useState(false);

  useEffect(() => {
    // Init data on mount; useAuth will redirect to signin if missing token
    fetchLibraries();
  }, []);

  const fetchLibraries = async () => {
    try {
      setLoading(true);
      const libs = await psychApi.getQuestionLibraries();

      // Fetch actual question counts for each library
      const normalized = await Promise.all(
        (libs || []).map(async (l: any) => {
          let questionCount = 0;

          // Always fetch questions to get accurate count
          try {
            const questions = await psychApi.getQuestions(l.id);
            questionCount = Array.isArray(questions) ? questions.length : 0;
          } catch (err) {
            console.debug(
              `Could not fetch questions for library ${l.id}:`,
              err,
            );
            // Fallback to library's noOfQuestions if API fails
            questionCount = l.noOfQuestions || 0;
          }

          return {
            id: l.id,
            name:
              (l as any).name ||
              l.title ||
              l.title_en ||
              l.subject ||
              "Untitled",
            title: l.title,
            description: l.description,
            noOfQuestions: questionCount,
          };
        }),
      );
      setLibraries(normalized);
    } catch (err) {
      console.error("Failed to fetch libraries", err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateExam = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedLibraryId) return alert("Please select a question library");
    if (!title.trim()) return alert("Please enter exam title");

    try {
      setLoading(true);
      const payload = {
        psychometricQuestionLibraryId: selectedLibraryId,
        title: title,
        description: description || "",
        duration: duration || 30,
        isActive: true,
      };

      await psychApi.createExam(payload as any);

      alert("Exam created successfully!");
      setTitle("");
      setDescription("");
      setDuration(30);
      setSelectedLibraryId(null);
      fetchLibraries();
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Create exam failed:", errorMessage, err);
      alert("Failed to create exam: " + errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // Function to view questions for a specific library in modal
  const handleViewLibraryQuestions = async (
    libraryId: number,
    libraryName: string,
  ) => {
    try {
      setLoadingViewQuestions(true);
      setViewingLibraryId(libraryId);
      setViewingLibraryName(libraryName);

      // Use getQuestions to get questions for this library
      const questions = await psychApi.getQuestions(libraryId);
      setViewingLibraryQuestions(questions || []);
    } catch (err) {
      console.error("Failed to fetch library questions", err);
      setViewingLibraryQuestions([]);
      alert("Failed to load questions for this library");
    } finally {
      setLoadingViewQuestions(false);
    }
  };

  const handleCreateNewLibrary = () => {
    sessionStorage.setItem("redirectTo", "create-exam");
    router.push("/psychometric-test/create-questionset");
  };

  const handleDeleteQuestion = async (questionId: number) => {
    if (!window.confirm("Are you sure you want to delete this question?")) {
      return;
    }

    try {
      await psychApi.deleteQuestion(questionId);
      // Refresh both the libraries list (to update question count) and the questions view
      await fetchLibraries();
      if (viewingLibraryId) {
        handleViewLibraryQuestions(viewingLibraryId, viewingLibraryName);
      }
    } catch (err: any) {
      console.error("Failed to delete question:", err);
      alert("Failed to delete question");
    }
  };

  const handleDeleteLibrary = async (libraryId: number) => {
    if (
      !window.confirm(
        "Are you sure you want to delete this library and all its questions?",
      )
    ) {
      return;
    }

    try {
      await psychApi.deleteQuestionLibrary(libraryId);
      setViewingLibraryId(null);
      setViewingLibraryQuestions([]);
      setViewingLibraryName("");
      fetchLibraries();
      if (selectedLibraryId === libraryId) {
        setSelectedLibraryId(null);
      }
    } catch (err: any) {
      console.error("Failed to delete library:", err);
      alert("Failed to delete library");
    }
  };

  // Function to close the viewing modal
  const handleCloseViewQuestions = () => {
    setViewingLibraryId(null);
    setViewingLibraryQuestions([]);
    setViewingLibraryName("");
  };

  // Function to open edit modal for a question
  const handleEditQuestion = (question: any) => {
    setEditingQuestionId(question.id);
    setEditingQuestion(question);
    setEditTitle(question.questionText || "");
    setEditTopic(question.topic || "");
    setEditOptions(question.options || { A: "", B: "", C: "", D: "" });
    setEditWeights(question.weights || { A: 0, B: 0, C: 0, D: 0 });
    setEditAnswer(question.answer || "");
  };

  // Function to close edit modal
  const handleCloseEditQuestion = () => {
    setEditingQuestionId(null);
    setEditingQuestion(null);
    setEditTitle("");
    setEditTopic("");
    setEditOptions({});
    setEditWeights({});
    setEditAnswer("");
    setIsAddingQuestion(false);
  };

  // Open add-question modal
  const handleOpenAddQuestion = () => {
    setIsAddingQuestion(true);
    setEditingQuestionId(null);
    setEditingQuestion(null);
    setEditTitle("");
    setEditTopic("");
    // default two options
    setEditOptions({ A: "", B: "" });
    setEditWeights({ A: 0, B: 0 });
    setEditAnswer("");
  };

  // Function to add a new option
  const handleAddOption = () => {
    const currentKeys = Object.keys(editOptions);
    let nextKey = "E";

    // Find the next available key
    for (let i = 0; i < 26; i++) {
      const letter = String.fromCharCode(65 + i); // A=65, Z=90
      if (!currentKeys.includes(letter)) {
        nextKey = letter;
        break;
      }
    }

    setEditOptions({ ...editOptions, [nextKey]: "" });
    setEditWeights({ ...editWeights, [nextKey]: 0 });
  };

  // Function to remove an option
  const handleRemoveOption = (optionKey: string) => {
    const newOptions = { ...editOptions };
    const newWeights = { ...editWeights };
    delete newOptions[optionKey];
    delete newWeights[optionKey];

    // Update answer if it was the removed option
    if (editAnswer === optionKey) {
      setEditAnswer("");
    }

    setEditOptions(newOptions);
    setEditWeights(newWeights);
  };

  // Function to save edited question
  const handleSaveEditedQuestion = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!editTitle.trim()) return alert("Question title is required");
    if (!editAnswer) return alert("Correct answer is required");

    try {
      setSavingQuestion(true);
      const payload = {
        psychometricQuestionLibraryId: viewingLibraryId,
        questionText: editTitle,
        topic: editTopic,
        options: editOptions,
        weights: editWeights,
        answer: editAnswer,
      };

      if (isAddingQuestion) {
        await psychApi.createQuestion(payload as any);
        alert("Question created successfully!");
      } else {
        await psychApi.updateQuestion(editingQuestionId!, payload as any);
        alert("Question updated successfully!");
      }
      handleCloseEditQuestion();
      // Refresh both the libraries list (to update question count) and the questions view
      await fetchLibraries();
      if (viewingLibraryId) {
        handleViewLibraryQuestions(viewingLibraryId, viewingLibraryName);
      }
    } catch (err: any) {
      console.error("Failed to update question:", err);
      alert("Failed to update question");
    } finally {
      setSavingQuestion(false);
    }
  };

  return (
    <>
      <div className="page-wrapper dashboard">
        <section className="user-dashboard">
          <div className="dashboard-outer container">
            <div className="row">
              {/* Left Column: Create Exam */}
              <div className="col-lg-4">
                <div className="ls-widget p-4">
                  <h5>Create New Exam</h5>

                  <div className="mb-3">
                    <label className="form-label">Exam Title *</label>
                    <input
                      type="text"
                      value={title}
                      onChange={(e) => setTitle(e.target.value)}
                      placeholder="e.g., Software Engineer Assessment"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Description</label>
                    <textarea
                      value={description}
                      onChange={(e) => setDescription(e.target.value)}
                      placeholder="Description (optional)"
                      rows={3}
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Duration (minutes) *</label>
                    <input
                      type="number"
                      value={duration}
                      onChange={(e) => {
                        const val = e.target.value;
                        setDuration(val === "" ? 30 : parseInt(val));
                      }}
                      placeholder="Duration in minutes"
                      min={1}
                      max={480}
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Select Library *</label>
                    <select
                      value={selectedLibraryId || ""}
                      onChange={(e) =>
                        setSelectedLibraryId(
                          e.target.value ? Number(e.target.value) : null,
                        )
                      }
                      className="form-control"
                    >
                      <option value="">-- Select a library --</option>
                      {libraries.map((lib) => (
                        <option key={lib.id} value={lib.id}>
                          {lib.name || lib.title} ({lib.noOfQuestions || 0}{" "}
                          questions)
                        </option>
                      ))}
                    </select>
                  </div>

                  <button
                    className="theme-btn btn-style-one w-100"
                    onClick={handleCreateExam}
                    disabled={loading || !selectedLibraryId || !title.trim()}
                  >
                    {loading ? "Creating..." : "Create Exam"}
                  </button>
                </div>
              </div>

              {/* Right Column: Question Libraries */}
              <div className="col-lg-8">
                <div className="ls-widget p-4">
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginBottom: "20px",
                    }}
                  >
                    <h5 style={{ margin: 0 }}>
                      Question Libraries ({libraries.length})
                    </h5>
                    <button
                      className="theme-btn btn-style-one"
                      style={{
                        display: "inline-block",
                        padding: "10px 20px",
                        fontSize: "14px",
                        borderRadius: "4px",
                      }}
                      onClick={handleCreateNewLibrary}
                    >
                      + Create New Library
                    </button>
                  </div>

                  {loading ? (
                    <p>Loading...</p>
                  ) : libraries.length === 0 ? (
                    <p className="text-muted">No libraries available</p>
                  ) : (
                    <div style={{ maxHeight: "600px", overflowY: "auto" }}>
                      {libraries.map((lib) => (
                        <div
                          key={lib.id}
                          style={{
                            marginBottom: "15px",
                            padding: "12px",
                            border: "1px solid #dee2e6",
                            borderRadius: "4px",
                            backgroundColor: "#f8f9fa",
                          }}
                        >
                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "start",
                            }}
                          >
                            <div style={{ flex: 1 }}>
                              <h6 style={{ margin: "0 0 5px 0" }}>
                                {lib.name || lib.title}
                              </h6>
                              <small className="text-muted">
                                {lib.noOfQuestions || 0} questions
                              </small>
                              {lib.description && (
                                <p
                                  style={{
                                    margin: "5px 0 0 0",
                                    fontSize: "12px",
                                    color: "#666",
                                  }}
                                >
                                  {lib.description}
                                </p>
                              )}
                            </div>
                            <div
                              style={{
                                display: "flex",
                                gap: "5px",
                                marginLeft: "10px",
                              }}
                            >
                              <button
                                className="theme-btn btn-style-one"
                                style={{
                                  display: "inline-block",
                                  padding: "4px 8px",
                                  fontSize: "12px",
                                  borderRadius: "4px",
                                }}
                                onClick={() =>
                                  handleViewLibraryQuestions(lib.id, lib.name)
                                }
                              >
                                View
                              </button>
                              <button
                                className="btn btn-sm btn-danger"
                                onClick={() => handleDeleteLibrary(lib.id)}
                                style={{
                                  padding: "4px 8px",
                                  fontSize: "12px",
                                }}
                              >
                                Delete
                              </button>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>

      {/* Modal for viewing library questions */}
      {viewingLibraryId && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0,0,0,0.5)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1050,
          }}
          onClick={handleCloseViewQuestions}
        >
          <div
            style={{
              backgroundColor: "white",
              borderRadius: "8px",
              maxWidth: "900px",
              width: "90%",
              maxHeight: "90vh",
              display: "flex",
              flexDirection: "column",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: "20px",
                borderBottom: "1px solid #dee2e6",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h5 style={{ margin: 0 }}>Questions in: {viewingLibraryName}</h5>
              <div
                style={{ display: "flex", gap: "10px", alignItems: "center" }}
              >
                <button
                  className="theme-btn btn-style-one"
                  style={{
                    display: "inline-block",
                    padding: "5px 10px",
                    fontSize: "14px",
                    borderRadius: "4px",
                  }}
                  onClick={() => handleOpenAddQuestion()}
                >
                  + Add Question
                </button>
                <button
                  className="btn btn-sm btn-danger"
                  onClick={() => {
                    handleDeleteLibrary(viewingLibraryId!);
                  }}
                >
                  Delete Library
                </button>
                <button
                  type="button"
                  className="btn-close"
                  onClick={handleCloseViewQuestions}
                  aria-label="Close"
                ></button>
              </div>
            </div>
            <div style={{ padding: "20px", overflowY: "auto", flex: 1 }}>
              {loadingViewQuestions ? (
                <div style={{ textAlign: "center", padding: "40px 0" }}>
                  <div className="spinner-border text-primary" role="status">
                    <span className="visually-hidden">Loading...</span>
                  </div>
                  <p style={{ marginTop: "10px" }}>Loading questions...</p>
                </div>
              ) : viewingLibraryQuestions.length === 0 ? (
                <div style={{ textAlign: "center", padding: "40px 0" }}>
                  <p style={{ color: "#6c757d" }}>
                    No questions found in this library.
                  </p>
                </div>
              ) : (
                <div>
                  {viewingLibraryQuestions.map((q: any, idx: number) => (
                    <div
                      key={q.id}
                      style={{
                        marginBottom: "20px",
                        padding: "15px",
                        border: "1px solid #dee2e6",
                        borderRadius: "8px",
                        backgroundColor: "#f8f9fa",
                      }}
                    >
                      <div
                        style={{
                          display: "flex",
                          justifyContent: "space-between",
                          alignItems: "flex-start",
                          marginBottom: "10px",
                        }}
                      >
                        <h6 style={{ marginBottom: "5px" }}>
                          <span
                            className="badge bg-primary"
                            style={{ marginRight: "10px" }}
                          >
                            {idx + 1}
                          </span>
                          {q.questionText}
                        </h6>
                        <div
                          style={{
                            display: "flex",
                            gap: "5px",
                            marginLeft: "10px",
                          }}
                        >
                          <button
                            className="btn btn-sm btn-warning"
                            onClick={() => handleEditQuestion(q)}
                            style={{
                              padding: "4px 8px",
                              fontSize: "12px",
                            }}
                          >
                            Edit
                          </button>
                          <button
                            className="btn btn-sm btn-danger"
                            onClick={() => handleDeleteQuestion(q.id)}
                            style={{
                              padding: "4px 8px",
                              fontSize: "12px",
                            }}
                          >
                            Delete
                          </button>
                        </div>
                      </div>
                      <p
                        style={{
                          fontSize: "14px",
                          color: "#6c757d",
                          marginBottom: "15px",
                        }}
                      >
                        <strong>Topic:</strong> {q.topic || "N/A"}
                      </p>
                      <div>
                        {q.options &&
                          Object.entries(q.options).map(
                            ([key, value]: [string, any]) => (
                              <div
                                key={key}
                                style={{
                                  display: "flex",
                                  alignItems: "center",
                                  marginBottom: "10px",
                                  padding: "10px",
                                  borderRadius: "4px",
                                  backgroundColor:
                                    q.answer === key
                                      ? "rgba(25, 135, 84, 0.1)"
                                      : "#fff",
                                  border:
                                    q.answer === key
                                      ? "1px solid #198754"
                                      : "1px solid #dee2e6",
                                }}
                              >
                                <span
                                  className={`badge ${q.answer === key ? "bg-success" : "bg-secondary"}`}
                                  style={{
                                    minWidth: "30px",
                                    marginRight: "10px",
                                  }}
                                >
                                  {key}
                                </span>
                                <span style={{ flex: 1 }}>{value}</span>
                                <span
                                  className="badge bg-light text-dark"
                                  style={{ marginLeft: "10px" }}
                                >
                                  Weight: {q.weights?.[key] || 0}
                                </span>
                              </div>
                            ),
                          )}
                      </div>
                      {/* {q.answer && (
                        <div style={{ marginTop: "10px" }}>
                          <small style={{ color: "#198754" }}>
                            <strong>✓ Correct Answer:</strong> {q.answer}
                          </small>
                        </div>
                      )} */}
                    </div>
                  ))}
                </div>
              )}
            </div>
          </div>
        </div>
      )}

      {/* Modal for editing a question */}
      {(editingQuestionId !== null || isAddingQuestion) && (
        <div
          style={{
            position: "fixed",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            backgroundColor: "rgba(0,0,0,0.5)",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            zIndex: 1051,
          }}
          onClick={handleCloseEditQuestion}
        >
          <div
            style={{
              backgroundColor: "white",
              borderRadius: "8px",
              maxWidth: "700px",
              width: "90%",
              maxHeight: "90vh",
              display: "flex",
              flexDirection: "column",
            }}
            onClick={(e) => e.stopPropagation()}
          >
            <div
              style={{
                padding: "20px",
                borderBottom: "1px solid #dee2e6",
                display: "flex",
                justifyContent: "space-between",
                alignItems: "center",
              }}
            >
              <h5 style={{ margin: 0 }}>
                {isAddingQuestion ? "Add Question" : "Edit Question"}
              </h5>
              <button
                type="button"
                className="btn-close"
                onClick={handleCloseEditQuestion}
                aria-label="Close"
              ></button>
            </div>
            <div style={{ padding: "20px", overflowY: "auto", flex: 1 }}>
              <form onSubmit={handleSaveEditedQuestion}>
                <div className="mb-3">
                  <label className="form-label">Question *</label>
                  <textarea
                    value={editTitle}
                    onChange={(e) => setEditTitle(e.target.value)}
                    className="form-control"
                    rows={3}
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Topic</label>
                  <input
                    type="text"
                    value={editTopic}
                    onChange={(e) => setEditTopic(e.target.value)}
                    className="form-control"
                  />
                </div>

                <div className="mb-3">
                  <label className="form-label">Options *</label>
                  {Object.entries(editOptions).map(([key, value]) => (
                    <div key={key} className="mb-2">
                      <div
                        style={{
                          display: "flex",
                          gap: "10px",
                          alignItems: "flex-end",
                        }}
                      >
                        <div style={{ flex: 1 }}>
                          <label
                            className="form-label"
                            style={{ fontSize: "12px" }}
                          >
                            Option {key}
                          </label>
                          <input
                            type="text"
                            value={value || ""}
                            onChange={(e) =>
                              setEditOptions({
                                ...editOptions,
                                [key]: e.target.value,
                              })
                            }
                            className="form-control"
                            placeholder={`Option ${key}`}
                          />
                        </div>
                        <div style={{ width: "80px" }}>
                          <label
                            className="form-label"
                            style={{ fontSize: "12px" }}
                          >
                            Weight
                          </label>
                          <input
                            type="number"
                            value={editWeights[key] || 0}
                            onChange={(e) =>
                              setEditWeights({
                                ...editWeights,
                                [key]: parseInt(e.target.value) || 0,
                              })
                            }
                            className="form-control"
                            min="0"
                          />
                        </div>
                        {Object.keys(editOptions).length > 1 && (
                          <button
                            type="button"
                            className="btn btn-sm btn-danger"
                            onClick={() => handleRemoveOption(key)}
                            style={{ padding: "4px 8px", marginBottom: "0px" }}
                          >
                            Remove
                          </button>
                        )}
                      </div>
                    </div>
                  ))}
                  <button
                    type="button"
                    className="theme-btn btn-style-one"
                    style={{
                      display: "inline-block",
                      padding: "5px 10px",
                      fontSize: "14px",
                      borderRadius: "4px",
                    }}
                    onClick={handleAddOption}
                  >
                    + Add Option
                  </button>
                </div>

                {/* <div className="mb-3">
                  <label className="form-label">Correct Answer *</label>
                  <input
                    type="text"
                    value={editAnswer}
                    onChange={(e) => setEditAnswer(e.target.value)}
                    placeholder="Enter the key of correct answer (e.g., A)"
                    className="form-control"
                  />
                  <small className="text-muted">
                    Must match one of the option keys above
                  </small>
                </div> */}

                <div
                  style={{
                    display: "flex",
                    gap: "10px",
                    justifyContent: "flex-end",
                  }}
                >
                  <button
                    type="button"
                    className="btn btn-danger"
                    onClick={handleCloseEditQuestion}
                    disabled={savingQuestion}
                  >
                    Cancel
                  </button>
                  <button
                    type="submit"
                    className="theme-btn btn-style-one"
                    style={{
                      display: "inline-block",
                      padding: "10px 20px",
                      fontSize: "14px",
                      borderRadius: "4px",
                    }}
                    disabled={savingQuestion}
                  >
                    {savingQuestion ? "Saving..." : "Save Changes"}
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default CreateExam;
