"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import { AuthGuard } from "@/components/auth/AuthGuard";
import { Navbar } from "@/components/layout/Navbar";
import { BottomNav } from "@/components/layout/BottomNav";
import { PlanCard } from "@/components/plans/PlanCard";
import { Spinner } from "@/components/ui/Spinner";
import { api } from "@/lib/api";
import type { GeneratedWeeklyPlan } from "@/lib/types";

export default function PlansPage() {
  const [plans, setPlans] = useState<GeneratedWeeklyPlan[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .getPlans()
      .then((data) => {
        const sorted = [...data].sort(
          (a, b) =>
            new Date(b.created_at).getTime() - new Date(a.created_at).getTime()
        );
        setPlans(sorted);
      })
      .catch((err) => console.error("Failed to fetch plans:", err))
      .finally(() => setLoading(false));
  }, []);

  return (
    <AuthGuard>
      <Navbar />
      <BottomNav />
      <main className="pt-20 pb-20 px-4 max-w-4xl mx-auto">
        <h1 className="text-2xl font-bold text-zinc-100 mb-6">Plans</h1>

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Spinner size="lg" />
          </div>
        ) : plans.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20 gap-4">
            <p className="text-zinc-400 text-lg text-center">
              No plans generated yet.
            </p>
            <Link
              href="/dashboard"
              className="text-[#39FF14] hover:underline text-sm font-medium"
            >
              Go to Dashboard to generate one
            </Link>
          </div>
        ) : (
          <div className="flex flex-col gap-3">
            {plans.map((plan) => (
              <PlanCard key={plan.id} plan={plan} />
            ))}
          </div>
        )}
      </main>
    </AuthGuard>
  );
}
