import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";

export default function Carrito() {
  const [carrito, setCarrito] = useState([]);
  const [showDialog, setShowDialog] = useState(false);
  const [conciertoAEliminar, setConciertoAEliminar] = useState(null);
  const router = useRouter();

  useEffect(() => {
    const carritoGuardado = JSON.parse(localStorage.getItem("carrito")) || [];
    setCarrito(carritoGuardado);
  }, []);

  const eliminarConcierto = () => {
    if (conciertoAEliminar !== null) {
      const nuevoCarrito = carrito.filter((_, index) => index !== conciertoAEliminar);
      localStorage.setItem("carrito", JSON.stringify(nuevoCarrito));
      setCarrito(nuevoCarrito);
      setShowDialog(false);
    }
  };

  const calcularTotal = () => {
    return carrito.reduce((total, item) => total + (item.precio || 0), 0);
  };

  const pagar = async () => {
    try {
      const response = await fetch("/api/comprar-boletos", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ boletos: carrito }),
      });

      if (!response.ok) {
        throw new Error("Error al procesar el pago");
      }

      alert("Compra realizada con éxito");
      localStorage.removeItem("carrito");
      setCarrito([]);
      router.push("/");
    } catch (error) {
      console.error("Error en la compra:", error);
      alert("Hubo un problema al realizar la compra");
    }
  };

  return (
    <div className="p-4 max-w-3xl mx-auto bg-gray-900 text-white rounded-lg shadow-lg">
      <h2 className="text-2xl font-bold mb-4">Carrito de Compras</h2>
      {carrito.length === 0 ? (
        <p className="text-gray-400">No hay conciertos en el carrito.</p>
      ) : (
        carrito.map((item, index) => (
          <div key={index} className="border p-4 mb-2 rounded-lg bg-gray-800">
            <p className="text-lg font-semibold text-white">{item.nombre}</p>
            <p className="text-sm text-gray-300">Fecha: {item.fecha}</p>
            <p className="text-sm text-gray-300">Asiento: {item.asiento}</p>
            <p className="text-sm text-gray-300">Precio: ${item.precio}</p>
            <Button
              className="mt-2 bg-red-500 hover:bg-red-600"
              onClick={() => {
                setConciertoAEliminar(index);
                setShowDialog(true);
              }}
            >
              Eliminar
            </Button>
          </div>
        ))
      )}

      {carrito.length > 0 && (
        <>
          <p className="text-xl font-bold text-white mt-4">Total: ${calcularTotal()}</p>
          <div className="flex justify-between mt-4">
            <Button
              className="bg-gray-500 hover:bg-gray-600"
              onClick={() => router.push("/")}
            >
              Cancelar
            </Button>
            <Button className="bg-green-500 hover:bg-green-600" onClick={pagar}>Pagar</Button>
          </div>
        </>
      )}

      <Dialog open={showDialog} onOpenChange={setShowDialog}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>¿Estás seguro de eliminar este concierto?</DialogTitle>
          </DialogHeader>
          <div className="flex justify-end gap-2 mt-4">
            <Button variant="outline" onClick={() => setShowDialog(false)}>
              Cancelar
            </Button>
            <Button className="bg-red-500 hover:bg-red-600" onClick={eliminarConcierto}>
              Eliminar
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}