"use client";

import { useState, useEffect, useRef } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import gsap from "gsap";

interface Template {
  id: string;
  name: string;
  description: string;
  level: string;
  goal: string;
  days_per_week: number;
  total_weeks: number;
  estimated_calories_per_week: number;
  equipment_needed: string;
  who_is_for: string;
  long_description: string;
}

const LEVEL_BADGE_STYLES: Record<string, string> = {
  beginner: "bg-emerald-600 text-white",
  intermediate: "bg-blue-600 text-white",
  advanced: "bg-orange-600 text-white",
};

const LEVEL_LABELS: Record<string, string> = {
  beginner: "Beginner",
  intermediate: "Intermediate",
  advanced: "Advanced",
};

export default function ProgramLibraryPage() {
  const router = useRouter();
  const gridRef = useRef<HTMLDivElement>(null);
  const [templates, setTemplates] = useState<Template[]>([]);
  const [filteredTemplates, setFilteredTemplates] = useState<Template[]>([]);
  const [activeTab, setActiveTab] = useState("all");
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [savedProgramIds, setSavedProgramIds] = useState<string[]>([]);
  const [activeProgramId, setActiveProgramId] = useState<string | null>(null);

  useEffect(() => {
    document.title = "Workout Plans Library | Marich Wellness";
    fetchTemplates();
    fetchUserPrograms();
  }, []);

  useEffect(() => {
    if (filteredTemplates.length > 0 && gridRef.current) {
      const cards = gridRef.current.querySelectorAll(".program-card");
      if (cards.length > 0) {
        gsap.fromTo(
          cards,
          { opacity: 0, y: 30 },
          { opacity: 1, y: 0, stagger: 0.06, duration: 0.5, ease: "power3.out" }
        );
      }
    }
  }, [filteredTemplates]);

  async function fetchTemplates() {
    try {
      const res = await fetch('/api/fitness/templates');
      if (!res.ok) throw new Error('Failed to fetch templates');
      const data = await res.json();
      setTemplates(data.templates || []);
      setFilteredTemplates(data.templates || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }

  async function fetchUserPrograms() {
    try {
      const profileRes = await fetch('/api/user/profile');
      if (profileRes.ok) {
        const profileData = await profileRes.json();
        const email = profileData?.profile?.user_email;
        if (email) {
          const programsRes = await fetch(`/api/fitness/programs?userId=${encodeURIComponent(email)}`);
          if (programsRes.ok) {
            const programsData = await programsRes.json();
            const saved = (programsData.programs || []).map((p: any) => p.template_id).filter(Boolean);
            setSavedProgramIds(saved);
            const active = (programsData.programs || []).find((p: any) => p.is_active);
            if (active) setActiveProgramId(active.template_id);
          }
        }
      }
    } catch (err) {
      // Silently fail - user may not be logged in
    }
  }

  function handleFilter(level: string) {
    setActiveTab(level);
    if (level === "all") {
      setFilteredTemplates(templates);
    } else {
      setFilteredTemplates(templates.filter(t => t.level === level));
    }
  }

  async function handleSaveProgram(template: Template) {
    try {
      const profileRes = await fetch('/api/user/profile');
      if (!profileRes.ok) {
        alert('Please complete the fitness questionnaire first to save programs.');
        router.push('/fitness-planner');
        return;
      }
      const profileData = await profileRes.json();
      const email = profileData?.profile?.user_email;
      if (!email) {
        alert('Please complete the fitness questionnaire first to save programs.');
        router.push('/fitness-planner');
        return;
      }

      const res = await fetch('/api/fitness/programs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          user_id: email,
          template_id: template.id,
          name: template.name,
          description: template.description,
          is_active: false,
          source: 'template',
        }),
      });

      if (res.ok) {
        setSavedProgramIds(prev => [...prev, template.id]);
      } else {
        const data = await res.json();
        alert(data.error || 'Failed to save program');
      }
    } catch (err: any) {
      alert('Error saving program: ' + err.message);
    }
  }

  async function handleSetActive(template: Template) {
    try {
      const profileRes = await fetch('/api/user/profile');
      if (!profileRes.ok) {
        alert('Please complete the fitness questionnaire first.');
        router.push('/fitness-planner');
        return;
      }
      const profileData = await profileRes.json();
      const email = profileData?.profile?.user_email;
      if (!email) {
        alert('Please complete the fitness questionnaire first.');
        router.push('/fitness-planner');
        return;
      }

      let programId = savedProgramIds.includes(template.id) 
        ? template.id 
        : null;

      if (!programId) {
        const saveRes = await fetch('/api/fitness/programs', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            user_id: email,
            template_id: template.id,
            name: template.name,
            description: template.description,
            is_active: true,
            source: 'template',
          }),
        });
        if (saveRes.ok) {
          setSavedProgramIds(prev => [...prev, template.id]);
          setActiveProgramId(template.id);
        }
      } else {
        const programsRes = await fetch(`/api/fitness/programs?userId=${encodeURIComponent(email)}`);
        if (programsRes.ok) {
          const programsData = await programsRes.json();
          const userProgram = (programsData.programs || []).find((p: any) => p.template_id === template.id);
          if (userProgram) {
            const updateRes = await fetch(`/api/fitness/programs/${userProgram.id}`, {
              method: 'PUT',
              headers: { 'Content-Type': 'application/json' },
              body: JSON.stringify({ is_active: true }),
            });
            if (updateRes.ok) {
              setActiveProgramId(template.id);
            }
          }
        }
      }
    } catch (err: any) {
      alert('Error setting active program: ' + err.message);
    }
  }

  const tabCounts = {
    all: templates.length,
    beginner: templates.filter(t => t.level === 'beginner').length,
    intermediate: templates.filter(t => t.level === 'intermediate').length,
    advanced: templates.filter(t => t.level === 'advanced').length,
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center">
        <div className="text-center space-y-4">
          <div className="w-12 h-12 border-4 border-emerald-100 border-t-emerald-600 rounded-full animate-spin mx-auto"></div>
          <p className="text-emerald-600 font-bold uppercase tracking-widest text-xs">Loading Programs...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950 flex items-center justify-center">
        <div className="text-center space-y-4">
          <p className="text-red-500 font-serif italic text-xl">Failed to load programs</p>
          <button onClick={fetchTemplates} className="px-6 py-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs">
            Retry
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950">
      {/* Navigation */}
      <nav className="px-6 py-6 flex justify-between items-center max-w-7xl mx-auto w-full">
        <Link href="/" className="text-2xl font-serif text-emerald-900 dark:text-emerald-50 italic">
          Marich Wellness
        </Link>
        <div className="flex items-center gap-6">
          <Link href="/fitness-planner/dashboard" className="text-black dark:text-white hover:text-emerald-600 transition-colors">
            <span className="material-symbols-outlined text-2xl">arrow_back</span>
          </Link>
        </div>
      </nav>

      <main className="max-w-7xl mx-auto px-6 pb-16">
        {/* Page Header */}
        <div className="mb-8 space-y-3">
          <h1 className="text-4xl md:text-6xl font-serif text-emerald-900 dark:text-emerald-50 italic tracking-tight leading-none">
            Workout Plans
          </h1>
          <p className="text-lg md:text-xl text-black dark:text-white font-serif italic">
            Browse and save pre-built programs for every level
          </p>
          <div className="flex items-center gap-2 text-black dark:text-white">
            <span className="material-symbols-outlined text-lg text-black dark:text-white">book</span>
            <span className="text-sm font-bold uppercase tracking-widest text-black dark:text-white">{templates.length} programs</span>
          </div>
        </div>

        {/* Filter Tabs */}
        <div className="flex gap-2 mb-8 overflow-x-auto pb-2">
          {[
            { id: "all", label: "All", count: tabCounts.all },
            { id: "beginner", label: "Beginner", count: tabCounts.beginner },
            { id: "intermediate", label: "Intermediate", count: tabCounts.intermediate },
            { id: "advanced", label: "Advanced", count: tabCounts.advanced },
          ].map((tab) => (
            <button
              key={tab.id}
              onClick={() => handleFilter(tab.id)}
              className={`px-5 py-2.5 font-bold uppercase tracking-widest text-xs whitespace-nowrap transition-all ${
                activeTab === tab.id
                  ? "bg-emerald-900 text-white shadow-lg"
                  : "bg-white dark:bg-zinc-900 text-zinc-500 border border-zinc-200 dark:border-zinc-700 hover:border-emerald-600"
              }`}
            >
              {tab.label} ({tab.count})
            </button>
          ))}
        </div>

        {/* Program Grid */}
        {filteredTemplates.length === 0 ? (
          <div className="text-center py-20">
            <span className="material-symbols-outlined text-6xl text-black dark:text-white mb-4">fitness_center</span>
            <p className="text-black dark:text-white font-serif italic text-xl">No programs found for this level.</p>
          </div>
        ) : (
          <div ref={gridRef} className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
            {filteredTemplates.map((template) => {
              const isSaved = savedProgramIds.includes(template.id);
              const isActive = activeProgramId === template.id;
              const totalDays = template.days_per_week * template.total_weeks;

              return (
                <div
                  key={template.id}
                  className="program-card bg-white dark:bg-zinc-900 border-2 border-zinc-400 dark:border-zinc-500 shadow-xl hover:shadow-2xl hover:border-emerald-500 dark:hover:border-emerald-400 transition-all duration-300"
                >
                  {/* Card Body */}
                  <div className="p-5 space-y-3">
                    {/* Level Badge + Save Icon */}
                    <div className="flex justify-between items-start">
                      <span className={`text-[10px] font-bold uppercase tracking-widest px-2.5 py-1 ${LEVEL_BADGE_STYLES[template.level] || LEVEL_BADGE_STYLES.beginner}`}>
                        {LEVEL_LABELS[template.level] || template.level}
                      </span>
                      <button
                        onClick={() => handleSaveProgram(template)}
                        className={`transition-colors ${isSaved ? 'text-emerald-600' : 'text-zinc-400 hover:text-emerald-600'}`}
                      >
                        <span className="material-symbols-outlined text-xl">
                          {isSaved ? 'bookmark' : 'bookmark_border'}
                        </span>
                      </button>
                    </div>

                    {/* Program Name */}
                    <h3 className="text-xl font-bold text-emerald-900 dark:text-white leading-tight">
                      {template.name}
                    </h3>

                    {/* Description */}
                    <p className="text-black dark:text-white text-base leading-relaxed line-clamp-2">
                      {template.description}
                    </p>

                    {/* Stats Row */}
                    <div className="flex gap-4 text-sm font-bold uppercase tracking-widest text-black dark:text-white">
                      <span>{template.days_per_week}x/week</span>
                      <span>{template.total_weeks} weeks</span>
                      <span>{totalDays} days</span>
                    </div>

                    {/* Goal Tags */}
                    <div className="flex flex-wrap gap-1.5">
                      {template.goal.split(',').map((g: string) => (
                        <span key={g.trim()} className="text-[10px] uppercase tracking-widest font-bold px-2 py-0.5 bg-emerald-100 dark:bg-emerald-800 text-emerald-800 dark:text-emerald-100 border border-emerald-300 dark:border-emerald-600">
                          {g.trim()}
                        </span>
                      ))}
                    </div>
                  </div>

                  {/* Card Footer */}
                  <div className="border-t-2 border-zinc-300 dark:border-zinc-600 p-4 flex gap-2">
                    <Link
                      href={`/fitness-planner/library/${template.id}`}
                      className="flex-1 py-3 border-2 border-emerald-700 text-emerald-700 dark:text-emerald-400 dark:border-emerald-500 text-center font-bold uppercase tracking-widest text-sm hover:bg-emerald-700 hover:text-white dark:hover:bg-emerald-500 dark:hover:text-white transition-all"
                    >
                      Select Workout
                    </Link>
                    {isActive ? (
                      <div className="flex-1 py-3 bg-emerald-600 text-white text-center font-bold uppercase tracking-widest text-sm flex items-center justify-center gap-1.5">
                        <span className="material-symbols-outlined text-sm">check</span>
                        Active
                      </div>
                    ) : isSaved ? (
                      <button
                        onClick={() => handleSetActive(template)}
                        className="flex-1 py-3 bg-emerald-700 text-white text-center font-bold uppercase tracking-widest text-sm hover:bg-emerald-600 transition-all"
                      >
                        Set Active
                      </button>
                    ) : (
                      <button
                        onClick={() => handleSaveProgram(template)}
                        className="flex-1 py-3 bg-emerald-700 text-white text-center font-bold uppercase tracking-widest text-sm hover:bg-emerald-600 transition-all"
                      >
                        Save Plan
                      </button>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </main>
    </div>
  );
}
