import { Metadata } from "next"
import Link from "next/link"
import { notFound } from "next/navigation"
import { ArrowLeft, Edit, Trash2, Clock, Flame, Dumbbell, Zap, Timer, Target } from "lucide-react"

import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { supabase } from "@/lib/supabase"

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

const BODY_ZONE_COLORS: Record<string, string> = {
  "upper-body": "bg-green-500/20 text-green-500",
  "lower-body": "bg-purple-500/20 text-purple-500",
  "full-body": "bg-orange-500/20 text-orange-500",
}

const LEVEL_COLORS: Record<string, string> = {
  "Beginner": "bg-emerald-500/20 text-emerald-500",
  "Intermediate": "bg-yellow-500/20 text-yellow-500",
  "Advanced": "bg-red-500/20 text-red-500",
}

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 }: ProgramDetailPageProps): Promise<Metadata> {
  const resolvedParams = await params
  const program = await getProgram(resolvedParams.id)

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

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

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

  if (!program) {
    notFound()
  }

  const tabatas = program.program_tabatas || []

  return (
    <div className="p-8 max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-start justify-between mb-8">
        <div>
          <Button variant="ghost" asChild className="mb-4 text-neutral-400 hover:text-white">
            <Link href="/programs">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Programs
            </Link>
          </Button>

          <div className="flex items-center gap-3 mb-2">
            {program.accent_color && (
              <div
                className="h-4 w-4 rounded-full flex-shrink-0"
                style={{ backgroundColor: program.accent_color }}
              />
            )}
            <h1 className="text-3xl font-bold text-white">{program.title}</h1>
            <Badge className={program.is_free ? "bg-emerald-500/20 text-emerald-500" : "bg-amber-500/20 text-amber-500"}>
              {program.is_free ? "Free" : "Premium"}
            </Badge>
          </div>

          <div className="flex items-center gap-2 text-neutral-400">
            <Badge className={BODY_ZONE_COLORS[program.body_zone] || "bg-neutral-500/20 text-neutral-500"}>
              {program.body_zone}
            </Badge>
            <span className="text-neutral-600">|</span>
            <Badge className={LEVEL_COLORS[program.level] || "bg-neutral-500/20 text-neutral-500"}>
              {program.level}
            </Badge>
          </div>

          {program.description && (
            <p className="text-neutral-400 mt-3 max-w-2xl">{program.description}</p>
          )}
        </div>

        <div className="flex gap-2">
          <Button variant="outline" asChild className="border-neutral-700">
            <Link href={`/programs/${program.id}/edit`}>
              <Edit className="mr-2 h-4 w-4" />
              Edit
            </Link>
          </Button>
        </div>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
        <Card className="bg-neutral-900 border-neutral-800">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-neutral-400 mb-2">
              <Clock className="h-4 w-4" />
              <span className="text-sm">Duration</span>
            </div>
            <p className="text-2xl font-bold text-white">{program.estimated_duration} min</p>
            <p className="text-xs text-neutral-500">estimated total</p>
          </CardContent>
        </Card>

        <Card className="bg-neutral-900 border-neutral-800">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-neutral-400 mb-2">
              <Flame className="h-4 w-4" />
              <span className="text-sm">Calories</span>
            </div>
            <p className="text-2xl font-bold text-white">{program.estimated_calories}</p>
            <p className="text-xs text-neutral-500">estimated burn</p>
          </CardContent>
        </Card>

        <Card className="bg-neutral-900 border-neutral-800">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-neutral-400 mb-2">
              <Dumbbell className="h-4 w-4" />
              <span className="text-sm">Tabatas</span>
            </div>
            <p className="text-2xl font-bold text-white">{tabatas.length}</p>
            <p className="text-xs text-neutral-500">exercise pairs</p>
          </CardContent>
        </Card>

        <Card className="bg-neutral-900 border-neutral-800">
          <CardContent className="pt-6">
            <div className="flex items-center gap-2 text-neutral-400 mb-2">
              <Target className="h-4 w-4" />
              <span className="text-sm">Sort Order</span>
            </div>
            <p className="text-2xl font-bold text-white">{program.sort_order}</p>
            <p className="text-xs text-neutral-500">display position</p>
          </CardContent>
        </Card>
      </div>

      {/* Tabatas */}
      <div className="space-y-6">
        {tabatas.map((tabata: any) => (
          <Card key={tabata.id} className="bg-neutral-900 border-neutral-800">
            <CardHeader>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="flex h-8 w-8 items-center justify-center rounded-full bg-orange-500/20 text-orange-500 font-bold text-sm">
                    {tabata.position}
                  </div>
                  <CardTitle className="text-white">Tabata {tabata.position}</CardTitle>
                </div>
                <div className="flex items-center gap-4 text-sm text-neutral-400">
                  <span className="flex items-center gap-1">
                    <Timer className="h-3.5 w-3.5" />
                    {tabata.rounds} rounds
                  </span>
                  <span className="flex items-center gap-1">
                    <Zap className="h-3.5 w-3.5" />
                    {tabata.work_time}s work
                  </span>
                  <span className="flex items-center gap-1">
                    <Clock className="h-3.5 w-3.5" />
                    {tabata.rest_time}s rest
                  </span>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 gap-4">
                {/* Exercise 1 */}
                <div className="rounded-lg border border-neutral-800 bg-neutral-950 p-4 space-y-3">
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="bg-orange-500/20 text-orange-500">
                      Exercise 1
                    </Badge>
                  </div>
                  <div>
                    <p className="text-white font-medium">{tabata.exercise_1_name}</p>
                    {tabata.exercise_1_name_en && (
                      <p className="text-sm text-neutral-500">{tabata.exercise_1_name_en}</p>
                    )}
                  </div>
                  {tabata.exercise_1_tip && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Tip</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_1_tip}</p>
                      {tabata.exercise_1_tip_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_1_tip_en}</p>
                      )}
                    </div>
                  )}
                  {tabata.exercise_1_modification && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Modification</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_1_modification}</p>
                      {tabata.exercise_1_modification_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_1_modification_en}</p>
                      )}
                    </div>
                  )}
                  {tabata.exercise_1_progression && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Progression</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_1_progression}</p>
                      {tabata.exercise_1_progression_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_1_progression_en}</p>
                      )}
                    </div>
                  )}
                </div>

                {/* Exercise 2 */}
                <div className="rounded-lg border border-neutral-800 bg-neutral-950 p-4 space-y-3">
                  <div className="flex items-center gap-2">
                    <Badge variant="secondary" className="bg-blue-500/20 text-blue-500">
                      Exercise 2
                    </Badge>
                  </div>
                  <div>
                    <p className="text-white font-medium">{tabata.exercise_2_name}</p>
                    {tabata.exercise_2_name_en && (
                      <p className="text-sm text-neutral-500">{tabata.exercise_2_name_en}</p>
                    )}
                  </div>
                  {tabata.exercise_2_tip && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Tip</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_2_tip}</p>
                      {tabata.exercise_2_tip_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_2_tip_en}</p>
                      )}
                    </div>
                  )}
                  {tabata.exercise_2_modification && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Modification</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_2_modification}</p>
                      {tabata.exercise_2_modification_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_2_modification_en}</p>
                      )}
                    </div>
                  )}
                  {tabata.exercise_2_progression && (
                    <div>
                      <p className="text-xs text-neutral-500 mb-0.5">Progression</p>
                      <p className="text-sm text-neutral-300">{tabata.exercise_2_progression}</p>
                      {tabata.exercise_2_progression_en && (
                        <p className="text-xs text-neutral-500">{tabata.exercise_2_progression_en}</p>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    </div>
  )
}
