"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import { Card, CardContent, CardHeader, CardTitle, CardFooter } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Separator } from "@/components/ui/separator";
import { Loader2, Save, Plus, Trash2, Check } from "lucide-react";
import { cn } from "@/lib/utils";

interface LineItem {
  description: string;
  quantity: number;
  unit_price: number;
  tax_rate: number;
  service_id?: string;
}

interface Props {
  patients: { id: string; first_name: string; last_name: string; phone: string | null }[];
  services: { id: string; name: string; price: number; tax_rate: number }[];
}

export function InvoiceForm({ patients, services }: Props) {
  const router = useRouter();
  const supabase = createClient();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [patientOpen, setPatientOpen] = useState(false);
  const [selectedPatientId, setSelectedPatientId] = useState("");
  const [selectedPatientLabel, setSelectedPatientLabel] = useState("");
  const [items, setItems] = useState<LineItem[]>([{ description: "", quantity: 1, unit_price: 0, tax_rate: 0.16 }]);

  function addItem() {
    setItems([...items, { description: "", quantity: 1, unit_price: 0, tax_rate: 0.16 }]);
  }

  function removeItem(index: number) {
    if (items.length > 1) setItems(items.filter((_, i) => i !== index));
  }

  function updateItem(index: number, field: string, value: any) {
    const updated = [...items];
    (updated[index] as any)[field] = value;
    setItems(updated);
  }

  function addService(serviceId: string) {
    const svc = services.find(s => s.id === serviceId);
    if (svc) {
      setItems([...items, { description: svc.name, quantity: 1, unit_price: svc.price, tax_rate: svc.tax_rate, service_id: svc.id }]);
    }
  }

  const subtotal = items.reduce((sum, i) => sum + i.quantity * i.unit_price, 0);
  const taxTotal = items.reduce((sum, i) => sum + i.quantity * i.unit_price * i.tax_rate, 0);
  const total = subtotal + taxTotal;

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    if (!selectedPatientId) { setError("Selecciona un paciente"); return; }
    if (items.every(i => !i.description)) { setError("Agrega al menos un concepto"); return; }
    setError(null);
    setLoading(true);

    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 form = new FormData(e.currentTarget);
    const { count } = await supabase.from("invoices").select("*", { count: "exact", head: true }).eq("clinic_id", profile.clinic_id);
    const invoiceNumber = `F-${String((count || 0) + 1).padStart(5, "0")}`;

    const { data: invoice, error: invErr } = await supabase.from("invoices").insert({
      clinic_id: profile.clinic_id,
      patient_id: selectedPatientId,
      invoice_number: invoiceNumber,
      subtotal: Math.round(subtotal * 100) / 100,
      tax_amount: Math.round(taxTotal * 100) / 100,
      total: Math.round(total * 100) / 100,
      forma_pago: (form.get("forma_pago") as string) || "01",
      metodo_pago: (form.get("metodo_pago") as string) || "PUE",
      uso_cfdi: (form.get("uso_cfdi") as string) || "S01",
      created_by: user.id,
    }).select().single();

    if (invErr || !invoice) { setError(invErr?.message || "Error"); setLoading(false); return; }

    const invItems = items.filter(i => i.description).map(i => ({
      invoice_id: invoice.id,
      description: i.description,
      quantity: i.quantity,
      unit_price: i.unit_price,
      tax_rate: i.tax_rate,
      total: Math.round(i.quantity * i.unit_price * (1 + i.tax_rate) * 100) / 100,
      service_id: i.service_id || null,
      product_id: null,
    }));

    await supabase.from("invoice_items").insert(invItems);
    router.push("/billing");
    router.refresh();
  }

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {error && <div className="rounded-lg bg-destructive/10 p-3 text-sm text-destructive">{error}</div>}

      {/* Patient */}
      <Card>
        <CardHeader><CardTitle className="text-base">Datos del paciente</CardTitle></CardHeader>
        <CardContent className="space-y-4">
          <div className="space-y-2">
            <Label>Paciente *</Label>
            <Popover open={patientOpen} onOpenChange={setPatientOpen}>
              <PopoverTrigger asChild>
                <Button variant="outline" className="w-full justify-start h-10 font-normal">
                  {selectedPatientLabel || <span className="text-muted-foreground">Buscar paciente...</span>}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0" align="start">
                <Command>
                  <CommandInput placeholder="Buscar..." />
                  <CommandList>
                    <CommandEmpty>Sin resultados.</CommandEmpty>
                    <CommandGroup>
                      {patients.map((p) => (
                        <CommandItem key={p.id} value={`${p.first_name} ${p.last_name}`} onSelect={() => {
                          setSelectedPatientId(p.id);
                          setSelectedPatientLabel(`${p.first_name} ${p.last_name}`);
                          setPatientOpen(false);
                        }}>
                          <Check className={cn("mr-2 h-4 w-4", selectedPatientId === p.id ? "opacity-100" : "opacity-0")} />
                          {p.first_name} {p.last_name}
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>
          <div className="grid grid-cols-3 gap-3">
            <div className="space-y-2">
              <Label>Forma de pago</Label>
              <Select name="forma_pago" defaultValue="01">
                <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="01">Efectivo</SelectItem>
                  <SelectItem value="04">Tarjeta</SelectItem>
                  <SelectItem value="03">Transferencia</SelectItem>
                  <SelectItem value="99">Otro</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Metodo de pago</Label>
              <Select name="metodo_pago" defaultValue="PUE">
                <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="PUE">Pago en una exhibicion</SelectItem>
                  <SelectItem value="PPD">Parcialidades</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div className="space-y-2">
              <Label>Uso CFDI</Label>
              <Select name="uso_cfdi" defaultValue="S01">
                <SelectTrigger className="h-10"><SelectValue /></SelectTrigger>
                <SelectContent>
                  <SelectItem value="D01">Gastos medicos</SelectItem>
                  <SelectItem value="G03">Gastos en general</SelectItem>
                  <SelectItem value="S01">Sin efectos fiscales</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Line Items */}
      <Card>
        <CardHeader className="flex flex-row items-center justify-between">
          <CardTitle className="text-base">Conceptos</CardTitle>
          <div className="flex gap-2">
            {services.length > 0 && (
              <Select onValueChange={addService}>
                <SelectTrigger className="h-8 text-xs w-[180px]"><SelectValue placeholder="Agregar servicio..." /></SelectTrigger>
                <SelectContent>{services.map(s => <SelectItem key={s.id} value={s.id}>{s.name} - ${s.price}</SelectItem>)}</SelectContent>
              </Select>
            )}
            <Button type="button" variant="outline" size="sm" onClick={addItem} className="gap-1"><Plus className="h-3 w-3" /> Concepto</Button>
          </div>
        </CardHeader>
        <CardContent className="space-y-3">
          {items.map((item, i) => (
            <div key={i} className="flex items-end gap-2">
              <div className="flex-1 space-y-1">
                {i === 0 && <Label className="text-xs">Descripcion</Label>}
                <Input value={item.description} onChange={(e) => updateItem(i, "description", e.target.value)} placeholder="Descripcion" className="h-9" />
              </div>
              <div className="w-20 space-y-1">
                {i === 0 && <Label className="text-xs">Cant.</Label>}
                <Input type="number" value={item.quantity} onChange={(e) => updateItem(i, "quantity", parseFloat(e.target.value) || 0)} className="h-9" min={1} />
              </div>
              <div className="w-28 space-y-1">
                {i === 0 && <Label className="text-xs">Precio</Label>}
                <Input type="number" value={item.unit_price} onChange={(e) => updateItem(i, "unit_price", parseFloat(e.target.value) || 0)} className="h-9" step="0.01" />
              </div>
              <div className="w-24 space-y-1">
                {i === 0 && <Label className="text-xs">Total</Label>}
                <div className="h-9 flex items-center text-sm font-medium px-2">
                  ${(item.quantity * item.unit_price).toLocaleString("es-MX", { minimumFractionDigits: 2 })}
                </div>
              </div>
              <Button type="button" variant="ghost" size="icon" className="h-9 w-9 text-muted-foreground hover:text-destructive" onClick={() => removeItem(i)}><Trash2 className="h-4 w-4" /></Button>
            </div>
          ))}
        </CardContent>
        <CardFooter className="flex flex-col items-end border-t pt-4 space-y-1">
          <div className="flex justify-between w-64 text-sm"><span className="text-muted-foreground">Subtotal:</span><span>${subtotal.toLocaleString("es-MX", { minimumFractionDigits: 2 })}</span></div>
          <div className="flex justify-between w-64 text-sm"><span className="text-muted-foreground">IVA (16%):</span><span>${taxTotal.toLocaleString("es-MX", { minimumFractionDigits: 2 })}</span></div>
          <Separator className="w-64 my-1" />
          <div className="flex justify-between w-64 text-lg font-bold"><span>Total:</span><span>${total.toLocaleString("es-MX", { minimumFractionDigits: 2 })}</span></div>
        </CardFooter>
      </Card>

      <div className="flex justify-end gap-3">
        <Button type="button" variant="ghost" onClick={() => router.back()}>Cancelar</Button>
        <Button type="submit" disabled={loading} className="gap-2 min-w-[160px]">
          {loading ? <><Loader2 className="h-4 w-4 animate-spin" /> Creando...</> : <><Save className="h-4 w-4" /> Crear factura</>}
        </Button>
      </div>
    </form>
  );
}
