"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import { ArrowLeft, Save, Loader2 } from "lucide-react";

export default function NewProductPage() {
  const router = useRouter();
  const supabase = createClient();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    setLoading(true);

    const form = new FormData(e.currentTarget);
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) { setError("No autenticado"); setLoading(false); return; }
    const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
    if (!profile) { setError("Perfil no encontrado"); setLoading(false); return; }

    const { error: err } = await supabase.from("products").insert({
      clinic_id: profile.clinic_id,
      name: form.get("name") as string,
      sku: (form.get("sku") as string) || null,
      description: (form.get("description") as string) || null,
      category: (form.get("category") as string) || "insumo",
      unit: (form.get("unit") as string) || "pieza",
      purchase_price: parseFloat(form.get("purchase_price") as string) || 0,
      sale_price: parseFloat(form.get("sale_price") as string) || 0,
      min_stock: parseInt(form.get("min_stock") as string) || 0,
    });

    if (err) { setError(err.message); setLoading(false); return; }
    router.push("/inventory");
    router.refresh();
  }

  return (
    <div className="mx-auto max-w-2xl space-y-6">
      <div className="flex items-center gap-4">
        <Link href="/inventory"><Button variant="ghost" size="icon"><ArrowLeft className="h-4 w-4" /></Button></Link>
        <div>
          <h1 className="text-2xl font-bold">Nuevo producto</h1>
          <p className="text-sm text-muted-foreground">Registra un nuevo producto o insumo.</p>
        </div>
      </div>

      <form onSubmit={handleSubmit}>
        <Card>
          <CardHeader><CardTitle className="text-lg">Informacion del producto</CardTitle></CardHeader>
          <CardContent className="space-y-4">
            {error && <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2"><Label>Nombre *</Label><Input name="name" required className="h-11" placeholder="Paracetamol 500mg" /></div>
              <div className="space-y-2"><Label>SKU</Label><Input name="sku" className="h-11 font-mono" placeholder="MED-001" /></div>
            </div>

            <div className="grid gap-4 sm:grid-cols-2">
              <div className="space-y-2">
                <Label>Categoria</Label>
                <Select name="category" defaultValue="insumo">
                  <SelectTrigger className="h-11"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="medicamento">Medicamento</SelectItem>
                    <SelectItem value="insumo">Insumo</SelectItem>
                    <SelectItem value="material">Material</SelectItem>
                    <SelectItem value="equipo">Equipo</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <div className="space-y-2">
                <Label>Unidad</Label>
                <Select name="unit" defaultValue="pieza">
                  <SelectTrigger className="h-11"><SelectValue /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="pieza">Pieza</SelectItem>
                    <SelectItem value="caja">Caja</SelectItem>
                    <SelectItem value="ml">mL</SelectItem>
                    <SelectItem value="kg">Kg</SelectItem>
                    <SelectItem value="paquete">Paquete</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>

            <Separator />

            <div className="grid gap-4 sm:grid-cols-3">
              <div className="space-y-2"><Label>Precio compra</Label><Input name="purchase_price" type="number" step="0.01" className="h-11" placeholder="0.00" /></div>
              <div className="space-y-2"><Label>Precio venta</Label><Input name="sale_price" type="number" step="0.01" className="h-11" placeholder="0.00" /></div>
              <div className="space-y-2"><Label>Stock minimo</Label><Input name="min_stock" type="number" className="h-11" placeholder="0" /></div>
            </div>

            <div className="space-y-2"><Label>Descripcion</Label><Textarea name="description" rows={2} placeholder="Descripcion del producto..." /></div>
          </CardContent>
          <CardFooter className="flex justify-between border-t pt-6">
            <Link href="/inventory"><Button type="button" variant="ghost" className="gap-2"><ArrowLeft className="h-4 w-4" /> Cancelar</Button></Link>
            <Button type="submit" disabled={loading} className="gap-2 min-w-[140px]">
              {loading ? <><Loader2 className="h-4 w-4 animate-spin" /> Guardando...</> : <><Save className="h-4 w-4" /> Guardar producto</>}
            </Button>
          </CardFooter>
        </Card>
      </form>
    </div>
  );
}
