"use client";

import { useState, useEffect } from "react";
import { useAuth } from "@/lib/AuthContext";
import { useRouter } from "next/navigation";
import {
  Lock,
  Book,
  Headphones,
  Award,
  Sparkles,
} from "lucide-react";

/* ------------------------------------------------------------------ */
/*  Types                                                             */
/* ------------------------------------------------------------------ */

interface CourseEnrollment {
  progress: number;
  completed: boolean;
}

interface LearnCourse {
  id: string;
  slug: string;
  title: string;
  author: string;
  description: string;
  imageUrl: string | null;
  moduleCount: number;
  totalMinutes: number;
  difficulty: string;
  priceFlh: number | null;
  priceUsd: number | null;
  subscriptionOnly: boolean;
  enrolled: boolean | null;
  enrollment?: CourseEnrollment;
}

/* ------------------------------------------------------------------ */
/*  Helpers                                                           */
/* ------------------------------------------------------------------ */

const DIFFICULTY_STYLES: Record<string, { label: string; classes: string }> = {
  beginner: {
    label: "Beginner",
    classes: "bg-green-900/30 text-[#00C48C] border border-green-800/30",
  },
  intermediate: {
    label: "Intermediate",
    classes: "bg-amber-900/30 text-amber-400 border border-amber-800/30",
  },
  advanced: {
    label: "Advanced",
    classes: "bg-red-900/30 text-red-400 border border-red-800/30",
  },
};

function difficultyLabel(diff: string): { label: string; classes: string } {
  return DIFFICULTY_STYLES[diff] ?? {
    label: diff,
    classes: "bg-gray-800/40 text-gray-400 border border-gray-700/30",
  };
}

function formatPrice(course: LearnCourse): string {
  if (course.subscriptionOnly) return "Learn Pass";
  if (course.priceFlh === null && course.priceUsd === null) return "FREE";
  if (course.priceUsd !== null) return `$${course.priceUsd.toFixed(2)}`;
  if (course.priceFlh !== null) return `FLH ${course.priceFlh.toLocaleString()}`;
  return "FREE";
}

function isFree(course: LearnCourse): boolean {
  if (course.subscriptionOnly) return false;
  return course.priceFlh === null && course.priceUsd === null;
}

/* ------------------------------------------------------------------ */
/*  Placeholder Thumbnail                                              */
/* ------------------------------------------------------------------ */

const COURSE_VISUALS: Record<string, { icon: string; bg: string }> = {
  // A few known slugs get themed visuals
  default: { icon: "📖", bg: "from-[#C9A84C]/20 to-[#C9A84C]/5" },
};

function courseVisual(slug: string): { icon: string; bg: string } {
  return COURSE_VISUALS[slug] ?? COURSE_VISUALS.default;
}

/* ------------------------------------------------------------------ */
/*  Page Component                                                    */
/* ------------------------------------------------------------------ */

export default function LearnCatalogPage() {
  const { user, token, loading } = useAuth();
  const router = useRouter();

  const [courses, setCourses] = useState<LearnCourse[]>([]);
  const [fetching, setFetching] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Redirect to auth if not logged in
  useEffect(() => {
    if (!loading && !token) router.push("/auth");
  }, [loading, token, router]);

  // Fetch courses
  useEffect(() => {
    if (!token) return;
    setFetching(true);
    setError(null);
    fetch("/mobile/api/learn/courses", {
      headers: { Authorization: `Bearer ${token}` },
    })
      .then((r) => {
        if (!r.ok) throw new Error("Failed to load courses");
        return r.json();
      })
      .then((data: { courses: LearnCourse[] }) =>
        setCourses(data.courses || [])
      )
      .catch((err: Error) => setError(err.message))
      .finally(() => setFetching(false));
  }, [token]);

  // ── Loading state ──
  if (loading) {
    return (
      <div className="min-h-dvh bg-[#07090C] flex items-center justify-center">
        <div className="w-8 h-8 rounded-full border-2 border-[#C9A84C]/30 border-t-[#C9A84C] animate-spin" />
      </div>
    );
  }

  if (!user) return null;

  // ── Guard: token present but no user yet ──
  if (!token) return null;

  // ── Enrolled / locked separation ──
  const enrolled = courses.filter((c) => c.enrolled === true);
  const locked = courses.filter((c) => c.enrolled !== true);

  return (
    <div className="min-h-dvh bg-[#07090C] pb-24">
      {/* ── Header ── */}
      <div className="px-0 pt-6 pb-2">
        <div className="flex items-center justify-between mb-1">
          <div>
            <h1 className="text-xl font-bold text-white">Falah Learn</h1>
            <p className="text-xs text-gray-500 mt-0.5">
              Micro learning courses. 5 minutes at a time.
            </p>
          </div>
          <div className="w-10 h-10 rounded-xl bg-[#C9A84C]/15 flex items-center justify-center">
            <Book size={20} className="text-[#C9A84C]" />
          </div>
        </div>
      </div>

      {/* ── Error state ── */}
      {error && !fetching && (
        <div className="mx-0 mt-4 bg-[#111118] border border-red-900/40 rounded-2xl p-5 text-center">
          <p className="text-sm text-red-400">{error}</p>
          <button
            onClick={() => {
              setFetching(true);
              setError(null);
              fetch("/mobile/api/learn/courses", {
                headers: { Authorization: `Bearer ${token}` },
              })
                .then((r) => {
                  if (!r.ok) throw new Error("Failed to load courses");
                  return r.json();
                })
                .then((data: { courses: LearnCourse[] }) =>
                  setCourses(data.courses || [])
                )
                .catch((err: Error) => setError(err.message))
                .finally(() => setFetching(false));
            }}
            className="mt-3 text-xs text-[#C9A84C] underline underline-offset-2"
          >
            Try again
          </button>
        </div>
      )}

      {/* ── Loading skeleton ── */}
      {fetching && (
        <div className="mt-6 space-y-4">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="bg-[#0C1017] border border-gray-800/40 rounded-2xl overflow-hidden animate-pulse"
            >
              <div className="h-32 bg-gray-800/30" />
              <div className="p-4 space-y-3">
                <div className="h-4 bg-gray-800/40 rounded w-3/4" />
                <div className="h-3 bg-gray-800/30 rounded w-1/2" />
                <div className="flex gap-2">
                  <div className="h-5 bg-gray-800/30 rounded-full w-16" />
                  <div className="h-5 bg-gray-800/30 rounded-full w-12" />
                </div>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* ── Course grid ── */}
      {!fetching && !error && courses.length === 0 && (
        <div className="mx-0 mt-8 bg-[#111118] border border-gray-800/60 rounded-2xl p-8 text-center">
          <Book size={32} className="mx-auto text-gray-700 mb-3" />
          <p className="text-sm text-gray-500">No courses available yet</p>
          <p className="text-xs text-gray-700 mt-1">
            Check back soon for new micro learning content
          </p>
        </div>
      )}

      {!fetching && !error && courses.length > 0 && (
        <>
          {/* ── Enrolled courses section ── */}
          {enrolled.length > 0 && (
            <div className="mt-6">
              <h2 className="text-sm font-semibold text-white flex items-center gap-2 mb-3">
                <Book size={14} className="text-[#00C48C]" />
                My Courses
              </h2>
              <div className="grid grid-cols-1 gap-4">
                {enrolled.map((course) => (
                  <CourseCard
                    key={course.id}
                    course={course}
                    enrolled
                    router={router}
                  />
                ))}
              </div>
            </div>
          )}

          {/* ── All / locked courses section ── */}
          <div className="mt-6">
            <h2 className="text-sm font-semibold text-white flex items-center gap-2 mb-3">
              <Award size={14} className="text-[#C9A84C]" />
              {enrolled.length > 0 ? "More Courses" : "All Courses"}
            </h2>
            <div className="grid grid-cols-1 gap-4">
              {locked.map((course) => (
                <CourseCard
                  key={course.id}
                  course={course}
                  enrolled={false}
                  router={router}
                />
              ))}
            </div>
          </div>
        </>
      )}

      {/* ── Learn Pass subscription card ── */}
      <div className="mt-8 mx-0">
        <div className="bg-gradient-to-br from-[#C9A84C]/10 to-[#C9A84C]/5 border border-[#C9A84C]/20 rounded-2xl p-5 relative overflow-hidden">
          {/* Decorative glow */}
          <div className="absolute -top-10 -right-10 w-32 h-32 bg-[#C9A84C]/10 rounded-full blur-3xl pointer-events-none" />
          <div className="absolute -bottom-8 -left-8 w-28 h-28 bg-[#00C48C]/5 rounded-full blur-3xl pointer-events-none" />

          <div className="relative z-10">
            <div className="flex items-center gap-2 mb-2">
              <Sparkles size={18} className="text-[#C9A84C]" />
              <h3 className="text-base font-bold text-white">Learn Pass</h3>
            </div>
            <p className="text-xs text-gray-400 mb-4 leading-relaxed">
              Get unlimited access to all courses, audio lessons, and
              certificates with a Learn Pass subscription.
            </p>
            <div className="flex items-center gap-4 mb-4">
              <div className="flex items-center gap-1.5 text-[11px] text-gray-500">
                <Headphones size={13} className="text-[#C9A84C]/70" />
                Audio lessons
              </div>
              <div className="flex items-center gap-1.5 text-[11px] text-gray-500">
                <Award size={13} className="text-[#C9A84C]/70" />
                Certificates
              </div>
              <div className="flex items-center gap-1.5 text-[11px] text-gray-500">
                <Book size={13} className="text-[#C9A84C]/70" />
                All courses
              </div>
            </div>
            <a
              href="https://istore.falahos.my"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-2 bg-[#C9A84C] text-[#07090C] text-sm font-semibold px-5 py-2.5 rounded-xl hover:bg-[#C9A84C]/90 active:scale-[0.97] transition min-h-[44px]"
            >
              <Sparkles size={16} />
              Get Learn Pass
            </a>
          </div>
        </div>
      </div>

      <div className="h-6" />
    </div>
  );
}

/* ------------------------------------------------------------------ */
/*  Course Card                                                        */
/* ------------------------------------------------------------------ */

function CourseCard({
  course,
  enrolled,
  router,
}: {
  course: LearnCourse;
  enrolled: boolean;
  router: ReturnType<typeof useRouter>;
}) {
  const vis = courseVisual(course.slug);
  const diff = difficultyLabel(course.difficulty);

  const handleClick = () => {
    if (enrolled) {
      router.push(`/learn/${course.slug}`);
    }
  };

  return (
    <div
      className={`bg-[#0C1017] border rounded-2xl overflow-hidden transition ${
        enrolled
          ? "border-gray-800/60 hover:border-gray-700/60 active:scale-[0.98] cursor-pointer"
          : "border-gray-800/40"
      }`}
      onClick={handleClick}
      role={enrolled ? "button" : "article"}
      tabIndex={enrolled ? 0 : undefined}
      onKeyDown={
        enrolled
          ? (e) => {
              if (e.key === "Enter" || e.key === " ") {
                e.preventDefault();
                router.push(`/learn/${course.slug}`);
              }
            }
          : undefined
      }
    >
      {/* Thumbnail placeholder */}
      <div
        className={`h-32 bg-gradient-to-br ${vis.bg} flex items-center justify-center relative`}
      >
        <span className="text-4xl">{vis.icon}</span>

        {/* Lock overlay for locked courses */}
        {!enrolled && (
          <div className="absolute inset-0 bg-[#07090C]/40 flex items-center justify-center backdrop-blur-[1px]">
            <div className="w-9 h-9 rounded-full bg-[#07090C]/70 flex items-center justify-center">
              <Lock size={16} className="text-gray-400" />
            </div>
          </div>
        )}

        {/* Progress bar for enrolled courses */}
        {enrolled && course.enrollment && (
          <div className="absolute bottom-0 left-0 right-0 h-1 bg-gray-800/60">
            <div
              className="h-full bg-[#00C48C] transition-all duration-500"
              style={{
                width: `${Math.min(100, Math.round((course.enrollment.progress ?? 0) * 100))}%`,
              }}
            />
          </div>
        )}
      </div>

      {/* Content */}
      <div className="p-4 space-y-2">
        {/* Title */}
        <h3 className="text-sm font-semibold text-white leading-tight line-clamp-2 min-h-[2.5rem]">
          {course.title}
        </h3>

        {/* Author */}
        <p className="text-[11px] text-gray-500 truncate">{course.author}</p>

        {/* Meta row: difficulty badge + modules */}
        <div className="flex items-center gap-2 flex-wrap">
          <span
            className={`text-[10px] font-medium px-2 py-0.5 rounded-full ${diff.classes}`}
          >
            {diff.label}
          </span>
          <span className="text-[10px] text-gray-500">
            {course.moduleCount} module{course.moduleCount !== 1 ? "s" : ""}
          </span>
          {course.totalMinutes > 0 && (
            <span className="text-[10px] text-gray-500">
              ~{course.totalMinutes} min
            </span>
          )}
        </div>

        {/* Price / CTA row */}
        <div className="flex items-center justify-between pt-1">
          <span
            className={`text-sm font-bold ${
              isFree(course) ? "text-[#00C48C]" : "text-[#C9A84C]"
            }`}
          >
            {formatPrice(course)}
          </span>

          {!enrolled && (
            <a
              href="https://istore.falahos.my"
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1 text-[11px] font-medium text-[#C9A84C] bg-[#C9A84C]/10 border border-[#C9A84C]/20 rounded-lg px-3 py-1.5 hover:bg-[#C9A84C]/20 active:scale-95 transition min-h-[36px]"
              onClick={(e) => e.stopPropagation()}
            >
              Get on iStore →
            </a>
          )}

          {enrolled && (
            <span className="flex items-center gap-1 text-[11px] text-[#00C48C]">
              {course.enrollment?.completed ? (
                <>
                  <Award size={12} /> Completed
                </>
              ) : course.enrollment && (course.enrollment.progress ?? 0) > 0 ? (
                <>
                  <Book size={12} />
                  {Math.round((course.enrollment.progress ?? 0) * 100)}%
                </>
              ) : (
                <>
                  <Headphones size={12} /> Start
                </>
              )}
            </span>
          )}
        </div>
      </div>
    </div>
  );
}
