"use client";

import { useState, useEffect } from "react";
import Link from "next/link";
import WorkoutNav from "@/components/WorkoutNav";

interface UserProgram {
  id: string;
  template_id: string | null;
  name: string;
  description: string;
  is_active: number;
  is_custom: number;
  source: string;
  current_week: number;
  current_day: number;
  completed_at: string | null;
  created_at: string;
  updated_at: string;
}

export default function MyPlansPage() {
  const [programs, setPrograms] = useState<UserProgram[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [userEmail, setUserEmail] = useState<string | null>(null);

  useEffect(() => {
    document.title = "My Plans | Marich Wellness";
    fetchUserAndPrograms();
  }, []);

  async function fetchUserAndPrograms() {
    try {
      const profileRes = await fetch('/api/user/profile');
      if (!profileRes.ok) {
        setError('Please complete the fitness questionnaire first.');
        setIsLoading(false);
        return;
      }
      const profileData = await profileRes.json();
      const email = profileData?.profile?.user_email;
      if (!email) {
        setError('Please complete the fitness questionnaire first.');
        setIsLoading(false);
        return;
      }
      setUserEmail(email);

      const programsRes = await fetch(`/api/fitness/programs?userId=${encodeURIComponent(email)}`);
      if (!programsRes.ok) throw new Error('Failed to fetch programs');
      const programsData = await programsRes.json();
      setPrograms(programsData.programs || []);
    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsLoading(false);
    }
  }

  async function handleSetActive(programId: string) {
    try {
      const res = await fetch(`/api/fitness/programs/${programId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ is_active: true }),
      });
      if (res.ok) {
        setPrograms(prev => prev.map(p => ({
          ...p,
          is_active: p.id === programId ? 1 : 0,
        })));
      }
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  async function handleDelete(programId: string) {
    if (!confirm('Delete this program? This cannot be undone.')) return;
    try {
      const res = await fetch(`/api/fitness/programs/${programId}`, {
        method: 'DELETE',
      });
      if (res.ok) {
        setPrograms(prev => prev.filter(p => p.id !== programId));
      }
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  async function handleComplete(programId: string) {
    try {
      const res = await fetch(`/api/fitness/programs/${programId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ completed: true }),
      });
      if (res.ok) {
        setPrograms(prev => prev.map(p => 
          p.id === programId ? { ...p, completed_at: new Date().toISOString(), is_active: 0 } : p
        ));
      }
    } catch (err: any) {
      alert('Error: ' + err.message);
    }
  }

  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 Plans...</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">{error}</p>
          <Link href="/fitness-planner" className="px-6 py-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs inline-block">
            Back to Fitness Planner
          </Link>
        </div>
      </div>
    );
  }

  // All non-completed programs stay in the grid in their original order
  // The active one is visually highlighted with a green border and badge
  const savedPrograms = programs.filter(p => !p.completed_at);
  const completedPrograms = programs.filter(p => p.completed_at);

  return (
    <div className="min-h-screen bg-surface-container-lowest dark:bg-zinc-950">
      <WorkoutNav currentPage="my-plans" />

      <main className="max-w-7xl mx-auto px-6 pb-32">
        {/* Page Header */}
        <div className="mb-12 space-y-4">
          <h1 className="text-5xl md:text-7xl font-serif text-emerald-900 dark:text-emerald-50 italic tracking-tight leading-none">
            My Plans
          </h1>
          <p className="text-5xl md:text-6xl text-black dark:text-white font-serif italic">
            Manage your saved and active workout programs
          </p>
          <div className="flex items-center gap-2 text-black dark:text-white">
            <span className="material-symbols-outlined text-3xl text-black dark:text-white">bookmark</span>
            <span className="text-lg font-bold uppercase tracking-widest text-black dark:text-white">{programs.length} plans</span>
          </div>
        </div>

        {/* All Programs Grid — active program stays in place, just highlighted */}
        <section className="mb-16">
          <h2 className="text-lg font-bold uppercase tracking-widest text-black dark:text-white mb-6">
            Saved Programs ({savedPrograms.length})
          </h2>
          {savedPrograms.length === 0 ? (
            <div className="text-center py-12 bg-white dark:bg-zinc-900 border-2 border-zinc-200 dark:border-zinc-700">
              <span className="material-symbols-outlined text-4xl text-black dark:text-white mb-4">bookmark_border</span>
              <p className="text-black dark:text-white font-serif italic mb-4">No saved programs yet.</p>
              <Link
                href="/fitness-planner/library"
                className="px-6 py-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-xs inline-block hover:bg-emerald-800 transition-all"
              >
                Browse Programs
              </Link>
            </div>
          ) : (
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {savedPrograms.map((program) => (
                <div
                  key={program.id}
                  className={`plan-card bg-white dark:bg-zinc-900 border-2 transition-all duration-500 ${
                    program.is_active
                      ? 'border-emerald-600 shadow-lg ring-2 ring-emerald-600/20'
                      : 'border-zinc-200 dark:border-zinc-700 hover:shadow-xl hover:border-emerald-300 dark:hover:border-emerald-700'
                  }`}
                >
                  <div className="p-6 space-y-4">
                    <div className="flex items-center justify-between">
                      <h3 className="font-bold text-emerald-900 dark:text-emerald-50 text-[22px]">
                        {program.name}
                      </h3>
                      {program.is_active && (
                        <span className="flex items-center gap-1 text-[10px] font-bold uppercase tracking-widest text-emerald-600 bg-emerald-50 dark:bg-emerald-900/30 px-2 py-1 rounded">
                          <span className="w-1.5 h-1.5 rounded-full bg-emerald-600 animate-pulse"></span>
                          Active
                        </span>
                      )}
                    </div>
                    {program.description && (
                      <p className="text-3xl text-black dark:text-white leading-relaxed line-clamp-2">
                        {program.description}
                      </p>
                    )}
                    <div className="flex gap-4 text-sm text-black dark:text-white font-bold uppercase tracking-widest">
                      <span>Week {program.current_week}</span>
                      <span>Day {program.current_day}</span>
                    </div>
                    <div className="flex gap-2 pt-2 border-t-2 border-zinc-200 dark:border-zinc-700">
                      <Link
                        href={`/fitness-planner/program/${program.id}`}
                        className="flex-1 py-3 bg-emerald-900 text-white font-bold uppercase tracking-widest text-sm text-center hover:bg-emerald-800 transition-all"
                      >
                        View Structure
                      </Link>
                      <button
                        onClick={() => handleSetActive(program.id)}
                        className={`px-4 py-3 font-bold uppercase tracking-widest text-sm transition-all ${
                          program.is_active
                            ? 'bg-emerald-100 text-emerald-600 cursor-default'
                            : 'border-2 border-zinc-300 dark:border-zinc-600 text-black dark:text-white hover:bg-zinc-50 dark:hover:bg-zinc-800'
                        }`}
                        disabled={program.is_active === 1}
                      >
                        {program.is_active ? 'Active' : 'Set Active'}
                      </button>
                      <button
                        onClick={() => handleDelete(program.id)}
                        className="px-4 py-3 border-2 border-zinc-300 dark:border-zinc-600 text-black dark:text-white font-bold uppercase tracking-widest text-sm hover:border-red-400 hover:text-red-500 transition-all"
                      >
                        <span className="material-symbols-outlined text-lg">delete</span>
                      </button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </section>

        {/* Completed Programs */}
        {completedPrograms.length > 0 && (
          <section>
            <h2 className="text-xs font-bold uppercase tracking-widest text-black dark:text-white mb-6">
              Completed ({completedPrograms.length})
            </h2>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
              {completedPrograms.map((program) => (
                <div
                  key={program.id}
                  className="plan-card bg-zinc-50 dark:bg-zinc-800/50 border-2 border-zinc-300 dark:border-zinc-600"
                >
                  <div className="p-6 space-y-2">
                    <div className="flex items-center gap-2">
                      <span className="material-symbols-outlined text-emerald-600 text-sm">check_circle</span>
                      <h3 className="font-bold text-black dark:text-white line-through">
                        {program.name}
                      </h3>
                    </div>
                    {program.completed_at && (
                      <p className="text-xs text-black dark:text-white">
                        Completed {new Date(program.completed_at).toLocaleDateString()}
                      </p>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </section>
        )}
      </main>
    </div>
  );
}
