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 TrainerForm from "@/components/trainer-form"
import { supabase } from "@/lib/supabase"

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

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

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

  return data
}

export async function generateMetadata({ params }: EditTrainerPageProps): Promise<Metadata> {
  const resolvedParams = await params
  const trainer = await getTrainer(resolvedParams.id)

  if (!trainer) {
    return {
      title: "Trainer Not Found | TabataFit Admin",
    }
  }

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

export default async function EditTrainerPage({ params }: EditTrainerPageProps) {
  const resolvedParams = await params
  const trainer = await getTrainer(resolvedParams.id)

  if (!trainer) {
    notFound()
  }

  return (
    <div className="p-8 max-w-2xl">
      <Button variant="ghost" asChild className="mb-4 text-neutral-400 hover:text-white">
        <Link href="/trainers">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Trainers
        </Link>
      </Button>

      <h1 className="text-2xl font-bold text-white mb-6">Edit Trainer</h1>

      <TrainerForm initialData={trainer} mode="edit" />
    </div>
  )
}
