import { createClient } from "@/lib/supabase/server";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Input } from "@/components/ui/input";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Plus, Package, Search, AlertTriangle, ArrowDownUp, Box } from "lucide-react";

export const dynamic = "force-dynamic";

const categoryLabels: Record<string, string> = {
  medicamento: "Medicamento",
  insumo: "Insumo",
  material: "Material",
  equipo: "Equipo",
};

const categoryColors: Record<string, string> = {
  medicamento: "bg-blue-100 text-blue-700",
  insumo: "bg-emerald-100 text-emerald-700",
  material: "bg-purple-100 text-purple-700",
  equipo: "bg-amber-100 text-amber-700",
};

export default async function InventoryPage({ searchParams }: { searchParams: Promise<{ q?: string }> }) {
  const params = await searchParams;
  const search = params.q || "";
  const supabase = await createClient();

  let query = supabase.from("products").select("*, stock:inventory_stock(current_stock)").eq("is_active", true).order("name");
  if (search) query = query.or(`name.ilike.%${search}%,sku.ilike.%${search}%`);
  const { data: products } = await query;

  const { data: movements } = await supabase
    .from("inventory_movements")
    .select("*, product:products(id, name)")
    .order("created_at", { ascending: false })
    .limit(20);

  const all = products || [];
  const lowStock = all.filter((p: any) => {
    const stock = p.stock?.[0]?.current_stock || 0;
    return stock <= p.min_stock && p.min_stock > 0;
  });

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">Inventario</h1>
          <p className="text-muted-foreground">Control de productos e insumos medicos.</p>
        </div>
        <Link href="/inventory/new"><Button className="gap-2"><Plus className="h-4 w-4" /> Nuevo producto</Button></Link>
      </div>

      {/* Summary */}
      <div className="grid gap-4 sm:grid-cols-3">
        <Card><CardContent className="p-4 flex items-center gap-4"><div className="flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10"><Box className="h-5 w-5 text-primary" /></div><div><p className="text-sm text-muted-foreground">Productos</p><p className="text-2xl font-bold">{all.length}</p></div></CardContent></Card>
        <Card><CardContent className="p-4 flex items-center gap-4"><div className="flex h-11 w-11 items-center justify-center rounded-xl bg-amber-100"><AlertTriangle className="h-5 w-5 text-amber-600" /></div><div><p className="text-sm text-muted-foreground">Stock bajo</p><p className="text-2xl font-bold text-amber-600">{lowStock.length}</p></div></CardContent></Card>
        <Card><CardContent className="p-4 flex items-center gap-4"><div className="flex h-11 w-11 items-center justify-center rounded-xl bg-blue-100"><ArrowDownUp className="h-5 w-5 text-blue-600" /></div><div><p className="text-sm text-muted-foreground">Movimientos hoy</p><p className="text-2xl font-bold">{(movements || []).length}</p></div></CardContent></Card>
      </div>

      <Tabs defaultValue="products">
        <TabsList>
          <TabsTrigger value="products" className="gap-2"><Package className="h-4 w-4" /> Productos</TabsTrigger>
          <TabsTrigger value="movements" className="gap-2"><ArrowDownUp className="h-4 w-4" /> Movimientos</TabsTrigger>
        </TabsList>

        <TabsContent value="products" className="mt-4 space-y-4">
          <div className="relative max-w-md">
            <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
            <form><Input name="q" placeholder="Buscar producto..." defaultValue={search} className="h-11 pl-10" /></form>
          </div>

          {all.length === 0 ? (
            <Card className="flex flex-col items-center justify-center py-16">
              <Package className="h-12 w-12 text-muted-foreground/40 mb-4" />
              <h3 className="text-lg font-semibold">Sin productos</h3>
              <p className="text-sm text-muted-foreground mb-4">Agrega tu primer producto.</p>
              <Link href="/inventory/new"><Button>Nuevo producto</Button></Link>
            </Card>
          ) : (
            <Card>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Producto</TableHead>
                    <TableHead>SKU</TableHead>
                    <TableHead>Categoria</TableHead>
                    <TableHead className="text-right">Precio venta</TableHead>
                    <TableHead className="text-right">Stock</TableHead>
                    <TableHead className="text-right">Minimo</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {all.map((p: any) => {
                    const stock = p.stock?.[0]?.current_stock || 0;
                    const isLow = stock <= p.min_stock && p.min_stock > 0;
                    return (
                      <TableRow key={p.id}>
                        <TableCell className="font-medium">{p.name}</TableCell>
                        <TableCell className="font-mono text-xs text-muted-foreground">{p.sku || "\u2014"}</TableCell>
                        <TableCell><Badge className={categoryColors[p.category]} variant="secondary">{categoryLabels[p.category]}</Badge></TableCell>
                        <TableCell className="text-right">${Number(p.sale_price).toLocaleString("es-MX", { minimumFractionDigits: 2 })}</TableCell>
                        <TableCell className={`text-right font-semibold ${isLow ? "text-destructive" : ""}`}>{stock}</TableCell>
                        <TableCell className="text-right text-muted-foreground">{p.min_stock}</TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </Card>
          )}
        </TabsContent>

        <TabsContent value="movements" className="mt-4">
          {!movements || movements.length === 0 ? (
            <Card className="py-12 text-center text-muted-foreground">Sin movimientos registrados.</Card>
          ) : (
            <Card>
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Producto</TableHead>
                    <TableHead>Tipo</TableHead>
                    <TableHead className="text-right">Cantidad</TableHead>
                    <TableHead>Motivo</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {movements.map((m: any) => (
                    <TableRow key={m.id}>
                      <TableCell className="font-medium">{m.product?.name}</TableCell>
                      <TableCell>
                        <Badge variant={m.type === "entrada" ? "default" : m.type === "salida" ? "secondary" : "destructive"}>
                          {m.type}
                        </Badge>
                      </TableCell>
                      <TableCell className={`text-right font-mono ${m.quantity > 0 ? "text-emerald-600" : "text-destructive"}`}>
                        {m.quantity > 0 ? "+" : ""}{m.quantity}
                      </TableCell>
                      <TableCell className="text-muted-foreground text-sm">{m.reason || "\u2014"}</TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </Card>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}
