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

type Exam = {
  id: number;
  title: string;
  description?: string;
  duration?: number;
  passingScore?: number;
  isActive?: boolean;
  skillQuestionLibrary?: {
    id: number;
    title: string;
  };
  created_at?: string;
  updated_at?: string;
};

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

const ShowExams = () => {
  const skillApi = useSkillApi() as any;
  const [exams, setExams] = useState<Exam[]>([]);
  const [libraries, setLibraries] = useState<Library[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [deleteConfirmId, setDeleteConfirmId] = useState<number | null>(null);
  const [selectedExam, setSelectedExam] = useState<Exam | null>(null);
  const [showModal, setShowModal] = useState(false);
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);

  // Edit modal states
  const [showEditModal, setShowEditModal] = useState(false);
  const [editingExam, setEditingExam] = useState<Exam | null>(null);
  const [editTitle, setEditTitle] = useState("");
  const [editDescription, setEditDescription] = useState("");
  const [editDuration, setEditDuration] = useState(30);
  const [editSelectedLibraryId, setEditSelectedLibraryId] = useState<
    number | null
  >(null);
  const [editIsActive, setEditIsActive] = useState(true);
  const [isSaving, setIsSaving] = 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;

  useEffect(() => {
    // Init data regardless; the `useAuth` hook will redirect to signin if no token
    const init = async () => {
      const libs = await fetchLibraries();
      await fetchExams(libs);
    };

    init();
    // Intentionally empty deps: we don't depend on auth return values here
  }, []);

  const fetchLibraries = async () => {
    try {
      const libs = await skillApi.getTestLibraries();
      const normalized = (libs || []).map((l: any) => ({
        id: l.id,
        name: l.name || l.title || "Untitled",
        title: l.title,
        description: l.description,
      }));
      setLibraries(normalized);
      return normalized;
    } catch (err) {
      console.error("Failed to fetch libraries", err);
      return [] as Library[];
    }
  };

  const fetchExams = async (libs?: Library[]) => {
    try {
      setLoading(true);
      setError(null);
      const data = await skillApi.getExams();

      // Handle various response formats
      let examsArray: Exam[] = [];
      if (Array.isArray(data)) {
        examsArray = data;
      } else if (data && typeof data === "object") {
        // Try to extract from nested structures
        if (Array.isArray(data.data)) {
          examsArray = data.data;
        } else if (Array.isArray(data.exams)) {
          examsArray = data.exams;
        } else if (Array.isArray(data.skillExams)) {
          examsArray = data.skillExams;
        }
      }

      // Attach library object to each exam if possible
      const lookup = libs && libs.length ? libs : libraries;
      const mapped = (examsArray || []).map((ex: any) => {
        const libId =
          ex.skillQuestionLibrary?.id ||
          ex.skillQuestionLibraryId ||
          ex.skill_question_library_id ||
          (ex.skillQuestionLibrary && (ex.skillQuestionLibrary as any).id);

        const lib = lookup ? lookup.find((l) => l.id === libId) : undefined;
        return {
          ...ex,
          skillQuestionLibrary: lib
            ? { id: lib.id, title: lib.title || lib.name }
            : ex.skillQuestionLibrary || null,
        };
      });

      setExams(mapped);
    } catch (err: any) {
      const errorMsg =
        err?.response?.data?.message || err?.message || "Failed to load exams";
      console.error("Failed to fetch skill test exams:", err);
      console.error("Error details:", {
        status: err?.response?.status,
        data: err?.response?.data,
        message: err?.message,
      });
      setError(errorMsg);
    } finally {
      setLoading(false);
    }
  };

  const handleViewDetails = (exam: Exam) => {
    setSelectedExam(exam);
    setShowModal(true);
  };

  const handleEdit = (exam: Exam) => {
    setEditingExam(exam);
    setEditTitle(exam.title);
    setEditDescription(exam.description || "");
    setEditDuration(exam.duration || 30);
    setEditIsActive(exam.isActive !== false);

    // Find the library ID from the exam data
    if (exam.skillQuestionLibrary) {
      setEditSelectedLibraryId(exam.skillQuestionLibrary.id);
    }

    setShowEditModal(true);
  };

  const handleSaveExam = async () => {
    if (!editingExam || !editTitle.trim()) {
      alert("Please enter exam title");
      return;
    }

    if (!editSelectedLibraryId) {
      alert("Please select a question library");
      return;
    }

    try {
      setIsSaving(true);
      const payload = {
        skillQuestionLibraryId: editSelectedLibraryId,
        title: editTitle.trim(),
        description: editDescription || "",
        duration: editDuration || 30,
        isActive: editIsActive,
      };

      await skillApi.updateExam(editingExam.id, payload as any);
      alert("Exam updated successfully!");
      setShowEditModal(false);
      fetchExams();
    } catch (err: any) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      console.error("Update exam failed:", errorMessage, err);
      alert("Failed to update exam: " + errorMessage);
    } finally {
      setIsSaving(false);
    }
  };

  const handleCloseEditModal = () => {
    setShowEditModal(false);
    setEditingExam(null);
    setEditTitle("");
    setEditDescription("");
    setEditDuration(30);
    setEditSelectedLibraryId(null);
    setEditIsActive(true);
  };

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

    try {
      setLoading(true);
      // Note: This assumes a deleteExam method exists in the API hook
      // If not available, you may need to add it to useSkillApi
      if (skillApi.deleteExam) {
        await skillApi.deleteExam(examId);
        alert("Exam deleted successfully!");
        fetchExams();
      } else {
        alert("Delete functionality not available yet.");
      }
    } catch (err: any) {
      const errorMsg = err?.response?.data?.message || "Failed to delete exam";
      console.error("Delete failed:", err);
      alert(errorMsg);
    } finally {
      setLoading(false);
      setDeleteConfirmId(null);
    }
  };

  const handleCreateNew = () => {
    router.push("/skill-test/create-exam");
  };

  if (loading) {
    return (
      <div
        style={{
          textAlign: "center",
          padding: "40px 20px",
          minHeight: "100vh",
        }}
      >
        <div style={{ marginBottom: "20px" }}>Loading exams...</div>
      </div>
    );
  }

  return (
    <>
      <div style={{ padding: "20px" }}>
        <div
          style={{
            marginBottom: "20px",
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
          }}
        >
          <h4 style={{ marginBottom: "0px", color: "#212245" }}>
            Skill Test Exams
          </h4>
          <button className="theme-btn btn-style-one" onClick={handleCreateNew}>
            + Create New Exam
          </button>
        </div>

        {error && <div className="alert alert-danger mt-3">{error}</div>}

        <div className="row">
          {exams.map((exam) => (
            <div key={exam.id} className="col-lg-4 col-md-6 mb-4">
              <div
                className="job-card border rounded p-4 h-100"
                style={{
                  boxShadow: "0 2px 8px rgba(0,0,0,0.1)",
                  transition: "transform 0.3s, box-shadow 0.3s",
                }}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = "translateY(-5px)";
                  e.currentTarget.style.boxShadow =
                    "0 4px 12px rgba(0,0,0,0.15)";
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = "translateY(0)";
                  e.currentTarget.style.boxShadow = "0 2px 8px rgba(0,0,0,0.1)";
                }}
              >
                <div className="d-flex justify-content-between align-items-start mb-3">
                  <div>
                    <h5 className="mb-1 fw-bold text-dark">{exam.title}</h5>
                    <p className="text-muted small mb-0">ID: {exam.id}</p>
                  </div>
                  <span
                    className={`badge ${exam.isActive ? "bg-success" : "bg-secondary"}`}
                  >
                    {exam.isActive ? "Active" : "Inactive"}
                  </span>
                </div>

                <div className="exam-details mb-3">
                  <div className="detail-row mb-2">
                    <strong className="text-muted small">Duration:</strong>
                    <p className="mb-0">
                      {exam.duration ? `${exam.duration} min` : "-"}
                    </p>
                  </div>
                  <div className="detail-row mb-2">
                    <strong className="text-muted small">Library:</strong>
                    <p className="mb-0">
                      {exam.skillQuestionLibrary?.title || "-"}
                    </p>
                  </div>
                  {exam.description && (
                    <div className="detail-row mb-2">
                      <strong className="text-muted small">Description:</strong>
                      <p className="mb-0 small text-muted">
                        {exam.description.substring(0, 80)}
                        {exam.description.length > 80 ? "..." : ""}
                      </p>
                    </div>
                  )}
                </div>

                <div className="d-flex gap-2 mt-4">
                  <button
                    className="theme-btn btn-style-one flex-grow-1"
                    onClick={() => handleViewDetails(exam)}
                    style={{
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                  >
                    View
                  </button>
                  <button
                    className="btn btn-sm btn-warning flex-grow-1"
                    onClick={() => handleEdit(exam)}
                    style={{
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                  >
                    Edit
                  </button>
                  <button
                    className="btn btn-sm btn-danger flex-grow-1"
                    onClick={() => handleDelete(exam.id)}
                    style={{
                      padding: "10px 20px",
                      fontSize: "14px",
                    }}
                  >
                    Delete
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Details Modal */}
      {showModal && selectedExam && (
        <div
          className="modal d-block"
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-lg">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Exam Details</h5>
                <button
                  type="button"
                  className="btn-close"
                  onClick={() => setShowModal(false)}
                ></button>
              </div>
              <div className="modal-body">
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Title:</strong>
                    <p>{selectedExam.title}</p>
                  </div>
                  <div className="col-md-6">
                    <strong>ID:</strong>
                    <p>{selectedExam.id}</p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-12">
                    <strong>Description:</strong>
                    <p>{selectedExam.description || "-"}</p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Duration:</strong>
                    <p>
                      {selectedExam.duration
                        ? `${selectedExam.duration} minutes`
                        : "-"}
                    </p>
                  </div>
                </div>
                <div className="row mb-3">
                  <div className="col-md-6">
                    <strong>Question Library:</strong>
                    <p>{selectedExam.skillQuestionLibrary?.title || "-"}</p>
                  </div>
                  <div className="col-md-6">
                    <strong>Status:</strong>
                    <p>
                      {selectedExam.isActive ? (
                        <span className="badge bg-success">Active</span>
                      ) : (
                        <span className="badge bg-secondary">Inactive</span>
                      )}
                    </p>
                  </div>
                </div>
                {/* Created/Updated intentionally removed from details view */}
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-secondary"
                  onClick={() => setShowModal(false)}
                >
                  Close
                </button>
                <button
                  type="button"
                  className="btn btn-warning"
                  onClick={() => {
                    setShowModal(false);
                    handleEdit(selectedExam);
                  }}
                >
                  Edit
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Edit Exam Modal */}
      {showEditModal && editingExam && (
        <div
          className="modal d-block"
          style={{ backgroundColor: "rgba(0,0,0,0.5)" }}
        >
          <div className="modal-dialog modal-lg">
            <div className="modal-content">
              <div className="modal-header">
                <h5 className="modal-title">Edit Exam</h5>
                <button
                  type="button"
                  className="btn-close"
                  onClick={handleCloseEditModal}
                  disabled={isSaving}
                ></button>
              </div>
              <div className="modal-body">
                <form
                  onSubmit={(e) => {
                    e.preventDefault();
                    handleSaveExam();
                  }}
                >
                  <div className="mb-3">
                    <label className="form-label">Exam Title</label>
                    <input
                      type="text"
                      className="form-control"
                      value={editTitle}
                      onChange={(e) => setEditTitle(e.target.value)}
                      disabled={isSaving}
                    />
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Description</label>
                    <textarea
                      className="form-control"
                      rows={3}
                      value={editDescription}
                      onChange={(e) => setEditDescription(e.target.value)}
                      disabled={isSaving}
                    />
                  </div>

                  <div className="row mb-3">
                    <div className="col-md-6">
                      <label className="form-label">Duration (minutes)</label>
                      <input
                        type="number"
                        className="form-control"
                        value={editDuration}
                        onChange={(e) =>
                          setEditDuration(parseInt(e.target.value) || 30)
                        }
                        disabled={isSaving}
                      />
                    </div>
                  </div>

                  <div className="mb-3">
                    <label className="form-label">Question Library</label>
                    <select
                      className="form-select"
                      value={editSelectedLibraryId || ""}
                      onChange={(e) =>
                        setEditSelectedLibraryId(
                          parseInt(e.target.value) || null,
                        )
                      }
                      disabled={isSaving}
                    >
                      <option value="">Select a library</option>
                      {libraries.map((lib) => (
                        <option key={lib.id} value={lib.id}>
                          {lib.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="mb-3 form-check">
                    <input
                      type="checkbox"
                      className="form-check-input"
                      id="editIsActive"
                      checked={editIsActive}
                      onChange={(e) => setEditIsActive(e.target.checked)}
                      disabled={isSaving}
                    />
                    <label className="form-check-label" htmlFor="editIsActive">
                      Active
                    </label>
                  </div>
                </form>
              </div>
              <div className="modal-footer">
                <button
                  type="button"
                  className="btn btn-danger"
                  onClick={handleCloseEditModal}
                  disabled={isSaving}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="theme-btn btn-style-one"
                  style={{
                    display: "inline-block",
                    padding: "10px 20px",
                    fontSize: "14px",
                    borderRadius: "4px",
                  }}
                  onClick={handleSaveExam}
                  disabled={isSaving}
                >
                  {isSaving ? "Saving..." : "Save Changes"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ShowExams;
