"use client";

import React from "react";
import {
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  ResponsiveContainer,
  BarChart,
  Bar,
} from "recharts";
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from "@/components/ui/card";
import { formatCurrency } from "@/lib/format";
import { 
  ShoppingBag, 
  Package, 
  ChevronRight,
  ArrowUpRight,
  ArrowDownRight
} from "lucide-react";
import Link from "next/link";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { PaymentStatusBadge } from "@/components/dashboard/PaymentStatusBadge";
import { CopyButton } from "@/components/ui/CopyButton";

interface DashboardOverviewClientProps {
  salesData: any[];
  topProducts: any[];
  recentOrders: any[];
  lowStockItems: any[];
}

export default function DashboardOverviewClient({ 
  salesData, 
  topProducts, 
  recentOrders,
  lowStockItems 
}: DashboardOverviewClientProps) {
  return (
    <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-7">
      {/* Revenue Trend */}
      <Card className="lg:col-span-4 shadow-sm border-border/40">
        <CardHeader className="flex flex-row items-center justify-between">
          <div className="space-y-1">
            <CardTitle className="text-base font-semibold">Umsatz-Trend</CardTitle>
            <CardDescription className="text-xs">Täglicher Umsatz der letzten 7 Tage</CardDescription>
          </div>
          <Badge variant="outline" className="text-xs uppercase font-bold tracking-normal gap-1 text-emerald-500 border-emerald-500/20 bg-emerald-500/5">
            <ArrowUpRight className="size-3" aria-hidden="true" /> 12%
          </Badge>
        </CardHeader>
        <CardContent>
          <div className="h-[300px] w-full mt-2">
            <ResponsiveContainer width="100%" height="100%">
              <LineChart data={salesData}>
                <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--muted))" opacity={0.3} />
                <XAxis 
                  dataKey="name" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))", fontWeight: 600 }}
                  dy={10}
                />
                <YAxis 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))", fontWeight: 600 }}
                  tickFormatter={(value) => `€${value}`}
                />
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: "hsl(var(--background))", 
                    borderRadius: "8px", 
                    border: "1px solid hsl(var(--border))", 
                    boxShadow: "0 4px 12px rgba(0,0,0,0.1)",
                    fontSize: "12px",
                    fontWeight: 600
                  }}
                  formatter={(value: any) => [formatCurrency(value), "Umsatz"]}
                />
                <Line 
                  type="monotone" 
                  dataKey="total" 
                  stroke="hsl(var(--primary))" 
                  strokeWidth={3} 
                  dot={{ r: 4, fill: "hsl(var(--primary))", strokeWidth: 2, stroke: "hsl(var(--background))" }} 
                  activeDot={{ r: 6, strokeWidth: 0 }}
                />
              </LineChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Top Products */}
      <Card className="lg:col-span-3 shadow-sm border-border/40">
        <CardHeader>
          <CardTitle className="text-base font-semibold">Bestseller</CardTitle>
          <CardDescription className="text-xs">Top Produkte nach verkauften Einheiten</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="h-[300px] w-full mt-2">
            <ResponsiveContainer width="100%" height="100%">
              <BarChart data={topProducts} layout="vertical" margin={{ left: -20 }}>
                <CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="hsl(var(--muted))" opacity={0.3} />
                <XAxis 
                  type="number" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))", fontWeight: 600 }}
                />
                <YAxis 
                  dataKey="name" 
                  type="category" 
                  axisLine={false} 
                  tickLine={false} 
                  tick={{ fontSize: 12, fill: "hsl(var(--muted-foreground))", fontWeight: 600 }}
                  width={100}
                />
                <Tooltip 
                  contentStyle={{ 
                    backgroundColor: "hsl(var(--background))", 
                    borderRadius: "8px", 
                    border: "1px solid hsl(var(--border))",
                    fontSize: "12px",
                    fontWeight: 600
                  }}
                  cursor={{ fill: "hsl(var(--muted))", opacity: 0.1 }}
                />
                <Bar dataKey="sales" fill="hsl(var(--primary))" radius={[0, 4, 4, 0]} barSize={16} />
              </BarChart>
            </ResponsiveContainer>
          </div>
        </CardContent>
      </Card>

      {/* Recent Orders */}
      <Card className="lg:col-span-4 shadow-sm border-border/40">
        <CardHeader className="flex flex-row items-center justify-between">
          <div className="space-y-1">
            <CardTitle className="text-base font-semibold">Letzte Bestellungen</CardTitle>
            <CardDescription className="text-xs">Echtzeit-Übersicht der Transaktionen</CardDescription>
          </div>
          <Link href="/dashboard/orders/overview">
            <Badge variant="secondary" className="text-xs uppercase font-bold tracking-normal cursor-pointer hover:bg-muted transition-colors">
              Alle ansehen
            </Badge>
          </Link>
        </CardHeader>
        <CardContent className="p-0">
          <div className="divide-y divide-border/40">
            {recentOrders.map((order) => (
              <div key={order.id} className="group flex items-center justify-between px-6 py-3.5 hover:bg-muted/30 transition-colors">
                <div className="flex items-center gap-3">
                  <div className="size-8 rounded-full bg-primary/10 flex items-center justify-center">
                    <ShoppingBag className="size-4 text-primary" aria-hidden="true" />
                  </div>
                  <div>
                    <div className="flex items-center gap-1">
                      <p className="text-sm font-bold">{order.origin_reference?.slice(0, 8) || order.id.slice(0, 8)}</p>
                      <CopyButton
                        value={order.origin_reference || order.id}
                        copyMessage="Referenz kopieren"
                        successMessage="Referenz kopiert!"
                        aria-label={`Bestell-Referenz ${order.origin_reference || order.id} kopieren`}
                        className="size-4 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity"
                      />
                    </div>
                    <p className="text-xs text-muted-foreground font-medium uppercase">{new Date(order.created_at).toLocaleDateString()}</p>
                  </div>
                </div>
                <div className="text-right flex flex-col items-end gap-1">
                  <p className="text-sm font-bold">{formatCurrency(order.amount_total)}</p>
                  <PaymentStatusBadge status={order.payment_status} />
                </div>
              </div>
            ))}
            {recentOrders.length === 0 && (
              <div className="py-12 text-center text-muted-foreground text-sm font-medium">Keine Bestellungen vorhanden.</div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Low Stock Alerts */}
      <Card className="lg:col-span-3 shadow-sm border-border/40">
        <CardHeader>
          <CardTitle className="text-base font-semibold">Lagerwarnungen</CardTitle>
          <CardDescription className="text-xs">Produkte mit kritischem Lagerbestand</CardDescription>
        </CardHeader>
        <CardContent className="p-0">
          <div className="divide-y divide-border/40">
            {lowStockItems.map((product) => (
              <div key={product.id} className="group flex items-center justify-between px-6 py-3.5 hover:bg-muted/30 transition-colors">
                <div className="flex items-center gap-3">
                  <div className="size-8 rounded-lg bg-amber-500/10 flex items-center justify-center">
                    <Package className="size-4 text-amber-600" aria-hidden="true" />
                  </div>
                  <div className="max-w-[140px]">
                    <div className="flex items-center gap-1 min-w-0">
                      <p className="text-sm font-bold truncate min-w-0 flex-1">{product.name}</p>
                      <CopyButton
                        value={product.id}
                        copyMessage="Produkt-ID kopieren"
                        successMessage="ID kopiert!"
                        aria-label={`Produkt-ID ${product.id} kopieren`}
                        className="size-4 opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity shrink-0"
                      />
                    </div>
                    <p className="text-xs text-muted-foreground font-medium uppercase">Bestand: {product.inventory}</p>
                  </div>
                </div>
                <Link href={`/dashboard/products/overview?id=${product.id}`} title="Produktbestand auffüllen">
                  <Badge variant="outline" className="text-xs uppercase font-bold tracking-normal border-amber-500/30 text-amber-600 bg-amber-500/5 hover:bg-amber-500/10 cursor-pointer">
                    Auffüllen
                  </Badge>
                </Link>
              </div>
            ))}
            {lowStockItems.length === 0 && (
              <div className="py-12 text-center text-emerald-500 text-sm font-bold">Alles auf Lager!</div>
            )}
          </div>
        </CardContent>
      </Card>
    </div>
  );
}


