"use client";

import { useState, useEffect } 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, Loader2 } from "lucide-react";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { updateOrderStatus } from "@/lib/actions/orders";
import { resolveSupabaseUrl } from "@/lib/utils";

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 [orders, setOrders] = useState(initialOrders);
  const [search, setSearch] = useState("");
  const [statusFilter, setStatusFilter] = useState<string>("all");
  const [updatingId, setUpdatingId] = useState<string | null>(null);

  useEffect(() => {
    setOrders(initialOrders);
  }, [initialOrders]);

  const handleStatusChange = async (orderId: string, newStatus: 'pending' | 'active' | 'completed' | 'cancelled') => {
    setUpdatingId(orderId);
    try {
      await updateOrderStatus(orderId, newStatus);
      setOrders(prev => prev.map(o => o.id === orderId ? { ...o, status: newStatus } : o));
    } catch (error) {
      console.error(error);
      alert("Fehler beim Ändern des Status.");
    } finally {
      setUpdatingId(null);
    }
  };

  const filteredOrders = orders.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>
                      <DropdownMenu>
                        <DropdownMenuTrigger asChild disabled={updatingId === order.id}>
                          <button className="focus:outline-none focus:ring-0 active:scale-95 disabled:pointer-events-none transition-transform duration-100">
                            <Badge className={`text-xs px-2 py-0.5 rounded cursor-pointer transition-all duration-200 hover:opacity-85 flex items-center gap-1.5 ${statusClass[order.status] ?? 'bg-slate-500/20 text-slate-300'}`}>
                              {updatingId === order.id ? (
                                <Loader2 className="w-3 h-3 animate-spin mr-1" />
                              ) : null}
                              {statusLabel[order.status] ?? order.status}
                              <span className="text-[9px] opacity-70">▼</span>
                            </Badge>
                          </button>
                        </DropdownMenuTrigger>
                        <DropdownMenuContent align="start" className="bg-slate-900 border-white/10 text-white min-w-[140px]">
                          {Object.entries(statusLabel).map(([key, label]) => (
                            <DropdownMenuItem
                              key={key}
                              disabled={updatingId === order.id}
                              onClick={() => handleStatusChange(order.id, key as any)}
                              className={`text-xs cursor-pointer hover:bg-white/10 transition-colors focus:bg-white/10 focus:text-white ${order.status === key ? 'font-bold text-primary' : ''}`}
                            >
                              {label}
                            </DropdownMenuItem>
                          ))}
                        </DropdownMenuContent>
                      </DropdownMenu>
                    </TableCell>
                    <TableCell className="text-right">
                      <div className="flex justify-end gap-1.5">
                        <Button variant="outline" size="sm" asChild className="h-8 border-amber-500/20 hover:bg-amber-500/10 text-amber-400 text-xs">
                          <a href={`/order?id=${order.id}`}>
                            Bearbeiten
                          </a>
                        </Button>
                        {order.pdf_url ? (
                          <>
                            <Button variant="outline" size="sm" asChild className="h-8 border-white/10 hover:bg-primary/20 text-xs">
                              <a href={resolveSupabaseUrl(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={`/api/admin/orders/${order.id}/download`}>
                                <Download className="w-3.5 h-3.5" />
                              </a>
                            </Button>
                          </>
                        ) : (
                          <span className="text-xs text-slate-500 italic self-center px-2">Keine Bestätigung</span>
                        )}
                      </div>
                    </TableCell>
                  </TableRow>
                );
              })
            )}
          </TableBody>
        </Table>
      </div>
    </div>
  );
}
