"use client";

import { useState, useEffect, useCallback } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter, useParams } from "next/navigation";
import {
  ChevronLeft,
  CheckCircle2,
  Circle,
  Headphones,
  Award,
  Lock,
  Loader2,
} from "lucide-react";
import ErrorFeedback from "@/components/ErrorFeedback";

// ── Types ──

interface ModuleProgress {
  completed: boolean;
  score: number | null;
  listened: boolean;
}

interface Module {
  id: string;
  order: number;
  title: string;
  slug: string;
  keyTakeaway: string | null;
  duration: number;
  content: string | null;
  quizData: Record<string, unknown> | null;
  progress: ModuleProgress | null;
}

interface Course {
  id: string;
  slug: string;
  title: string;
  author: string;
  description: string;
  imageUrl: string | null;
  moduleCount: number;
  totalMinutes: number;
  difficulty: string;
  giteaPath: string;
}

interface Enrollment {
  id: string;
  purchaseType: string;
  completed: boolean;
  progress: number;
}

interface CourseData {
  course: Course;
  modules: Module[];
  enrollment: Enrollment | null;
}

interface Certificate {
  id: string;
  serialNumber: string;
  courseId: string;
  score: number | null;
  issuedAt: string;
  pdfPath: string | null;
}

// ── Helpers ──

function getDifficultyColor(difficulty: string): string {
  switch (difficulty) {
    case "beginner":
      return "text-emerald-400 bg-emerald-400/10 border-emerald-400/20";
    case "intermediate":
      return "text-amber-400 bg-amber-400/10 border-amber-400/20";
    case "advanced":
      return "text-red-400 bg-red-400/10 border-red-400/20";
    default:
      return "text-gray-400 bg-gray-400/10 border-gray-400/20";
  }
}

function formatDuration(totalMinutes: number): string {
  if (totalMinutes < 60) return `${totalMinutes} min`;
  const hours = Math.floor(totalMinutes / 60);
  const mins = totalMinutes % 60;
  return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
}

// ── Component ──

export default function LearnCoursePage() {
  const { user, token, loading: authLoading } = useAuth();
  const router = useRouter();
  const params = useParams();
  const slug = params.slug as string;

  const [data, setData] = useState<CourseData | null>(null);
  const [loadingData, setLoadingData] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [certificates, setCertificates] = useState<Certificate[]>([]);

  // ── Fetch course + certificates ──

  const fetchCourse = useCallback(async () => {
    if (!token) return;
    setLoadingData(true);
    setError(null);
    try {
      const [courseRes, certRes] = await Promise.all([
        fetch(`/mobile/api/learn/courses/${slug}`, {
          headers: { Authorization: `Bearer ${token}` },
        }),
        fetch(`/mobile/api/learn/certificates`, {
          headers: { Authorization: `Bearer ${token}` },
        }),
      ]);

      if (courseRes.ok) {
        const d = await courseRes.json();
        setData(d);
      } else {
        const d = await courseRes.json().catch(() => ({}));
        setError(d.error || "Failed to load course");
      }

      if (certRes.ok) {
        const d = await certRes.json();
        setCertificates(d.certificates || []);
      }
    } catch {
      setError("Network error. Please try again.");
    } finally {
      setLoadingData(false);
    }
  }, [token, slug]);

  // ── Auth guard ──

  useEffect(() => {
    if (!authLoading && !token) {
      router.push("/auth");
    }
  }, [authLoading, token, router]);

  // ── Fetch on mount ──

  useEffect(() => {
    if (token && slug) {
      fetchCourse();
    }
  }, [token, slug, fetchCourse]);

  // ── Derived state ──

  const isEnrolled = !!data?.enrollment;
  const progress = data?.enrollment?.progress ?? 0;
  const progressPercent = Math.round(progress * 100);
  const completedModules =
    data?.modules.filter((m) => m.progress?.completed).length ?? 0;

  const certificate = certificates.find(
    (c) => c.courseId === data?.course?.id
  );
  const canViewCertificate =
    data?.enrollment?.completed && !!certificate?.serialNumber;

  // ── Loading state ──

  if (authLoading) {
    return (
      <div className="min-h-dvh bg-[#0a0a0f] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#D4AF37]/30 border-t-[#D4AF37] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  return (
    <div className="min-h-dvh bg-[#0a0a0f] pb-28">
      {/* ── Sticky header ── */}
      <div className="sticky top-0 z-20 bg-[#0a0a0f]/90 backdrop-blur-lg border-b border-gray-800/40">
        <div className="flex items-center gap-3 px-4 h-12">
          <button
            onClick={() => router.push("/learn")}
            className="w-8 h-8 rounded-full bg-gray-800/60 flex items-center justify-center active:bg-gray-700/60 transition"
          >
            <ChevronLeft size={16} className="text-gray-400" />
          </button>
          <h1 className="text-sm font-semibold text-white truncate">
            {data ? data.course.title : "Course"}
          </h1>
        </div>
      </div>

      {/* ── Loading / Error / Empty ── */}
      {loadingData ? (
        <div className="flex flex-col items-center justify-center py-20">
          <Loader2 size={32} className="text-[#D4AF37] animate-spin mb-3" />
          <p className="text-sm text-gray-500">Loading course...</p>
        </div>
      ) : error ? (
        <ErrorFeedback
          error={error}
          kind="network"
          onRetry={fetchCourse}
          context="learn course detail"
        />
      ) : !data ? (
        <div className="mx-4 mt-4 bg-gray-900/40 border border-gray-800/60 rounded-2xl p-6 text-center">
          <p className="text-sm text-gray-400">Course not found</p>
          <button
            onClick={() => router.push("/learn")}
            className="mt-3 text-xs text-[#D4AF37] underline"
          >
            Back to courses
          </button>
        </div>
      ) : (
        <>
          {/* ── Course header card ── */}
          <div className="px-4 pt-4 pb-2">
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl p-5">
              {/* Title + author */}
              <h2 className="text-lg font-bold text-white">
                {data.course.title}
              </h2>
              <p className="text-xs text-gray-400 mt-1">
                by{" "}
                <span className="text-[#D4AF37]">{data.course.author}</span>
              </p>

              {/* Tags row */}
              <div className="flex flex-wrap items-center gap-2 mt-3">
                <span
                  className={`text-[10px] font-medium px-2 py-0.5 rounded-full border ${getDifficultyColor(
                    data.course.difficulty
                  )}`}
                >
                  {data.course.difficulty}
                </span>
                <span className="text-[10px] text-gray-500 bg-gray-800/60 px-2 py-0.5 rounded-full border border-gray-700/40">
                  {data.course.moduleCount} module
                  {data.course.moduleCount !== 1 ? "s" : ""}
                </span>
                <span className="text-[10px] text-gray-500 bg-gray-800/60 px-2 py-0.5 rounded-full border border-gray-700/40">
                  {formatDuration(data.course.totalMinutes)}
                </span>
              </div>

              {/* Description */}
              {data.course.description && (
                <p className="text-xs text-gray-500 mt-3 leading-relaxed">
                  {data.course.description}
                </p>
              )}

              {/* ── Progress bar (only if enrolled) ── */}
              {isEnrolled && (
                <div className="mt-4">
                  <div className="flex items-center justify-between mb-1.5">
                    <span className="text-[11px] text-gray-500">
                      Progress
                    </span>
                    <span className="text-[11px] font-medium text-gray-400">
                      {completedModules}/{data.modules.length} modules
                    </span>
                  </div>
                  <div className="w-full h-2 bg-gray-800/80 rounded-full overflow-hidden">
                    <div
                      className="h-full bg-gradient-to-r from-[#D4AF37] to-amber-400 rounded-full transition-all duration-500"
                      style={{ width: `${progressPercent}%` }}
                    />
                  </div>
                  <span className="text-[10px] text-gray-600 mt-1 block">
                    {progressPercent}% complete
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* ── Purchase / Certificate call-to-action ── */}
          <div className="px-4 mb-3">
            {!isEnrolled ? (
              <button
                onClick={() =>
                  window.open(
                    `https://istore.falahos.my/courses/${slug}`,
                    "_blank"
                  )
                }
                className="w-full flex items-center justify-center gap-2 bg-amber-500/15 border border-amber-500/30 rounded-xl px-4 py-3.5 active:bg-amber-500/25 transition"
              >
                <Lock size={16} className="text-amber-400" />
                <span className="text-sm font-medium text-amber-400">
                  Purchase on iStore
                </span>
              </button>
            ) : canViewCertificate ? (
              <a
                href={`/mobile/api/learn/certificates/${certificate!.serialNumber}`}
                target="_blank"
                rel="noopener noreferrer"
                className="w-full flex items-center justify-center gap-2 bg-emerald-500/15 border border-emerald-500/30 rounded-xl px-4 py-3.5 active:bg-emerald-500/25 transition"
              >
                <Award size={16} className="text-emerald-400" />
                <span className="text-sm font-medium text-emerald-400">
                  🎓 View Certificate
                </span>
              </a>
            ) : null}
          </div>

          {/* ── Module list ── */}
          <div className="px-4">
            <h3 className="text-xs font-semibold text-gray-500 uppercase tracking-wider mb-3 px-1">
              Course Modules
            </h3>

            <div className="relative space-y-0">
              {/* Vertical timeline line */}
              <div className="absolute left-[17px] top-2 bottom-2 w-px bg-gray-800/60" />

              {data.modules.map((mod) => {
                const isCompleted = mod.progress?.completed ?? false;
                const hasQuiz = !!mod.quizData;
                const quizScore = mod.progress?.score ?? null;
                const hasListened = mod.progress?.listened ?? false;

                return (
                  <div key={mod.id} className="relative flex gap-3 pb-4">
                    {/* Timeline dot */}
                    <div className="relative z-10 flex-shrink-0 mt-1">
                      {isCompleted ? (
                        <CheckCircle2
                          size={20}
                          className="text-emerald-400"
                        />
                      ) : (
                        <Circle
                          size={20}
                          className="text-gray-600"
                        />
                      )}
                    </div>

                    {/* Module card */}
                    <div className="flex-1 min-w-0">
                      <button
                        onClick={() => {
                          router.push(`/learn/${slug}/${mod.slug}`);
                        }}
                        className="w-full text-left bg-[#111118] border border-gray-800/60 rounded-xl p-3.5 active:bg-[#1a1a24] transition"
                      >
                        {/* Header row */}
                        <div className="flex items-start justify-between gap-2">
                          <div className="flex-1 min-w-0">
                            <span className="text-[10px] text-gray-600 font-medium">
                              Module {mod.order}
                            </span>
                            <h4 className="text-sm font-semibold text-white mt-0.5 leading-snug">
                              {mod.title}
                            </h4>
                          </div>

                          {/* Duration badge */}
                          <span className="shrink-0 text-[10px] text-gray-500 bg-gray-800/60 px-2 py-0.5 rounded-full border border-gray-700/40 whitespace-nowrap">
                            {mod.duration} min
                          </span>
                        </div>

                        {/* Key takeaway */}
                        {mod.keyTakeaway && (
                          <p className="text-xs text-gray-500 mt-2 leading-relaxed border-t border-gray-800/60 pt-2">
                            {mod.keyTakeaway}
                          </p>
                        )}

                        {/* Action buttons row */}
                        <div className="flex items-center gap-2 mt-3">
                          {/* Listen button */}
                          <button
                            onClick={(e) => {
                              e.stopPropagation();
                              router.push(
                                `/learn/${slug}/${mod.slug}?listen=true`
                              );
                            }}
                            className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[10px] font-medium transition ${
                              hasListened
                                ? "bg-emerald-500/10 border border-emerald-500/20 text-emerald-400"
                                : "bg-gray-800/60 border border-gray-700/40 text-gray-400 hover:border-gray-600/60"
                            }`}
                          >
                            <Headphones size={12} />
                            Listen
                          </button>

                          {/* Quiz status */}
                          {hasQuiz && (
                            <span
                              className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[10px] font-medium border ${
                                quizScore !== null
                                  ? "bg-emerald-500/10 border-emerald-500/20 text-emerald-400"
                                  : "bg-gray-800/60 border-gray-700/40 text-gray-500"
                              }`}
                            >
                              {quizScore !== null
                                ? `Quiz: ${Math.round(quizScore)}%`
                                : "Quiz"}
                            </span>
                          )}
                        </div>
                      </button>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          {/* ── Course footer stats ── */}
          <div className="px-4 mt-4">
            <div className="bg-[#111118] border border-gray-800/60 rounded-2xl px-4 py-3">
              <div className="flex items-center justify-between text-xs text-gray-500">
                <span>Total duration</span>
                <span className="text-gray-400 font-medium">
                  {formatDuration(data.course.totalMinutes)}
                </span>
              </div>
              {isEnrolled && (
                <div className="flex items-center justify-between text-xs text-gray-500 mt-2 pt-2 border-t border-gray-800/40">
                  <span>Enrolled</span>
                  <span className="text-emerald-400 font-medium">
                    {data.enrollment!.purchaseType === "free"
                      ? "Free"
                      : data.enrollment!.purchaseType === "subscription"
                        ? "Subscription"
                        : "Purchased"}
                  </span>
                </div>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
