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

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

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

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

  // Sort tabatas by position
  if (data.program_tabatas) {
    data.program_tabatas.sort((a: any, b: any) => a.position - b.position)
  }

  return data
}

export async function generateMetadata({ params }: EditProgramPageProps): Promise<Metadata> {
  const resolvedParams = await params
  const program = await getProgram(resolvedParams.id)

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

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

export default async function EditProgramPage({ params }: EditProgramPageProps) {
  const resolvedParams = await params
  const program = await getProgram(resolvedParams.id)

  if (!program) {
    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={`/programs/${program.id}`}>
            <ArrowLeft className="mr-2 h-4 w-4" />
            Back to Program
          </Link>
        </Button>

        <h1 className="text-3xl font-bold text-white mb-2">Edit Program</h1>
        <p className="text-neutral-400">
          Update the details for &quot;{program.title}&quot;
        </p>
      </div>

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