import { createClient } from '@/lib/supabase/server'
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { CheckCircle2, Download, ExternalLink, ShoppingBag, ArrowRight } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Separator } from '@/components/ui/separator'
import { Badge } from '@/components/ui/badge'
import type { Order } from '@/lib/types'

export default async function OrderSuccessPage({
  searchParams,
}: {
  searchParams: Promise<{ id?: string }>
}) {
  const { id } = await searchParams
  if (!id) redirect('/')

  const supabase = await createClient()

  // Authentifizierung prüfen
  const { data: { user } } = await supabase.auth.getUser()
  if (!user) redirect('/auth/login')

  // Bestellung laden und prüfen ob sie dem eingeloggten User gehört
  const { data: order, error } = await supabase
    .from('orders')
    .select('*')
    .eq('id', id)
    .eq('user_id', user.id)
    .single()

  if (error || !order) redirect('/')

  const o = order as Order
  const items = o.order_data?.items ?? []

  const statusLabel: Record<string, string> = {
    pending: 'Eingegangen',
    active: 'In Bearbeitung',
    cancelled: 'Storniert',
  }

  return (
    <div className="min-h-screen bg-[#020617] text-white flex items-center justify-center px-4 py-16">
      <div className="w-full max-w-2xl space-y-6">
        {/* Erfolgsmeldung */}
        <div className="text-center space-y-4">
          <div className="w-24 h-24 bg-green-500/10 rounded-full flex items-center justify-center mx-auto border border-green-500/30 animate-pulse">
            <CheckCircle2 className="w-12 h-12 text-green-400" />
          </div>
          <h1 className="text-4xl font-extrabold tracking-tight text-white">
            Bestellung eingegangen!
          </h1>
          <p className="text-slate-400 text-lg">
            Ihre Bestellung wurde erfolgreich gespeichert.
          </p>
          <div className="inline-flex items-center gap-2 bg-white/5 border border-white/10 rounded-full px-5 py-2 font-mono text-lg font-bold text-primary">
            #{o.order_number}
          </div>
        </div>

        {/* Bestell-Details */}
        <Card className="glass-dark border-white/10">
          <CardHeader className="flex flex-row items-center justify-between">
            <CardTitle className="text-white">Bestellübersicht</CardTitle>
            <Badge
              className={
                o.status === 'active'
                  ? 'bg-green-500/20 text-green-400 border-green-500/30'
                  : o.status === 'cancelled'
                  ? 'bg-red-500/20 text-red-400 border-red-500/30'
                  : 'bg-amber-500/20 text-amber-400 border-amber-500/30'
              }
            >
              {statusLabel[o.status] ?? o.status}
            </Badge>
          </CardHeader>
          <CardContent className="space-y-4">
            {/* Produkte */}
            <div className="space-y-3">
              {items.map((item) => (
                <div key={item.product_id} className="space-y-1">
                  <div className="flex justify-between text-sm">
                    <span className="font-semibold text-white">{item.product_name}</span>
                    <span className="text-white">
                      {new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(item.base_price)}
                      <span className="text-slate-400 text-xs ml-1">
                        {item.billing_interval === 'one_time' ? 'einmalig' : '/ Monat'}
                      </span>
                    </span>
                  </div>
                  {item.selected_modules.map((mod) => (
                    <div key={mod.module_id} className="flex justify-between text-xs pl-4 text-slate-400">
                      <span>+ {mod.module_name}</span>
                      <span>{new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(mod.price)}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>

            <Separator className="bg-white/10" />

            {/* Gesamtbetrag */}
            <div className="flex justify-between text-lg font-bold">
              <span className="text-slate-300">Gesamtbetrag</span>
              <span className="text-gradient">
                {new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(o.total_price)}
              </span>
            </div>

            <Separator className="bg-white/10" />

            {/* Kundendaten */}
            <div className="text-sm text-slate-400 space-y-1">
              <p className="font-semibold text-white">{o.customer_data?.company_name}</p>
              <p>{o.customer_data?.first_name} {o.customer_data?.last_name}</p>
              <p>{o.customer_data?.address}, {o.customer_data?.zip_code} {o.customer_data?.city}</p>
            </div>

            {/* PDF-Download */}
            {o.pdf_url && (
              <div className="flex gap-2 pt-2">
                <Button variant="outline" size="sm" asChild className="border-white/10 hover:bg-white/10">
                  <a href={o.pdf_url} target="_blank" rel="noopener noreferrer">
                    <ExternalLink className="w-4 h-4 mr-2" /> Rechnung ansehen
                  </a>
                </Button>
                <Button variant="secondary" size="sm" asChild>
                  <a href={o.pdf_url} download>
                    <Download className="w-4 h-4 mr-2" /> Herunterladen
                  </a>
                </Button>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Aktions-Buttons */}
        <div className="flex gap-3">
          <Link href="/my-orders" className="flex-1">
            <Button variant="outline" className="w-full border-white/10 hover:bg-white/5">
              <ShoppingBag className="w-4 h-4 mr-2" />
              Meine Bestellungen
            </Button>
          </Link>
          <Link href="/" className="flex-1">
            <Button className="w-full">
              Zurück zur Startseite <ArrowRight className="w-4 h-4 ml-2" />
            </Button>
          </Link>
        </div>
      </div>
    </div>
  )
}
