"use client";

import { useEffect, useState, useCallback } 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 { WeeklyPlanGrid } from "@/components/plans/WeeklyPlanGrid";
import { Badge } from "@/components/ui/Badge";
import { Button } from "@/components/ui/Button";
import { Spinner } from "@/components/ui/Spinner";
import { api } from "@/lib/api";
import type { GeneratedWeeklyPlan } from "@/lib/types";

function formatDate(dateStr: string): string {
  const date = new Date(dateStr + "T00:00:00");
  return date.toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

function getStatusVariant(
  status: string
): "success" | "warning" | "error" | "default" {
  switch (status) {
    case "completed":
      return "success";
    case "pending":
      return "warning";
    case "failed":
      return "error";
    default:
      return "default";
  }
}

export default function PlanDetailPage({
  params,
}: {
  params: { planId: string };
}) {
  const { planId } = params;
  const [plan, setPlan] = useState<GeneratedWeeklyPlan | null>(null);
  const [loading, setLoading] = useState(true);

  const fetchPlan = useCallback(async () => {
    try {
      const data = await api.getPlan(Number(planId));
      setPlan(data);
    } catch (err) {
      console.error("Failed to fetch plan:", err);
    } finally {
      setLoading(false);
    }
  }, [planId]);

  useEffect(() => {
    fetchPlan();
  }, [fetchPlan]);

  return (
    <AuthGuard>
      <Navbar />
      <BottomNav />
      <main className="pt-20 pb-20 px-4 max-w-5xl mx-auto">
        <Link
          href="/plans"
          className="inline-flex items-center gap-1 text-sm text-zinc-400 hover:text-zinc-100 transition-colors mb-4"
        >
          <svg
            xmlns="http://www.w3.org/2000/svg"
            width="16"
            height="16"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            strokeLinecap="round"
            strokeLinejoin="round"
          >
            <polyline points="15 18 9 12 15 6" />
          </svg>
          Back to Plans
        </Link>

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Spinner size="lg" />
          </div>
        ) : !plan ? (
          <div className="text-center py-20">
            <p className="text-zinc-400">Plan not found.</p>
          </div>
        ) : (
          <div>
            <div className="flex items-center justify-between mb-6">
              <div>
                <h1 className="text-2xl font-bold text-zinc-100 mb-1">
                  {formatDate(plan.week_start_date)} &ndash;{" "}
                  {formatDate(plan.week_end_date)}
                </h1>
                <Badge variant={getStatusVariant(plan.status)}>
                  {plan.status}
                </Badge>
              </div>
              <Button variant="secondary" size="sm" onClick={fetchPlan}>
                Refresh
              </Button>
            </div>

            <WeeklyPlanGrid plan={plan} onUpdate={fetchPlan} />
          </div>
        )}
      </main>
    </AuthGuard>
  );
}
