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

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

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

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

const CreateQuestionSet = () => {
  const skillApi = useSkillApi() as any;
  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();
  // The admin `useAuth` hook performs a client-side redirect when unauthorized
  // It does not return `isAuthenticated`/`loading` shape, so call it for side-effects only
  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: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
      correctAnswer: "",
    },
  ]);

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

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

  const handleCreateLibrary = async () => {
    if (!name.trim()) {
      alert("Library name is required.");
      return;
    }
    if (!subject.trim()) {
      alert("Subject is required.");
      return;
    }
    if (!role.trim()) {
      alert("Role is required.");
      return;
    }
    if (!noOfQuestions || noOfQuestions <= 0) {
      alert("Number of questions must be greater than 0.");
      return;
    }
    const isDuplicate = libraries.some(
      (lib) => lib.name.toLowerCase() === name.trim().toLowerCase()
    );
    if (isDuplicate) {
      alert("Library name already exists");
      return;
    }
    try {
      const lib = await skillApi.createLibrary({
        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: "",
      options: [
        { key: "A", text: "", weight: 0 },
        { key: "B", text: "", weight: 0 },
      ],
      correctAnswer: "",
    };
    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 = {
          skillQuestionLibraryId: 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 skillApi.createMultipleQuestions(payloads);
        const successCount = createdQuestions.length;

        alert(`All ${successCount} questions saved successfully!`);
        setQuestions([
          {
            id: `q-${Date.now()}`,
            questionText: "",
            topic: "",
            options: [
              { key: "A", text: "", weight: 0 },
              { key: "B", text: "", weight: 0 },
            ],
            correctAnswer: "",
          },
        ]);
        // Redirect based on where we came from
        const redirectTo =
          sessionStorage.getItem("redirectTo") || "create-exam";
        sessionStorage.removeItem("redirectTo");
        router.push(`/skill-test/${redirectTo}`);
      } catch (err: any) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        console.error("Failed to save questions:", err);
        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) => {
                        const val = e.target.value;
                        if (/^[a-zA-Z\s]*$/.test(val)) setSubject(val);
                      }}
                      placeholder="Subject (e.g., Programming)"
                      className="form-control"
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Role *</label>
                    <input
                      type="text"
                      value={role}
                      onChange={(e) => {
                        const val = e.target.value;
                        if (/^[a-zA-Z\s]*$/.test(val)) setRole(val);
                      }}
                      placeholder="Role (e.g., Frontend Developer)"
                      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: Questions Editor - Only visible when library is selected */}
              {selectedLibraryId ? (
                <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 }}>
                        Create Questions ({questions.length})
                      </h5>
                      <div>
                        <button
                          className="theme-btn btn-style-one"
                          onClick={handleAddQuestion}
                          style={{ marginRight: 8 }}
                        >
                          + Add Question
                        </button>
                        <button
                          className="theme-btn btn-style-one"
                          onClick={handleSaveAllQuestions}
                        >
                          Save All Questions
                        </button>
                      </div>
                    </div>

                    <div>
                      {[...questions].reverse().map((q, idx) => (
                        <div
                          key={q.id}
                          style={{
                            marginBottom: 20,
                            padding: 12,
                            border: "1px solid #dee2e6",
                            borderRadius: 8,
                          }}
                        >
                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "center",
                            }}
                          >
                            <strong>Question {questions.length - idx}</strong>
                            <div>
                              <button
                                className="btn btn-sm btn-danger"
                                onClick={() => handleRemoveQuestion(q.id!)}
                                style={{ marginRight: 8 }}
                              >
                                Remove
                              </button>
                            </div>
                          </div>

                          <div className="mb-3">
                            <label className="form-label">Question Text</label>
                            <input
                              type="text"
                              value={q.questionText}
                              onChange={(e) =>
                                handleQuestionChange(
                                  q.id!,
                                  "questionText",
                                  e.target.value,
                                )
                              }
                              className="form-control"
                            />
                          </div>

                          <div className="mb-3">
                            <label className="form-label">Topic</label>
                            <input
                              type="text"
                              value={q.topic}
                              onChange={(e) =>
                                handleQuestionChange(
                                  q.id!,
                                  "topic",
                                  e.target.value,
                                )
                              }
                              className="form-control"
                            />
                          </div>

                          <div className="mb-3">
                            <label className="form-label">Options *</label>
                            {q.options.map((opt, oi) => (
                              <div key={oi} className="mb-2">
                                <div
                                  style={{
                                    display: "flex",
                                    gap: "10px",
                                    alignItems: "flex-end",
                                  }}
                                >
                                  <div style={{ flex: 1 }}>
                                    <label
                                      className="form-label"
                                      style={{ fontSize: "12px" }}
                                    >
                                      Option {opt.key}
                                    </label>
                                    <input
                                      type="text"
                                      value={opt.text}
                                      onChange={(e) =>
                                        handleOptionChange(
                                          q.id!,
                                          oi,
                                          "text",
                                          e.target.value,
                                        )
                                      }
                                      className="form-control"
                                      placeholder={`Option ${opt.key}`}
                                    />
                                  </div>
                                  <div
                                    style={{
                                      display: "flex",
                                      gap: "5px",
                                      alignItems: "flex-end",
                                    }}
                                  >
                                    {q.options.length > 1 && (
                                      <button
                                        type="button"
                                        className="btn btn-sm btn-danger"
                                        onClick={() =>
                                          handleRemoveOption(q.id!, oi)
                                        }
                                        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(q.id!)}
                            >
                              + Add Option
                            </button>
                          </div>

                          <div className="mb-3">
                            <label className="form-label">
                              Correct Answer *
                            </label>
                            <input
                              type="text"
                              value={q.correctAnswer}
                              onChange={(e) =>
                                handleQuestionChange(
                                  q.id!,
                                  "correctAnswer",
                                  e.target.value,
                                )
                              }
                              placeholder="Enter the key of correct answer (e.g., A)"
                              className="form-control"
                            />
                          </div>
                        </div>
                      ))}
                    </div>
                  </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>
    </>
  );
};

export default CreateQuestionSet;
