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

type QuestionOption = {
  key: string;
  text: string;
  weight: number;
};

type Question = {
  id?: string;
  questionText: string;
  topic: string;
  correctAnswer: string;
  options: QuestionOption[];
};

const CreateQuestionSet = () => {
  const psychApi = usePsychometricApi();
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [subject, setSubject] = useState("");
  const [role, setRole] = useState("");
  const [noOfQuestions, setNoOfQuestions] = useState<number | "">(0);
  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);

  const [questions, setQuestions] = useState<Question[]>([
    {
      id: `q-${Date.now()}`,
      questionText: "",
      topic: "",
      correctAnswer: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
    },
  ]);

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

  const fetchLibraries = async () => {
    try {
      setLoading(true);
      const libs = await psychApi.getQuestionLibraries();
      const normalized = (libs || []).map((l: any) => ({
        id: l.id,
        name:
          (l as any).name || l.title || l.title_en || l.subject || "Untitled",
      }));
      setLibraries(normalized);
    } catch (err) {
      console.error("Failed to fetch libraries", err);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateLibrary = async () => {
    if (!name.trim()) return alert("Enter library name");
    const isDuplicate = libraries.some(
      (lib) => lib.name.toLowerCase() === name.trim().toLowerCase()
    );
    if (isDuplicate) {
      alert("Library name already exists");
      return;
    }
    try {
      const lib = await psychApi.createQuestionLibrary({
        title: name,
        description: description || undefined,
        subject: subject || undefined,
        role: role || undefined,
        noOfQuestions:
          typeof noOfQuestions === "number" ? noOfQuestions : undefined,
      });
      if (!lib || !lib.id) {
        console.error("Invalid library response - missing id:", lib);
        alert("Failed to create library: Invalid response from server");
        return;
      }
      const normalized = {
        id: lib.id,
        name: (lib as any).name || lib.title || name,
      };
      setLibraries((prev) => [normalized, ...prev]);
      setName("");
      setDescription("");
      setSubject("");
      setRole("");
      setNoOfQuestions(0);
      setSelectedLibraryId(lib.id);
      alert("Library created successfully");
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Create library failed - Full Error:", err);
      alert("Failed to create library: " + errorMessage);
    }
  };

  const handleAddQuestion = () => {
    const newQuestion: Question = {
      id: `q-${Date.now()}`,
      questionText: "",
      topic: "",
      correctAnswer: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
    };
    setQuestions([...questions, newQuestion]);
  };

  const handleRemoveQuestion = (questionId: string) => {
    if (questions.length <= 1)
      return alert("At least one question is required");
    setQuestions(questions.filter((q) => q.id !== questionId));
  };

  const handleQuestionChange = (
    questionId: string,
    field: keyof Question,
    value: any,
  ) => {
    setQuestions(
      questions.map((q) =>
        q.id === questionId ? { ...q, [field]: value } : q,
      ),
    );
  };

  const handleAddOption = (questionId: string) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          // Auto-generate the next key (A, B, C, ...)
          const currentKeys = q.options.map((opt) => opt.key);
          let nextKey = "A";
          for (let i = 0; i < 26; i++) {
            const letter = String.fromCharCode(65 + i);
            if (!currentKeys.includes(letter)) {
              nextKey = letter;
              break;
            }
          }
          return {
            ...q,
            options: [...q.options, { key: nextKey, text: "", weight: 0 }],
          };
        }
        return q;
      }),
    );
  };

  const handleRemoveOption = (questionId: string, optionIndex: number) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          if (q.options.length <= 1) {
            alert("At least one option is required");
            return q;
          }
          const removedKey = q.options[optionIndex].key;
          const newOptions = q.options
            .filter((_, i) => i !== optionIndex)
            .map((opt, i) => ({
              ...opt,
              key: String.fromCharCode(65 + i), // Reassign keys: A, B, C, ...
            }));
          // Update correct answer if it was the removed key
          let correctAnswer = q.correctAnswer;
          if (q.correctAnswer === removedKey) {
            correctAnswer = "";
          } else {
            // Find the new key for the correct answer
            const oldCorrectIndex = q.options.findIndex(
              (opt) => opt.key === q.correctAnswer,
            );
            if (oldCorrectIndex !== -1 && oldCorrectIndex !== optionIndex) {
              const newIndex =
                oldCorrectIndex > optionIndex
                  ? oldCorrectIndex - 1
                  : oldCorrectIndex;
              correctAnswer = String.fromCharCode(65 + newIndex);
            }
          }
          return { ...q, options: newOptions, correctAnswer };
        }
        return q;
      }),
    );
  };

  const handleOptionChange = (
    questionId: string,
    optionIndex: number,
    field: "key" | "text" | "weight",
    value: string | number,
  ) => {
    setQuestions(
      questions.map((q) => {
        if (q.id === questionId) {
          const newOptions = [...q.options];
          if (field === "weight") {
            newOptions[optionIndex][field] =
              typeof value === "number"
                ? value
                : parseInt(value as string) || 0;
          } else {
            newOptions[optionIndex][field] = value as string;
          }
          return { ...q, options: newOptions };
        }
        return q;
      }),
    );
  };

  const validateQuestion = (
    question: Question,
    index: number,
  ): string | null => {
    if (!question.questionText.trim()) {
      return `Question ${index + 1}: Enter question text`;
    }
    if (!question.topic.trim()) {
      return `Question ${index + 1}: Enter topic`;
    }
    if (!question.correctAnswer.trim()) {
      return `Question ${index + 1}: Select correct answer`;
    }

    for (let i = 0; i < question.options.length; i++) {
      const opt = question.options[i];
      if (!opt.text.trim()) {
        return `Question ${index + 1}, Option ${opt.key}: Please fill option text`;
      }
    }

    const keys = question.options.map((opt) => opt.key);
    const uniqueKeys = new Set(keys);
    if (keys.length !== uniqueKeys.size) {
      return `Question ${index + 1}: Option keys must be unique`;
    }

    if (!keys.includes(question.correctAnswer)) {
      return `Question ${index + 1}: Correct answer must match one of the option keys`;
    }

    return null;
  };

  const handleSaveAllQuestions = async () => {
    if (!selectedLibraryId) return alert("Select a library first");

    for (let i = 0; i < questions.length; i++) {
      const validationError = validateQuestion(questions[i], i);
      if (validationError) {
        return alert(validationError);
      }
    }

    try {
      setLoading(true);
      const payloads: any[] = [];
      const errors: string[] = [];

      // Prepare payloads
      for (let idx = 0; idx < questions.length; idx++) {
        const question = questions[idx];
        const optionsObj: { [key: string]: string } = {};
        const weightsObj: { [key: string]: number } = {};

        question.options.forEach((opt) => {
          optionsObj[opt.key] = opt.text;
          weightsObj[opt.key] = opt.weight;
        });

        const payload = {
          psychometricQuestionLibraryId: selectedLibraryId,
          questionText: question.questionText,
          options: optionsObj,
          answer: question.correctAnswer,
          weights: weightsObj,
          topic: question.topic,
          isActive: true,
        };
        payloads.push(payload);
      }

      // Send bulk request
      try {
        const createdQuestions =
          await psychApi.createMultipleQuestions(payloads);
        const successCount = createdQuestions.length;

        alert(`All ${successCount} questions saved successfully!`);
        setQuestions([
          {
            id: `q-${Date.now()}`,
            questionText: "",
            topic: "",
            correctAnswer: "",
            options: [
              { key: "A", text: "", weight: 0 },
              { key: "B", text: "", weight: 0 },
            ],
          },
        ]);
        // Redirect to create-exam page after successful save (admin app route)
        const redirectTo =
          sessionStorage.getItem("redirectTo") || "create-exam";
        sessionStorage.removeItem("redirectTo");
        router.push(`/psychometric-test/${redirectTo}`);
      } catch (err: any) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        console.error("Failed to save questions:", err);

        // Handle backend returning specific error messages for bulk failure if possible
        // For now, show the main error
        alert("Failed to save questions: " + errorMsg);
      }
    } catch (err) {
      const errMsg = err instanceof Error ? err.message : String(err);
      console.error("Save questions failed:", errMsg, err);
      alert("Failed to save questions: " + errMsg);
    } finally {
      setLoading(false);
    }
  };

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

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

                  <div className="mb-3">
                    <label className="form-label">Library Name *</label>
                    <input
                      type="text"
                      value={name}
                      onChange={(e) => setName(e.target.value)}
                      placeholder="Library name"
                      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">Subject *</label>
                    <input
                      type="text"
                      value={subject}
                      onChange={(e) => setSubject(e.target.value)}
                      placeholder="Subject (e.g., Psychology)"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Role *</label>
                    <input
                      type="text"
                      value={role}
                      onChange={(e) => setRole(e.target.value)}
                      placeholder="Role (e.g., Software Engineer)"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Number of Questions *</label>
                    <input
                      type="number"
                      value={noOfQuestions}
                      onChange={(e) => {
                        const val = e.target.value;
                        setNoOfQuestions(val === "" ? "" : parseInt(val));
                      }}
                      placeholder="Number of questions"
                      min={1}
                      className="form-control"
                    />
                  </div>

                  <button
                    className="theme-btn btn-style-one w-100"
                    onClick={handleCreateLibrary}
                  >
                    Create Library
                  </button>

                  <div className="mb-3 mt-4">
                    <label className="form-label">
                      Or Select Existing 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}
                        </option>
                      ))}
                    </select>
                    {selectedLibraryId && (
                      <small className="text-success d-block mt-2">
                        ✓ Library selected for adding questions
                      </small>
                    )}
                  </div>
                </div>
              </div>

              {/* Right Column: Total Questions - Only visible when library is selected */}
              {selectedLibraryId ? (
                <div className="col-lg-8">
                  <div className="ls-widget p-4">
                    <div className="d-flex justify-content-between align-items-center mb-4">
                      <h5>Total Questions ({questions.length})</h5>
                      <button
                        type="button"
                        className="theme-btn btn-style-one"
                        style={{
                          display: "inline-block",
                          padding: "10px 20px",
                          fontSize: "14px",
                          borderRadius: "4px",
                        }}
                        onClick={handleAddQuestion}
                      >
                        + Add Another Question
                      </button>
                    </div>

                    {[...questions].reverse().map((question, qIndex) => (
                      <div
                        key={question.id}
                        className="question-form mb-4 p-3 border rounded"
                        style={{ backgroundColor: "#f8f9fa" }}
                      >
                        <div className="d-flex justify-content-between align-items-center mb-3">
                          <h6 className="mb-0">
                            Question {questions.length - qIndex}
                          </h6>
                          {questions.length > 1 && (
                            <button
                              type="button"
                              className="btn btn-danger btn-sm"
                              onClick={() => handleRemoveQuestion(question.id!)}
                            >
                              Remove Question
                            </button>
                          )}
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Topic *</label>
                          <input
                            type="text"
                            value={question.topic}
                            onChange={(e) =>
                              handleQuestionChange(
                                question.id!,
                                "topic",
                                e.target.value,
                              )
                            }
                            placeholder="e.g., Teamwork, Stress Management"
                            className="form-control"
                          />
                        </div>

                        <div className="mb-3">
                          <label className="form-label">Question Text *</label>
                          <textarea
                            value={question.questionText}
                            onChange={(e) =>
                              handleQuestionChange(
                                question.id!,
                                "questionText",
                                e.target.value,
                              )
                            }
                            placeholder="Enter your question"
                            rows={3}
                            className="form-control"
                          />
                        </div>

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

                        {/* <div className="mb-3">
                        <label className="form-label">Correct Answer *</label>
                        <input
                          type="text"
                          value={question.correctAnswer}
                          onChange={(e) =>
                            handleQuestionChange(
                              question.id!,
                              "correctAnswer",
                              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>
                    ))}

                    <button
                      className="theme-btn btn-style-one w-100"
                      onClick={handleSaveAllQuestions}
                      disabled={loading}
                    >
                      {loading
                        ? "Saving..."
                        : `Save All Questions (${questions.length})`}
                    </button>
                  </div>
                </div>
              ) : (
                <div className="col-lg-8">
                  <div className="ls-widget p-4 text-center">
                    <div style={{ padding: "60px 20px" }}>
                      <div
                        style={{
                          fontSize: "48px",
                          color: "#dee2e6",
                          marginBottom: "20px",
                        }}
                      >
                        📚
                      </div>
                      <h5 style={{ color: "#6c757d", marginBottom: "10px" }}>
                        Select a Library First For Adding Questions
                      </h5>
                      <p style={{ color: "#6c757d", marginBottom: "0" }}>
                        Please select an existing library from the dropdown on
                        the left to start adding questions.
                      </p>
                    </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>
              <button
                type="button"
                className="btn-close"
                onClick={handleCloseViewQuestions}
                aria-label="Close"
              ></button>
            </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>
                      <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>
      )}
    </>
  );
};

export default CreateQuestionSet;
