import { Metadata } from "next"
import Link from "next/link"
import { notFound } from "next/navigation"
import { ArrowLeft } from "lucide-react"

import { Button } from "@/components/ui/button"
import WorkoutForm from "@/components/workout-form"
import { supabase } from "@/lib/supabase"

interface EditWorkoutPageProps {
  params: Promise<{
    id: string
  }>
}

async function getWorkout(id: string) {
  const { data, error } = await (supabase.from("workouts") as any)
    .select("*")
    .eq("id", id)
    .single()

  if (error || !data) {
    return null
  }

  return data
}

export async function generateMetadata({ params }: EditWorkoutPageProps): Promise<Metadata> {
  const resolvedParams = await params
  const workout = await getWorkout(resolvedParams.id)
  
  if (!workout) {
    return {
      title: "Workout Not Found | TabataFit Admin",
    }
  }

  return {
    title: `Edit ${workout.title} | TabataFit Admin`,
  }
}

export default async function EditWorkoutPage({ params }: EditWorkoutPageProps) {
  const resolvedParams = await params
  const workout = await getWorkout(resolvedParams.id)

  if (!workout) {
    notFound()
  }

  return (
    <div className="p-8 max-w-4xl mx-auto">
      <div className="mb-8">
        <Button variant="ghost" asChild className="mb-4 text-neutral-400 hover:text-white">
          <Link href={`/workouts/${workout.id}`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Workout
          </Link>
        </Button>
        
        <h1 className="text-3xl font-bold text-white mb-2">Edit Workout</h1>
        <p className="text-neutral-400">
          Update the details for "{workout.title}"
        </p>
      </div>

      <div className="rounded-lg border border-neutral-800 bg-neutral-900 p-6">
        <WorkoutForm initialData={workout} mode="edit" />
      </div>
    </div>
  )
}
