"use client";

import { useState } from "react";
import { createClient } from "@/lib/supabase/client";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Plus, Loader2, Stethoscope } from "lucide-react";
import { toast } from "sonner";

interface Props {
  services: any[];
}

export function ServicesCatalog({ services }: Props) {
  const supabase = createClient();
  const [showDialog, setShowDialog] = useState(false);
  const [loading, setLoading] = useState(false);

  async function handleAddService(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setLoading(true);
    const form = new FormData(e.currentTarget);
    const { data: { user } } = await supabase.auth.getUser();
    if (!user) { toast.error("No autenticado"); setLoading(false); return; }
    const { data: profile } = await supabase.from("users").select("clinic_id").eq("id", user.id).single();
    if (!profile) { toast.error("Perfil no encontrado"); setLoading(false); return; }

    const { error } = await supabase.from("services_catalog").insert({
      clinic_id: profile.clinic_id,
      name: form.get("name") as string,
      description: (form.get("description") as string) || null,
      price: parseFloat(form.get("price") as string) || 0,
      sat_product_key: (form.get("sat_product_key") as string) || null,
      tax_rate: 0.16,
    });

    if (error) { toast.error(error.message); setLoading(false); return; }
    toast.success("Servicio agregado");
    setLoading(false);
    setShowDialog(false);
    window.location.reload();
  }

  return (
    <div className="space-y-4">
      <div className="flex justify-end">
        <Button onClick={() => setShowDialog(true)} className="gap-2"><Plus className="h-4 w-4" /> Nuevo servicio</Button>
      </div>

      {services.length === 0 ? (
        <Card className="flex flex-col items-center justify-center py-16">
          <Stethoscope className="h-12 w-12 text-muted-foreground/40 mb-4" />
          <h3 className="text-lg font-semibold">Sin servicios</h3>
          <p className="text-sm text-muted-foreground mb-4">Agrega los servicios que ofrece tu clinica.</p>
          <Button onClick={() => setShowDialog(true)}>Agregar servicio</Button>
        </Card>
      ) : (
        <Card>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Servicio</TableHead>
                <TableHead>Descripcion</TableHead>
                <TableHead>Clave SAT</TableHead>
                <TableHead className="text-right">Precio</TableHead>
                <TableHead>Estado</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {services.map((s: any) => (
                <TableRow key={s.id}>
                  <TableCell className="font-medium">{s.name}</TableCell>
                  <TableCell className="text-muted-foreground text-sm max-w-[200px] truncate">{s.description || "—"}</TableCell>
                  <TableCell className="font-mono text-xs text-muted-foreground">{s.sat_product_key || "—"}</TableCell>
                  <TableCell className="text-right font-semibold">${Number(s.price).toLocaleString("es-MX", { minimumFractionDigits: 2 })}</TableCell>
                  <TableCell>{s.is_active ? <Badge variant="outline" className="text-emerald-600">Activo</Badge> : <Badge variant="outline" className="text-red-600">Inactivo</Badge>}</TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </Card>
      )}

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent className="max-w-md">
          <DialogHeader><DialogTitle>Nuevo servicio</DialogTitle></DialogHeader>
          <form onSubmit={handleAddService} className="space-y-4">
            <div className="space-y-2"><Label>Nombre del servicio *</Label><Input name="name" required className="h-10" placeholder="Consulta general" /></div>
            <div className="space-y-2"><Label>Descripcion</Label><Input name="description" className="h-10" placeholder="Descripcion del servicio" /></div>
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-2"><Label>Precio *</Label><Input name="price" type="number" step="0.01" required className="h-10" placeholder="500.00" /></div>
              <div className="space-y-2"><Label>Clave SAT</Label><Input name="sat_product_key" className="h-10 font-mono" placeholder="85121800" /></div>
            </div>
            <Button type="submit" disabled={loading} className="w-full h-10">
              {loading ? <><Loader2 className="mr-2 h-4 w-4 animate-spin" /> Guardando...</> : "Guardar servicio"}
            </Button>
          </form>
        </DialogContent>
      </Dialog>
    </div>
  );
}
