"use client";

import { useState } from "react";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Download, ExternalLink, Search } from "lucide-react";

interface OrdersTableProps {
  initialOrders: any[];
}

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

const statusClass: Record<string, string> = {
  pending: 'bg-amber-500/20 text-amber-400 border border-amber-500/30',
  active: 'bg-blue-500/20 text-blue-400 border border-blue-500/30',
  completed: 'bg-green-500/20 text-green-400 border border-green-500/30',
  cancelled: 'bg-red-500/20 text-red-400 border border-red-500/30',
};

export function OrdersTable({ initialOrders }: OrdersTableProps) {
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");

  const filteredOrders = initialOrders.filter((order) => {
    const orderNum = (order.order_number || "").toLowerCase();
    const company = (order.customer_data?.company_name || "").toLowerCase();
    const contact = `${order.customer_data?.first_name || ""} ${order.customer_data?.last_name || ""}`.toLowerCase();
    
    const matchesSearch = 
      orderNum.includes(search.toLowerCase()) ||
      company.includes(search.toLowerCase()) ||
      contact.includes(search.toLowerCase());

    const matchesStatus = statusFilter === "all" || order.status === statusFilter;

    return matchesSearch && matchesStatus;
  });

  return (
    <div className="space-y-4">
      {/* Filterleiste */}
      <div className="flex flex-col md:flex-row gap-4 justify-between items-start md:items-center bg-white/5 p-4 rounded-xl border border-white/5">
        <div className="relative w-full md:max-w-sm">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400" />
          <Input
            placeholder="Bestellung, Firma oder Name suchen..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="pl-10 bg-slate-950/40 border-white/10 text-white placeholder:text-slate-500"
          />
        </div>

        <div className="flex flex-wrap gap-2">
          <Button
            variant={statusFilter === "all" ? "default" : "outline"}
            size="sm"
            onClick={() => setStatusFilter("all")}
            className="text-xs"
          >
            Alle
          </Button>
          <Button
            variant={statusFilter === "pending" ? "default" : "outline"}
            size="sm"
            onClick={() => setStatusFilter("pending")}
            className="text-xs border-amber-500/20 hover:bg-amber-500/10 text-amber-400"
          >
            Eingegangen
          </Button>
          <Button
            variant={statusFilter === "active" ? "default" : "outline"}
            size="sm"
            onClick={() => setStatusFilter("active")}
            className="text-xs border-blue-500/20 hover:bg-blue-500/10 text-blue-400"
          >
            In Bearbeitung
          </Button>
          <Button
            variant={statusFilter === "completed" ? "default" : "outline"}
            size="sm"
            onClick={() => setStatusFilter("completed")}
            className="text-xs border-green-500/20 hover:bg-green-500/10 text-green-400"
          >
            Abgeschlossen
          </Button>
          <Button
            variant={statusFilter === "cancelled" ? "default" : "outline"}
            size="sm"
            onClick={() => setStatusFilter("cancelled")}
            className="text-xs border-red-500/20 hover:bg-red-500/10 text-red-400"
          >
            Storniert
          </Button>
        </div>
      </div>

      {/* Tabelle */}
      <div className="rounded-xl border border-white/5 bg-black/20 overflow-hidden backdrop-blur-xl">
        <Table>
          <TableHeader>
            <TableRow className="border-white/10 bg-white/5 hover:bg-transparent">
              <TableHead className="w-[140px] text-slate-200">Bestellnr.</TableHead>
              <TableHead className="text-slate-200">Datum</TableHead>
              <TableHead className="text-slate-200">Kunde</TableHead>
              <TableHead className="text-slate-200">Auswahl</TableHead>
              <TableHead className="text-slate-200">Betrag</TableHead>
              <TableHead className="text-slate-200">Status</TableHead>
              <TableHead className="text-right text-slate-200">Aktionen</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {filteredOrders.length === 0 ? (
              <TableRow>
                <TableCell colSpan={7} className="text-center py-16 text-slate-500 italic">
                  Keine Bestellungen gefunden.
                </TableCell>
              </TableRow>
            ) : (
              filteredOrders.map((order) => {
                const items = order.order_data?.items || [];
                return (
                  <TableRow key={order.id} className="border-white/5 hover:bg-white/5 transition-colors">
                    <TableCell className="font-mono text-xs text-primary font-semibold">
                      #{order.order_number || order.id.slice(0, 8)}
                    </TableCell>
                    <TableCell className="text-slate-300 text-sm">
                      {new Date(order.created_at).toLocaleDateString('de-DE', {
                        day: '2-digit', month: '2-digit', year: 'numeric'
                      })}
                    </TableCell>
                    <TableCell>
                      <div className="font-semibold text-white text-sm">
                        {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="max-w-[200px]">
                      <div className="flex flex-wrap gap-1">
                        {items.map((item: any) => (
                          <span
                            key={item.product_id}
                            className="text-[10px] bg-white/5 border border-white/10 rounded-full px-2 py-0.5 text-slate-300 inline-block"
                          >
                            {item.product_name}
                            {item.selected_modules?.length > 0 && (
                              <span className="text-slate-500 ml-1">+{item.selected_modules.length}</span>
                            )}
                          </span>
                        ))}
                      </div>
                    </TableCell>
                    <TableCell className="font-bold text-white text-sm">
                      {new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(order.total_price)}
                    </TableCell>
                    <TableCell>
                      <Badge className={`text-xs px-2 py-0.5 rounded ${statusClass[order.status] ?? 'bg-slate-500/20 text-slate-300'}`}>
                        {statusLabel[order.status] ?? order.status}
                      </Badge>
                    </TableCell>
                    <TableCell className="text-right">
                      {order.pdf_url ? (
                        <div className="flex justify-end gap-1.5">
                          <Button variant="outline" size="sm" asChild className="h-8 border-white/10 hover:bg-primary/20 text-xs">
                            <a href={order.pdf_url} target="_blank" rel="noopener noreferrer">
                              <ExternalLink className="w-3.5 h-3.5 mr-1" /> PDF
                            </a>
                          </Button>
                          <Button variant="secondary" size="sm" asChild className="h-8 text-xs">
                            <a href={order.pdf_url} download>
                              <Download className="w-3.5 h-3.5" />
                            </a>
                          </Button>
                        </div>
                      ) : (
                        <span className="text-xs text-slate-500 italic">Keine Rechnung</span>
                      )}
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
