"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 { SupersetCard } from "@/components/workout/SupersetCard";
import { Spinner } from "@/components/ui/Spinner";
import { api } from "@/lib/api";
import type { WorkoutDetail } from "@/lib/types";

function formatTime(seconds: number | null): string {
  if (!seconds) return "N/A";
  const mins = Math.round(seconds / 60);
  if (mins >= 60) {
    const h = Math.floor(mins / 60);
    const m = mins % 60;
    return m > 0 ? `${h}h ${m}m` : `${h}h`;
  }
  return `${mins}m`;
}

export default function WorkoutDetailPage({
  params,
}: {
  params: { workoutId: string };
}) {
  const { workoutId } = params;
  const [workout, setWorkout] = useState<WorkoutDetail | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api
      .getWorkoutDetail(Number(workoutId))
      .then(setWorkout)
      .catch((err) => console.error("Failed to fetch workout:", err))
      .finally(() => setLoading(false));
  }, [workoutId]);

  return (
    <AuthGuard>
      <Navbar />
      <BottomNav />
      <main className="pt-20 pb-20 px-4 max-w-4xl mx-auto">
        <Link
          href="/dashboard"
          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
        </Link>

        {loading ? (
          <div className="flex items-center justify-center py-20">
            <Spinner size="lg" />
          </div>
        ) : !workout ? (
          <div className="text-center py-20">
            <p className="text-zinc-400">Workout not found.</p>
          </div>
        ) : (
          <div>
            <div className="mb-6">
              <h1 className="text-2xl font-bold text-zinc-100 mb-2">
                {workout.name}
              </h1>
              {workout.description && (
                <p className="text-sm text-zinc-400 mb-3">
                  {workout.description}
                </p>
              )}
              <div className="flex items-center gap-4 text-sm text-zinc-400">
                <span className="flex items-center gap-1.5">
                  <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"
                  >
                    <circle cx="12" cy="12" r="10" />
                    <polyline points="12 6 12 12 16 14" />
                  </svg>
                  {formatTime(workout.estimated_time)}
                </span>
                <span>
                  {workout.supersets.length} superset
                  {workout.supersets.length !== 1 ? "s" : ""}
                </span>
              </div>
            </div>

            <div className="flex flex-col gap-4">
              {[...workout.supersets]
                .sort((a, b) => a.order - b.order)
                .map((superset, i) => (
                  <SupersetCard
                    key={superset.id}
                    superset={superset}
                    defaultOpen={i === 0}
                  />
                ))}
            </div>
          </div>
        )}
      </main>
    </AuthGuard>
  );
}
