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

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

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

const ShowExams = () => {
  const psychApi = usePsychometricApi() 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();
  // admin useAuth performs redirect as a side-effect and does not return auth fields
  const auth = useAuth() as any;

  useEffect(() => {
    // Load libraries and exams on mount. `useAuth` will redirect if unauthenticated.
    const init = async () => {
      const libs = await fetchLibraries();
      await fetchExams(libs);
    };

    init();
  }, []);

  const fetchLibraries = async () => {
    try {
      const libs = await psychApi.getQuestionLibraries();
      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 psychApi.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.psychometricExams)) {
          examsArray = data.psychometricExams;
        }
      }

      // Attach library object to each exam if possible
      const lookup = libs && libs.length ? libs : libraries;
      const mapped = (examsArray || []).map((ex: any) => {
        // Possible library identifiers from API responses
        const libId =
          ex.psychometricQuestionLibrary?.id ||
          ex.psychometricQuestionLibraryId ||
          ex.psychometric_question_library_id ||
          (ex.psychometricQuestionLibrary &&
            (ex.psychometricQuestionLibrary as any).id);

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

      setExams(mapped);
    } catch (err: any) {
      const errorMsg =
        err?.response?.data?.message || err?.message || "Failed to load exams";
      console.error("Failed to fetch psychometric 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);
    // Normalize possible backend values for inactive: false, 0, "0"
    const raw = (exam as any).isActive;
    const isActiveNormalized = !(raw === false || raw === 0 || raw === "0");
    setEditIsActive(isActiveNormalized);

    // Find the library ID from the exam data
    if (exam.psychometricQuestionLibrary) {
      setEditSelectedLibraryId(exam.psychometricQuestionLibrary.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 = {
        psychometricQuestionLibraryId: editSelectedLibraryId,
        title: editTitle.trim(),
        description: editDescription || "",
        duration: editDuration || 30,
        isActive: editIsActive,
      };

      await psychApi.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 usePsychometricApi
      if (psychApi.deleteExam) {
        await psychApi.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("/psychometric-test/create-exam");
  };

  if (loading) {
    return (
      <div className="page-wrapper dashboard">
        <section className="user-dashboard">
          <div className="dashboard-outer">
            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div className="tabs-box">
                    <div className="widget-content text-center py-5">
                      <div className="spinner mb-4"></div>
                      <p>Loading exams...</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </div>
    );
  }

  return (
    <>
      <div className="page-wrapper dashboard">
        <section className="user-dashboard">
          <div className="dashboard-outer">
            <div className="row">
              <div className="col-lg-12">
                <div className="ls-widget">
                  <div className="tabs-box">
                    <div className="widget-title">
                      <h4>Psychometric 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="widget-content">
                      <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.psychometricQuestionLibrary?.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>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </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.psychometricQuestionLibrary?.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>
              </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-secondary"
                  onClick={handleCloseEditModal}
                  disabled={isSaving}
                >
                  Cancel
                </button>
                <button
                  type="button"
                  className="btn btn-primary"
                  onClick={handleSaveExam}
                  disabled={isSaving}
                >
                  {isSaving ? "Saving..." : "Save Changes"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  );
};

export default ShowExams;
