"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import { getTopicConfig, getTopicCurriculum } from "../config";
import { getLastWatched, getProgress } from "@/app/cloudphone/lib/learning";
import { ParticleBackground } from "@/app/cloudphone/components/ParticleBackground";
import { triggerPay } from "@/app/lib/triggerPay";

type TopicHeroProps = {
  topicId: string;
};

export function TopicHero({ topicId }: TopicHeroProps) {
  const config = getTopicConfig(topicId);
  const curriculum = getTopicCurriculum(topicId);
  const [last, setLast] = useState<ReturnType<typeof getLastWatched>>(null);
  const [progress, setProgress] = useState({ completed: 0, percent: 0 });

  const totalLessons = curriculum?.modules.reduce((s, m) => s + m.lessons.length, 0) ?? 0;

  useEffect(() => {
    if (curriculum?.hasContent && totalLessons > 0) {
      setLast(getLastWatched());
      setProgress(getProgress(totalLessons));
      const onProgress = () => {
        setLast(getLastWatched());
        setProgress(getProgress(totalLessons));
      };
      window.addEventListener("learning:progress", onProgress);
      return () => window.removeEventListener("learning:progress", onProgress);
    }
  }, [curriculum?.hasContent, totalLessons]);

  if (!config) return null;

  const isEnrollCta = !config.externalUrl && !last;

  return (
    <section className="relative overflow-hidden pt-24 pb-16 sm:pt-28 sm:pb-20 md:pt-32 md:pb-24">
      <div className="absolute inset-0 bg-[radial-gradient(ellipse_80%_50%_at_50%_-20%,var(--gradient-accent),transparent)] animate-gradient" />
      <ParticleBackground />
      <div className="relative mx-auto max-w-4xl px-4 text-center sm:px-6">
        <h1
          className="animate__animated animate__fadeInDown mb-4 text-3xl font-bold tracking-tight sm:text-4xl md:text-5xl lg:text-6xl"
          style={{ animationDelay: "0.1s", animationFillMode: "both" }}
        >
          {config.icon} {config.title}
        </h1>
        <p
          className="animate__animated animate__fadeInDown mb-6 text-lg text-[var(--muted-foreground)] sm:mb-8 sm:text-xl md:text-2xl"
          style={{ animationDelay: "0.2s", animationFillMode: "both" }}
        >
          {config.subtitle}
        </p>
        {config.desc && (
          <p
            className="animate__animated animate__fadeInDown mx-auto mb-10 max-w-2xl text-sm text-[var(--muted-foreground)] sm:mb-12 sm:text-base"
            style={{ animationDelay: "0.25s", animationFillMode: "both" }}
          >
            {config.desc}
          </p>
        )}
        <div
          className="animate__animated animate__fadeInDown mb-10 flex flex-wrap justify-center gap-6 sm:mb-12 sm:gap-8"
          style={{ animationDelay: "0.4s", animationFillMode: "both" }}
        >
          {config.stats.map((s) => (
            <div key={s.label} className="text-center transition-transform duration-300 hover:scale-105">
              <div className="text-2xl font-bold text-[var(--accent)] sm:text-3xl md:text-4xl">
                {s.value}
              </div>
              <div className="mt-1 text-xs text-[var(--muted-foreground)] sm:text-sm">{s.label}</div>
            </div>
          ))}
        </div>
        {curriculum?.hasContent && (
          <div
            className="animate__animated animate__fadeInDown flex flex-wrap justify-center gap-3 sm:gap-4"
            style={{ animationDelay: "0.6s", animationFillMode: "both" }}
          >
            {config.externalUrl ? (
              <Link
                href={config.externalUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
              >
                前往了解 →
              </Link>
            ) : isEnrollCta ? (
              <button
                type="button"
                onClick={() => triggerPay()}
                className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
              >
                立即报名 →
              </button>
            ) : (
              <Link
                href={`/cloudphone/course/${last!.moduleIndex}/${last!.lessonIndex}`}
                className="inline-flex shrink-0 items-center gap-2 rounded-full bg-[var(--accent)] px-8 py-4 text-lg font-semibold text-[var(--accent-foreground)] transition hover:opacity-90 sm:px-10"
              >
                继续学习 →
              </Link>
            )}
          </div>
        )}
        {curriculum?.hasContent && progress.completed > 0 && (
          <div className="mt-6 w-full max-w-xs" style={{ animationDelay: "0.7s", animationFillMode: "both" }}>
            <div className="mb-1 flex justify-between text-xs text-[var(--muted-foreground)]">
              <span>学习进度</span>
              <span>
                {progress.completed}/{totalLessons} 节
              </span>
            </div>
            <div className="h-2 overflow-hidden rounded-full bg-[var(--muted)]">
              <div
                className="h-full rounded-full bg-[var(--accent)] transition-all"
                style={{ width: `${progress.percent}%` }}
              />
            </div>
          </div>
        )}
      </div>
    </section>
  );
}
