"use client";

import { useEffect, useState } from "react";
import { useSession, signOut } from "next-auth/react";
import { useRouter } from "next/navigation";
import { QuizTemplate, QuizTheme, QuizUser, QuizAttempt } from "@/types/quiz";
import Logo from "@/components/Logo";

export default function AdminPage() {
  const { data: session } = useSession();
  const router = useRouter();
  const [templates, setTemplates] = useState<QuizTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [showNewForm, setShowNewForm] = useState(false);
  const [newTitle, setNewTitle] = useState("");
  const [newDescription, setNewDescription] = useState("");
  const [quizTheme, setQuizTheme] = useState<QuizTheme>("classmaker");
  const [themeSaving, setThemeSaving] = useState(false);
  const [quizUsers, setQuizUsers] = useState<QuizUser[]>([]);
  const [quizAttempts, setQuizAttempts] = useState<QuizAttempt[]>([]);
  const [expandedUser, setExpandedUser] = useState<string | null>(null);
  const [expandedAttempt, setExpandedAttempt] = useState<string | null>(null);
  const [expandedAdvancedAttempt, setExpandedAdvancedAttempt] = useState<string | null>(null);
  const [userPathTemplateIds, setUserPathTemplateIds] = useState<string[] | null>(null);

  useEffect(() => {
    fetch("/api/templates")
      .then((r) => r.json())
      .then((data) => { setTemplates(data); setLoading(false); });
    fetch("/api/settings")
      .then((r) => r.json())
      .then((s) => {
        setQuizTheme(s.quizTheme || "classmaker");
        setUserPathTemplateIds(s.userPathTemplateIds || null);
      });
    fetch("/api/admin/quiz-users")
      .then((r) => r.json())
      .then((data) => {
        setQuizUsers(data.users || []);
        setQuizAttempts(data.attempts || []);
      })
      .catch(() => {});
  }, []);

  async function fetchTemplates() {
    const res = await fetch("/api/templates");
    const data = await res.json();
    setTemplates(data);
    setLoading(false);
  }

  function getAttemptsForUser(userId: string) {
    return quizAttempts
      .filter((a) => a.userId === userId)
      .sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());
  }

  async function handleThemeChange(theme: QuizTheme) {
    setQuizTheme(theme);
    setThemeSaving(true);
    await fetch("/api/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ quizTheme: theme }),
    });
    setThemeSaving(false);
  }

  async function handleToggleUserPath(templateId: string) {
    const current = userPathTemplateIds || [];
    const updated = current.includes(templateId)
      ? current.filter((id) => id !== templateId)
      : [...current, templateId];
    setUserPathTemplateIds(updated.length > 0 ? updated : null);
    await fetch("/api/settings", {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ userPathTemplateIds: updated }),
    });
  }

  async function handleCreateTemplate(e: React.FormEvent) {
    e.preventDefault();
    const slug = newTitle.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/(^-|-$)/g, "");
    const id = slug || `template-${Date.now()}`;
    const template: QuizTemplate = {
      id,
      title: newTitle,
      description: newDescription,
      questions: [],
    };

    await fetch("/api/templates", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(template),
    });

    setNewTitle("");
    setNewDescription("");
    setShowNewForm(false);
    router.push(`/admin/edit/${id}`);
  }

  async function handleDuplicate(template: QuizTemplate) {
    const newId = `${template.id}-copy-${Date.now()}`;
    const copy: QuizTemplate = {
      ...template,
      id: newId,
      title: `Copy of ${template.title}`,
    };
    await fetch("/api/templates", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(copy),
    });
    fetchTemplates();
  }

  async function handleDelete(id: string) {
    if (!confirm("Are you sure you want to delete this template?")) return;
    await fetch(`/api/templates/${id}`, { method: "DELETE" });
    fetchTemplates();
  }

  function formatDuration(startedAt: string, completedAt: string | null) {
    if (!completedAt) return null;
    const ms = new Date(completedAt).getTime() - new Date(startedAt).getTime();
    const totalSeconds = Math.floor(ms / 1000);
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    if (hours > 0) return `${hours}h ${minutes}m ${seconds}s`;
    if (minutes > 0) return `${minutes}m ${seconds}s`;
    return `${seconds}s`;
  }

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-900 flex items-center justify-center">
        <p className="text-gray-400">Loading...</p>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-900 text-white">
      <header className="border-b border-gray-700 px-6 py-4 flex items-center justify-between">
        <Logo height={32} />
        <div className="flex items-center gap-4">
          <span className="text-gray-400 text-sm">
            Signed in as {session?.user?.name}
          </span>
          <button
            onClick={() => signOut({ callbackUrl: "/admin/login" })}
            className="text-sm text-gray-400 hover:text-white"
          >
            Sign out
          </button>
        </div>
      </header>

      <main className="max-w-4xl mx-auto p-6">
        <div className="flex items-center justify-between mb-6">
          <h2 className="text-lg font-semibold">Quiz Templates</h2>
          <button
            onClick={() => setShowNewForm(true)}
            className="px-4 py-2 bg-blue-600 rounded-lg hover:bg-blue-700 text-sm font-medium"
          >
            + New Template
          </button>
        </div>

        {showNewForm && (
          <form
            onSubmit={handleCreateTemplate}
            className="mb-6 p-4 bg-gray-800 rounded-lg space-y-3"
          >
            <input
              type="text"
              placeholder="Template title"
              value={newTitle}
              onChange={(e) => setNewTitle(e.target.value)}
              className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white"
              required
            />
            <input
              type="text"
              placeholder="Description"
              value={newDescription}
              onChange={(e) => setNewDescription(e.target.value)}
              className="w-full px-3 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white"
              required
            />
            <div className="flex gap-2">
              <button
                type="submit"
                className="px-4 py-2 bg-green-600 rounded-lg hover:bg-green-700 text-sm"
              >
                Create
              </button>
              <button
                type="button"
                onClick={() => setShowNewForm(false)}
                className="px-4 py-2 bg-gray-600 rounded-lg hover:bg-gray-500 text-sm"
              >
                Cancel
              </button>
            </div>
          </form>
        )}

        <div className="space-y-3">
          {templates.map((t) => (
            <div
              key={t.id}
              className="p-4 bg-gray-800 rounded-lg flex items-center justify-between"
            >
              <div>
                <h3 className="font-medium">{t.title}</h3>
                <p className="text-sm text-gray-400">
                  {t.description} &middot; {t.questions.length} questions
                </p>
              </div>
              <div className="flex items-center gap-3">
                <button
                  onClick={() => handleToggleUserPath(t.id)}
                  className="flex items-center gap-1.5 group"
                  title={
                    (!userPathTemplateIds || userPathTemplateIds.includes(t.id))
                      ? "Enabled for /user quizzes — click to disable"
                      : "Disabled for /user quizzes — click to enable"
                  }
                >
                  <div
                    className={`w-8 h-[18px] rounded-full transition-colors relative ${
                      (!userPathTemplateIds || userPathTemplateIds.includes(t.id))
                        ? "bg-green-500"
                        : "bg-gray-600"
                    }`}
                  >
                    <div
                      className={`w-3.5 h-3.5 rounded-full bg-white absolute top-[2px] transition-all ${
                        (!userPathTemplateIds || userPathTemplateIds.includes(t.id))
                          ? "left-[17px]"
                          : "left-[2px]"
                      }`}
                    />
                  </div>
                  <span className="text-xs text-gray-400 group-hover:text-gray-300">/user</span>
                </button>
                <button
                  onClick={() => router.push(`/admin/edit/${t.id}`)}
                  className="px-3 py-1.5 bg-blue-600 rounded hover:bg-blue-700 text-sm"
                >
                  Edit
                </button>
                <button
                  onClick={() => handleDuplicate(t)}
                  className="px-3 py-1.5 bg-gray-600 rounded hover:bg-gray-500 text-sm"
                >
                  Duplicate
                </button>
                <button
                  onClick={() => handleDelete(t.id)}
                  className="px-3 py-1.5 bg-red-600 rounded hover:bg-red-700 text-sm"
                >
                  Delete
                </button>
              </div>
            </div>
          ))}

          {templates.length === 0 && (
            <p className="text-gray-500 text-center py-8">
              No templates yet. Create one to get started.
            </p>
          )}
        </div>

        {/* Theme Switcher */}
        <div className="mt-10 pt-6 border-t border-gray-700">
          <div className="flex items-center justify-between mb-4">
            <h2 className="text-lg font-semibold">Quiz Theme</h2>
            {themeSaving && (
              <span className="text-xs text-gray-400">Saving...</span>
            )}
          </div>
          <div className="grid grid-cols-2 gap-4">
            <button
              onClick={() => handleThemeChange("classmaker")}
              className={`p-4 rounded-lg border-2 text-left transition-colors ${
                quizTheme === "classmaker"
                  ? "border-blue-500 bg-gray-800"
                  : "border-gray-700 bg-gray-800 hover:border-gray-600"
              }`}
            >
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${
                  quizTheme === "classmaker" ? "border-blue-500 bg-blue-500" : "border-gray-500"
                }`}>
                  {quizTheme === "classmaker" && <div className="w-1.5 h-1.5 rounded-full bg-white" />}
                </div>
                <span className="font-medium">ClassMarker</span>
                <span className="text-xs bg-blue-600/30 text-blue-400 px-1.5 py-0.5 rounded">Default</span>
              </div>
              <p className="text-sm text-gray-400">
                Classic ClassMarker design with red navigation buttons, lettered options (A. B. C.), and light blue question cards.
              </p>
            </button>

            <button
              onClick={() => handleThemeChange("modern")}
              className={`p-4 rounded-lg border-2 text-left transition-colors ${
                quizTheme === "modern"
                  ? "border-blue-500 bg-gray-800"
                  : "border-gray-700 bg-gray-800 hover:border-gray-600"
              }`}
            >
              <div className="flex items-center gap-2 mb-2">
                <div className={`w-4 h-4 rounded-full border-2 flex items-center justify-center ${
                  quizTheme === "modern" ? "border-blue-500 bg-blue-500" : "border-gray-500"
                }`}>
                  {quizTheme === "modern" && <div className="w-1.5 h-1.5 rounded-full bg-white" />}
                </div>
                <span className="font-medium">Modern</span>
              </div>
              <p className="text-sm text-gray-400">
                Clean modern design with blue header bar, question navigation dots, and progress tracking.
              </p>
            </button>
          </div>
        </div>

        {/* Quiz Users & Progress */}
        <div className="mt-10 pt-6 border-t border-gray-700">
          <h2 className="text-lg font-semibold mb-4">Quiz Users & Progress</h2>

          {quizUsers.length === 0 ? (
            <p className="text-gray-500 text-center py-8">
              No quiz users yet. Users will appear here after they start a quiz via /user.
            </p>
          ) : (
            <div className="space-y-3">
              {quizUsers.map((user) => {
                const userAttempts = getAttemptsForUser(user.id);
                const completedCount = userAttempts.filter((a) => a.status === "completed").length;
                const isExpanded = expandedUser === user.id;

                return (
                  <div key={user.id} className="bg-gray-800 rounded-lg overflow-hidden">
                    <button
                      onClick={() => setExpandedUser(isExpanded ? null : user.id)}
                      className="w-full p-4 flex items-center justify-between text-left hover:bg-gray-750"
                    >
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-medium">{user.name}</span>
                          <span className="text-sm text-gray-400">{user.email}</span>
                        </div>
                        <p className="text-sm text-gray-400 mt-0.5">
                          {userAttempts.length} attempt{userAttempts.length !== 1 ? "s" : ""}
                          {completedCount > 0 && ` (${completedCount} completed)`}
                          {" "}&middot; Last seen {new Date(user.lastSeenAt).toLocaleDateString()}
                        </p>
                      </div>
                      <span className="text-gray-400 text-sm">{isExpanded ? "▲" : "▼"}</span>
                    </button>

                    {isExpanded && (
                      <div className="px-4 pb-4 space-y-2">
                        {userAttempts.length === 0 ? (
                          <p className="text-sm text-gray-500 py-2">No attempts yet.</p>
                        ) : (
                          userAttempts.map((att) => {
                            const isAttemptExpanded = expandedAttempt === att.id;
                            return (
                              <div key={att.id} className="bg-gray-700 rounded-lg overflow-hidden">
                                <button
                                  onClick={() => setExpandedAttempt(isAttemptExpanded ? null : att.id)}
                                  className="w-full px-4 py-3 flex items-center justify-between text-left hover:bg-gray-650"
                                >
                                  <div className="flex items-center gap-3">
                                    <span
                                      className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                                        att.status === "completed"
                                          ? "bg-green-900/50 text-green-400"
                                          : "bg-yellow-900/50 text-yellow-400"
                                      }`}
                                    >
                                      {att.status === "completed" ? "Completed" : "In Progress"}
                                    </span>
                                    <span className="text-sm text-gray-300">
                                      {att.quizMode === "learning" ? "Learning" : "Testing"}
                                    </span>
                                    <span className="text-sm text-gray-400">
                                      {new Date(att.startedAt).toLocaleString()}
                                      {att.status === "completed" && att.completedAt
                                        ? ` · Duration: ${formatDuration(att.startedAt, att.completedAt)}`
                                        : ""}
                                    </span>
                                  </div>
                                  <div className="flex items-center gap-3">
                                    {att.status === "completed" ? (
                                      <span className={`text-sm font-medium ${
                                        (att.score || 0) >= 70 ? "text-green-400" :
                                        (att.score || 0) >= 50 ? "text-yellow-400" : "text-red-400"
                                      }`}>
                                        {att.score}% ({att.correctCount}/{att.totalQuestions})
                                      </span>
                                    ) : (
                                      <span className="text-sm text-gray-400">
                                        {att.answeredCount}/{att.totalQuestions} answered
                                      </span>
                                    )}
                                    <span className="text-gray-500 text-xs">{isAttemptExpanded ? "▲" : "▼"}</span>
                                  </div>
                                </button>

                                {isAttemptExpanded && (
                                  <div className="px-4 pb-3 space-y-2">
                                    {att.questions.map((q, qi) => {
                                      const answer = att.answers.find((a) => a.questionId === q.id);
                                      const selected = answer?.selectedAnswers || [];
                                      const hasAnswer = selected.length > 0;

                                      let isCorrect = false;
                                      if (hasAnswer) {
                                        if (q.type === "multiple-dropdown") {
                                          isCorrect = (q.subQuestions || []).every((sq) => {
                                            const entry = selected.find((a) => a.startsWith(sq.id + ":"));
                                            return entry ? entry.split(":")[1] === sq.correctOptionId : false;
                                          });
                                        } else {
                                          isCorrect =
                                            selected.length === q.correctAnswers.length &&
                                            selected.every((s) => q.correctAnswers.includes(s));
                                        }
                                      }

                                      return (
                                        <div
                                          key={q.id}
                                          className={`text-sm px-3 py-2 rounded ${
                                            !hasAnswer
                                              ? "bg-gray-600/50 text-gray-400"
                                              : isCorrect
                                              ? "bg-green-900/30 text-green-300"
                                              : "bg-red-900/30 text-red-300"
                                          }`}
                                        >
                                          <div className="flex items-start gap-2">
                                            <span className="text-gray-500 shrink-0">Q{qi + 1}.</span>
                                            <div className="flex-1">
                                              <p>{q.text}</p>
                                              {hasAnswer && q.type === "multiple-dropdown" ? (
                                                <div className="mt-1 space-y-0.5">
                                                  {(q.subQuestions || []).map((sq) => {
                                                    const entry = selected.find((a) => a.startsWith(sq.id + ":"));
                                                    const selectedOptId = entry ? entry.split(":")[1] : "";
                                                    const selectedOpt = (sq.options || []).find((o) => o.id === selectedOptId);
                                                    const correctOpt = (sq.options || []).find((o) => o.id === sq.correctOptionId);
                                                    const sqCorrect = selectedOptId === sq.correctOptionId;
                                                    return (
                                                      <p key={sq.id} className="text-xs">
                                                        <span className="text-gray-400">{sq.text}:</span>{" "}
                                                        <span className={sqCorrect ? "text-green-400" : "text-red-400"}>
                                                          {selectedOpt?.label || "(none)"}
                                                        </span>
                                                        {!sqCorrect && correctOpt && (
                                                          <span className="text-green-400 ml-1">(correct: {correctOpt.label})</span>
                                                        )}
                                                      </p>
                                                    );
                                                  })}
                                                </div>
                                              ) : hasAnswer ? (
                                                <p className="text-xs mt-1">
                                                  <span className="text-gray-400">Answer:</span>{" "}
                                                  {selected.map((s) => {
                                                    const opt = q.options.find((o) => o.id === s);
                                                    return opt?.label || s;
                                                  }).join(", ")}
                                                  {!isCorrect && (
                                                    <span className="text-green-400 ml-1">
                                                      (correct: {q.correctAnswers.map((c) => {
                                                        const opt = q.options.find((o) => o.id === c);
                                                        return opt?.label || c;
                                                      }).join(", ")})
                                                    </span>
                                                  )}
                                                </p>
                                              ) : (
                                                <p className="text-xs mt-1 text-gray-500">Not answered</p>
                                              )}
                                            </div>
                                          </div>
                                        </div>
                                      );
                                    })}
                                  </div>
                                )}
                              </div>
                            );
                          })
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>

        {/* Advanced Quiz Attempts */}
        <div className="mt-10 pt-6 border-t border-gray-700">
          <h2 className="text-lg font-semibold mb-4">Advanced Quiz Attempts</h2>

          {(() => {
            const advancedAttempts = quizAttempts
              .filter((a) => a.source === "advanced")
              .sort((a, b) => new Date(b.startedAt).getTime() - new Date(a.startedAt).getTime());

            if (advancedAttempts.length === 0) {
              return (
                <p className="text-gray-500 text-center py-8">
                  No advanced quiz attempts yet. Attempts will appear here after users take quizzes via /advanced.
                </p>
              );
            }

            return (
              <div className="space-y-2">
                {advancedAttempts.map((att) => {
                  const isAttemptExpanded = expandedAdvancedAttempt === att.id;
                  return (
                    <div key={att.id} className="bg-gray-800 rounded-lg overflow-hidden">
                      <button
                        onClick={() => setExpandedAdvancedAttempt(isAttemptExpanded ? null : att.id)}
                        className="w-full px-4 py-3 flex items-center justify-between text-left hover:bg-gray-750"
                      >
                        <div className="flex items-center gap-3">
                          <span className="text-sm font-medium text-blue-400">
                            {att.userName || att.userId}
                          </span>
                          <span
                            className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                              att.status === "completed"
                                ? "bg-green-900/50 text-green-400"
                                : "bg-yellow-900/50 text-yellow-400"
                            }`}
                          >
                            {att.status === "completed" ? "Completed" : "In Progress"}
                          </span>
                          <span className="text-sm text-gray-300">
                            {att.quizMode === "learning" ? "Learning" : "Testing"}
                          </span>
                          <span className="text-sm text-gray-400">
                            {new Date(att.startedAt).toLocaleString()}
                            {att.status === "completed" && att.completedAt
                              ? ` · Duration: ${formatDuration(att.startedAt, att.completedAt)}`
                              : ""}
                          </span>
                        </div>
                        <div className="flex items-center gap-3">
                          {att.status === "completed" ? (
                            <span className={`text-sm font-medium ${
                              (att.score || 0) >= 70 ? "text-green-400" :
                              (att.score || 0) >= 50 ? "text-yellow-400" : "text-red-400"
                            }`}>
                              {att.score}% ({att.correctCount}/{att.totalQuestions})
                            </span>
                          ) : (
                            <span className="text-sm text-gray-400">
                              {att.answeredCount}/{att.totalQuestions} answered
                            </span>
                          )}
                          <span className="text-gray-500 text-xs">{isAttemptExpanded ? "▲" : "▼"}</span>
                        </div>
                      </button>

                      {isAttemptExpanded && (
                        <div className="px-4 pb-3 space-y-2">
                          {att.questions.map((q, qi) => {
                            const answer = att.answers.find((a) => a.questionId === q.id);
                            const selected = answer?.selectedAnswers || [];
                            const hasAnswer = selected.length > 0;

                            let isCorrect = false;
                            if (hasAnswer) {
                              if (q.type === "multiple-dropdown") {
                                isCorrect = (q.subQuestions || []).every((sq) => {
                                  const entry = selected.find((a) => a.startsWith(sq.id + ":"));
                                  return entry ? entry.split(":")[1] === sq.correctOptionId : false;
                                });
                              } else {
                                isCorrect =
                                  selected.length === q.correctAnswers.length &&
                                  selected.every((s) => q.correctAnswers.includes(s));
                              }
                            }

                            return (
                              <div
                                key={q.id}
                                className={`text-sm px-3 py-2 rounded ${
                                  !hasAnswer
                                    ? "bg-gray-600/50 text-gray-400"
                                    : isCorrect
                                    ? "bg-green-900/30 text-green-300"
                                    : "bg-red-900/30 text-red-300"
                                }`}
                              >
                                <div className="flex items-start gap-2">
                                  <span className="text-gray-500 shrink-0">Q{qi + 1}.</span>
                                  <div className="flex-1">
                                    <p>{q.text}</p>
                                    {hasAnswer && q.type === "multiple-dropdown" ? (
                                      <div className="mt-1 space-y-0.5">
                                        {(q.subQuestions || []).map((sq) => {
                                          const entry = selected.find((a) => a.startsWith(sq.id + ":"));
                                          const selectedOptId = entry ? entry.split(":")[1] : "";
                                          const selectedOpt = (sq.options || []).find((o) => o.id === selectedOptId);
                                          const correctOpt = (sq.options || []).find((o) => o.id === sq.correctOptionId);
                                          const sqCorrect = selectedOptId === sq.correctOptionId;
                                          return (
                                            <p key={sq.id} className="text-xs">
                                              <span className="text-gray-400">{sq.text}:</span>{" "}
                                              <span className={sqCorrect ? "text-green-400" : "text-red-400"}>
                                                {selectedOpt?.label || "(none)"}
                                              </span>
                                              {!sqCorrect && correctOpt && (
                                                <span className="text-green-400 ml-1">(correct: {correctOpt.label})</span>
                                              )}
                                            </p>
                                          );
                                        })}
                                      </div>
                                    ) : hasAnswer ? (
                                      <p className="text-xs mt-1">
                                        <span className="text-gray-400">Answer:</span>{" "}
                                        {selected.map((s) => {
                                          const opt = q.options.find((o) => o.id === s);
                                          return opt?.label || s;
                                        }).join(", ")}
                                        {!isCorrect && (
                                          <span className="text-green-400 ml-1">
                                            (correct: {q.correctAnswers.map((c) => {
                                              const opt = q.options.find((o) => o.id === c);
                                              return opt?.label || c;
                                            }).join(", ")})
                                          </span>
                                        )}
                                      </p>
                                    ) : (
                                      <p className="text-xs mt-1 text-gray-500">Not answered</p>
                                    )}
                                  </div>
                                </div>
                              </div>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            );
          })()}
        </div>
      </main>
    </div>
  );
}
