import { createClient } from '@/lib/supabase/server'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { FileText, Download, ExternalLink } from 'lucide-react'
import Link from 'next/link'

import { Suspense } from 'react'

export default async function AdminOrdersPage() {
  return (
    <div className="space-y-6">
      <div className="flex justify-between items-center">
        <div>
          <h1 className="text-3xl font-bold tracking-tight text-white">Bestellungen & Rechnungen</h1>
          <p className="text-slate-400">Verwalten Sie alle Kundenbestellungen und greifen Sie auf generierte PDFs zu.</p>
        </div>
      </div>

      <Suspense fallback={<div className="h-40 w-full animate-pulse bg-white/5 rounded-xl" />}>
        <OrdersData />
      </Suspense>
    </div>
  )
}

async function OrdersData() {
  const supabase = await createClient()
  
  const { data: orders, error } = await supabase
    .from('orders')
    .select('*')
    .order('created_at', { ascending: false })

  if (error) {
    return <div>Fehler beim Laden der Bestellungen: {error.message}</div>
  }

  return (
    <Card className="glass-dark border-white/10">
      <CardContent className="p-0">
        <Table>
          <TableHeader>
            <TableRow className="border-white/10 hover:bg-transparent">
              <TableHead className="w-[100px] text-slate-200">ID</TableHead>
              <TableHead className="text-slate-200">Datum</TableHead>
              <TableHead className="text-slate-200">Kunde</TableHead>
              <TableHead className="text-slate-200">Betrag</TableHead>
              <TableHead className="text-slate-200">Status</TableHead>
              <TableHead className="text-right text-slate-200">Rechnung</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {orders?.length === 0 ? (
              <TableRow>
                <TableCell colSpan={6} className="text-center py-12 text-muted-foreground">
                  Noch keine Bestellungen vorhanden.
                </TableCell>
              </TableRow>
            ) : (
              orders?.map((order) => (
                <TableRow key={order.id} className="border-white/5 hover:bg-white/5">
                  <TableCell className="font-mono text-xs text-slate-500">
                    {order.id.slice(0, 8)}...
                  </TableCell>
                  <TableCell className="text-slate-300">
                    {new Date(order.created_at).toLocaleDateString('de-DE')}
                  </TableCell>
                  <TableCell>
                    <div className="font-medium text-white">{order.customer_data?.company_name || 'Privatkunde'}</div>
                    <div className="text-xs text-slate-400">{order.customer_data?.first_name} {order.customer_data?.last_name}</div>
                  </TableCell>
                  <TableCell className="font-semibold text-white">
                    {new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(order.total_price)}
                  </TableCell>
                  <TableCell>
                    <Badge variant={order.status === 'completed' ? 'default' : 'secondary'} className="capitalize">
                      {order.status}
                    </Badge>
                  </TableCell>
                  <TableCell className="text-right">
                    {order.pdf_url ? (
                      <div className="flex justify-end gap-2">
                        <Button variant="outline" size="sm" asChild className="h-8 border-white/10 hover:bg-primary/20">
                          <a href={order.pdf_url} target="_blank" rel="noopener noreferrer">
                            <ExternalLink className="w-4 h-4 mr-2" /> Ansehen
                          </a>
                        </Button>
                        <Button variant="secondary" size="sm" asChild className="h-8">
                          <a href={order.pdf_url} download>
                            <Download className="w-4 h-4" />
                          </a>
                        </Button>
                      </div>
                    ) : (
                      <span className="text-xs text-muted-foreground italic">Kein PDF</span>
                    )}
                  </TableCell>
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </CardContent>
    </Card>
  )
}
