"use client";
import { Suspense, useRef, useCallback, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { useState, useEffect } from "react";
import gsap from "gsap";
import { useSubscription } from "@/lib/useSubscription";
function safeJsonParse(v: any, fb: any): any {
  if (v === null || v === undefined) return fb;
  if (Array.isArray(v)) return v;
  if (typeof v === "string") { try { return JSON.parse(v); } catch { return fb; } }
  return fb;
}

function FitnessDashboardContent() {
  const sp = useSearchParams();
  const focus = sp.get("focus") || "workout";
  const goalsParam = sp.getAll("goal");
  const primaryGoal = goalsParam[0] || "general";
  const name = sp.get("name") || "Vitality";
  const [loading, setLoading] = useState(true);
  const [profile, setProfile] = useState<any>(null);
  const [activeProgram, setActiveProgram] = useState<any>(null);
  const [products, setProducts] = useState<any[]>([]);
  const [dashboardStats, setDashboardStats] = useState<any>(null);
  const loaded = useRef(false);
  const animated = useRef(false);
  const { subscription: subData, showUpgrade, setShowUpgrade } = useSubscription();

  const runAnim = useCallback(() => {
    if (animated.current) return; animated.current = true;
    requestAnimationFrame(() => {
      const cards = document.querySelectorAll(".dashboard-card");
      if (cards.length > 0) gsap.fromTo(cards, { opacity: 0, y: 30 }, { opacity: 1, y: 0, stagger: 0.1, duration: 0.8, ease: "power4.out" });
    });
  }, []);

  const sortedProducts = useMemo(() => {
    return products.length > 0 ? products.slice(0, 3) : [];
  }, [products]);

  useEffect(() => {
    document.title = "My Fitness Dashboard | Marich Wellness";
    if (loaded.current) return; loaded.current = true;
    async function load() {
      try { const cat = primaryGoal === "weight-loss" || primaryGoal === "general" ? "supplements" : "equipment"; const pr = await fetch("/api/products?category=" + cat + "&limit=6"); if (pr.ok) { const d = await pr.json(); if (d.products) setProducts(d.products); } } catch(e) {}
      try {
        const pr = await fetch("/api/user/profile");
        if (pr.ok) {
          const pd = await pr.json();
          setProfile(pd.profile);
          const email = pd?.profile?.user_email;
          if (email) {
            const pRes = await fetch(`/api/fitness/programs?userId=${encodeURIComponent(email)}&active=true`);
            if (pRes.ok) { const d = await pRes.json(); if (d.programs?.length > 0) setActiveProgram(d.programs[0]); }
            const sRes = await fetch(`/api/fitness/dashboard?userId=${encodeURIComponent(email)}`);
            if (sRes.ok) { const d = await sRes.json(); setDashboardStats(d.stats); }
          }
        }
      } catch(e) { console.warn(e); }
      finally { setLoading(false); setTimeout(() => runAnim(), 100); }
    }
    load();
  }, [runAnim]);

  if (loading) {
    return <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center"><div className="text-emerald-600 font-bold uppercase tracking-widest text-xs">Loading Dashboard...</div></div>;
  }

  const badge = subData.status !== "loading" && <span className={(subData.isPremium ? "bg-emerald-100 text-emerald-700" : subData.isTrialActive ? "bg-amber-100 text-amber-700" : "bg-red-100 text-red-700") + " px-3 py-1 text-[10px] font-bold uppercase tracking-widest rounded-full"}>{subData.isPremium ? "Premium" : subData.isTrialActive ? (30 - subData.remainingDays) + "d trial" : "Expired"}</span>;
  const modal = showUpgrade && <div className="fixed inset-0 z-50 bg-black/50 flex items-center justify-center p-2"><div className="bg-white dark:bg-zinc-900 p-10 max-w-xl mx-4 shadow-2xl relative"><button onClick={() => setShowUpgrade(false)} className="absolute top-3 right-3 w-8 h-8 bg-zinc-200 dark:bg-zinc-700 rounded-full flex items-center justify-center"><span className="material-symbols-outlined text-sm">close</span></button><div className="text-center space-y-6"><span className="material-symbols-outlined text-6xl text-emerald-600 block mb-2">star</span><h2 className="text-3xl md:text-4xl font-serif text-emerald-900 dark:text-emerald-50 italic">Upgrade to Premium</h2><p className="text-black dark:text-white text-lg">Free trial limited. Subscribe to unlock all features.</p><div className="flex justify-center gap-4 mt-8"><button onClick={() => setShowUpgrade(false)} className="px-8 py-4 border-2 border-zinc-300 dark:border-zinc-600 text-black dark:text-white font-bold uppercase tracking-widest text-xs">Later</button><button onClick={() => alert("Subscribe now. Payment coming soon.")} className="px-10 py-5 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs">Subscribe Now</button></div></div></div></div>;
  return (
    <>
      {modal}
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 font-sans text-primary">
        <header className="px-6 py-6 max-w-7xl mx-auto flex items-center justify-between">
          <Link href="/" className="text-2xl font-serif text-emerald-900 dark:text-emerald-50 italic">Marich Wellness</Link>
          <div className="flex items-center gap-4">
            {badge}
            <Link href="/fitness-planner/my-plans" className="text-xs font-bold uppercase tracking-widest bg-emerald-900 text-white px-4 py-3">My Plans</Link>
            <Link href="/fitness-planner/reports" className="text-xs font-bold uppercase tracking-widest border-2 border-emerald-900 text-emerald-900 dark:text-emerald-50 dark:border-emerald-50 px-4 py-3">Reports</Link>
          </div>
        </header>

        <main className="max-w-7xl mx-auto px-6 pb-24 space-y-8">
          <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-8">
            <div className="flex items-start justify-between">
              <div>
                <h2 className="text-4xl md:text-5xl font-serif text-emerald-900 dark:text-emerald-50 italic tracking-tight">Welcome, {name}</h2>
                <p className="text-xl text-black dark:text-white font-serif italic mt-2">{focus === "meal" ? "Nutrition Planning Strategy" : getGoalTitle()} {activeProgram ? "• Week " + activeProgram.current_week + ", Day " + activeProgram.current_day : ""}</p>
              </div>
            </div>
          </div>

          {dashboardStats && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
              <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
                <span className="text-3xl font-bold text-emerald-600">{dashboardStats.totalWorkouts || 0}</span>
                <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Workouts Done</p>
              </div>
              <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
                <span className="text-3xl font-bold text-emerald-600">{Math.floor((dashboardStats.totalTimeSeconds || 0) / 60)}m</span>
                <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Total Time</p>
              </div>
              <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
                <span className="text-3xl font-bold text-emerald-600">{Math.round((dashboardStats.avgTimeSeconds || 0) / 60)}m</span>
                <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Avg Duration</p>
              </div>
              <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 text-center">
                <span className="text-3xl font-bold text-emerald-600">{dashboardStats.completionPercent || 0}%</span>
                <p className="text-[10px] uppercase font-bold tracking-widest text-zinc-500 mt-1">Weekly Goal</p>
              </div>
            </div>
          )}
          {activeProgram && (
            <div className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-8">
              <div className="flex items-center justify-between">
                <div>
                  <h3 className="text-2xl font-bold text-emerald-900 dark:text-emerald-50">{activeProgram.name}</h3>
                  <p className="text-sm text-zinc-600 dark:text-zinc-400 mt-1">Week {activeProgram.current_week} · Day {activeProgram.current_day}</p>
                </div>
                <Link href={"/fitness-planner/program/" + activeProgram.id} className="px-6 py-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs hover:bg-emerald-800 transition-all">Go to Workout</Link>
              </div>
            </div>
          )}

          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            <Link href="/fitness-planner/library" className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-8 hover:shadow-2xl transition-all group">
              <div className="flex items-center gap-4 mb-4">
                <span className="material-symbols-outlined text-4xl text-emerald-600">library_books</span>
                <div><h3 className="text-xl font-bold text-emerald-900 dark:text-emerald-50">Browse Plans</h3><p className="text-[10px] uppercase tracking-widest font-bold text-zinc-400">Explore available programs</p></div>
              </div>
              <span className="text-xs font-bold uppercase tracking-widest text-emerald-600 group-hover:translate-x-2 transition-transform inline-block">View Plans →</span>
            </Link>
            <Link href="/fitness-planner/reports" className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-8 hover:shadow-2xl transition-all group">
              <div className="flex items-center gap-4 mb-4">
                <span className="material-symbols-outlined text-4xl text-emerald-600">bar_chart</span>
                <div><h3 className="text-xl font-bold text-emerald-900 dark:text-emerald-50">View Reports</h3><p className="text-[10px] uppercase tracking-widest font-bold text-zinc-400">Track your progress</p></div>
              </div>
              <span className="text-xs font-bold uppercase tracking-widest text-emerald-600 group-hover:translate-x-2 transition-transform inline-block">View Reports →</span>
            </Link>
          </div>

          {sortedProducts.length > 0 && (
            <section>
              <div className="flex items-center justify-between mb-6">
                <h2 className="text-xs font-bold uppercase tracking-[0.3em] text-black dark:text-white">Recommended Products</h2>
                <Link href={"/shop/" + (primaryGoal === "weight-loss" ? "supplements" : "equipment")} className="text-[10px] uppercase tracking-widest font-bold text-emerald-600 hover:text-emerald-700">View All →</Link>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {sortedProducts.map((prod: any, i: number) => {
                  const imgUrl = prod.image || prod.img || "";
                  return (
                    <div key={i} className="dashboard-card opacity-0 bg-white dark:bg-zinc-900 border border-zinc-200 dark:border-zinc-700 p-6 space-y-4 group hover:shadow-2xl transition-all duration-500">
                      <div className="aspect-square bg-zinc-100 dark:bg-zinc-800 overflow-hidden relative flex items-center justify-center">
                        {imgUrl ? <img src={imgUrl} loading="lazy" className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-110" alt={prod.name} /> : <span className="material-symbols-outlined text-6xl text-zinc-300">fitness_center</span>}
                      </div>
                      <div className="space-y-2">
                        <span className="text-[10px] uppercase font-bold tracking-[0.2em] text-emerald-600">{prod.category}</span>
                        <h4 className="text-xl font-bold text-emerald-900 dark:text-emerald-50">{prod.name}</h4>
                        <span className="text-lg font-bold text-emerald-900 dark:text-emerald-100">{prod.price}</span>
                        <Link href={"/products/" + (prod.slug || prod.id)} className="block w-full py-3 bg-emerald-900 text-white text-center font-bold uppercase tracking-widest text-xs hover:bg-emerald-800 transition-all mt-2">View Details</Link>
                      </div>
                    </div>
                  );
                })}
              </div>
            </section>
          )}
        </main>
      <nav className="lg:hidden fixed bottom-0 left-0 w-full bg-white/80 dark:bg-zinc-950/80 backdrop-blur-xl border-t border-zinc-100 dark:border-zinc-800 px-6 py-4 flex justify-around items-center z-50"><button className="text-emerald-600"><span className="material-symbols-outlined text-3xl">dashboard</span></button><button className="text-zinc-400"><span className="material-symbols-outlined text-3xl">fitness_center</span></button><div className="w-16 h-16 bg-emerald-600 text-white rounded-full flex items-center justify-center -translate-y-8 shadow-2xl border-4 border-surface-container-lowest dark:border-zinc-950"><span className="material-symbols-outlined text-3xl">add</span></div><button className="text-zinc-400"><span className="material-symbols-outlined text-3xl">restaurant</span></button><button className="text-zinc-400"><span className="material-symbols-outlined text-3xl">person</span></button></nav>
      </div>
    </>
  );
}

function getGoalTitle(): string {
  return "Your Fitness Journey";
}

export default function FitnessDashboard() {
  return (
    <Suspense fallback={<div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center"><div className="text-emerald-600 font-bold uppercase tracking-widest text-xs">Loading Dashboard...</div></div>}>
      <FitnessDashboardContent />
    </Suspense>
  );
}
