"use client";
import { useState } from "react";
import { useSearchParams, useRouter } from "next/navigation";
import { Container } from "@/components/container";
import { Heading } from "@/components/heading";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { NavBar } from "@/components/navbar";
import { Footer } from "@/components/footer";

const products = {
  ultra: { name: "👑 ULTRA", price: 16000 },
  mega: { name: "💎 MEGA", price: 9500 },
  premium: { name: "⭐ PREMIUM", price: 4800 },
  basico: { name: "🔹 Básico", price: 2900 },
  esencia: { name: "🟢 ESENCIA", price: 1650 },
  origen: { name: "🔵 ORIGEN", price: 1250 },
  raiz: { name: "🟡 RAÍZ", price: 950 },
  mini: { name: "🔴 Mini", price: 650 },
};

export default function CheckoutPage() {
  const searchParams = useSearchParams();
  const router = useRouter();
  const planId = (searchParams.get("plan") as keyof typeof products) || "mini";
  const product = products[planId];

  const [formData, setFormData] = useState({
    name: "",
    email: "",
    phone: "",
    address: "",
    paymentMethod: "card",
  });

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    const orderId = Math.random().toString(36).substring(7).toUpperCase();
    localStorage.setItem(`order_${orderId}`, JSON.stringify({
      ...formData,
      product: product.name,
      price: product.price,
      status: "Pendiente",
      date: new Date().toISOString(),
    }));
    router.push(`/payment?orderId=${orderId}`);
  };

  return (
    <main>
      <NavBar />
      <Container className="py-32">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          <div>
            <Heading className="mb-8">Finalizar Pedido</Heading>
            <form onSubmit={handleSubmit} className="space-y-6">
              <div className="space-y-2">
                <Label htmlFor="name">Nombre Completo</Label>
                <Input id="name" required value={formData.name} onChange={(e) => setFormData({...formData, name: e.target.value})} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="email">Correo Electrónico</Label>
                <Input id="email" type="email" required value={formData.email} onChange={(e) => setFormData({...formData, email: e.target.value})} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="phone">Teléfono / WhatsApp</Label>
                <Input id="phone" type="tel" required value={formData.phone} onChange={(e) => setFormData({...formData, phone: e.target.value})} />
              </div>
              <div className="space-y-2">
                <Label htmlFor="address">Dirección de Envío Completa</Label>
                <Input id="address" required value={formData.address} onChange={(e) => setFormData({...formData, address: e.target.value})} />
              </div>
              <div className="space-y-2">
                <Label>Método de Pago</Label>
                <Select value={formData.paymentMethod} onValueChange={(v) => setFormData({...formData, paymentMethod: v})}>
                  <SelectTrigger>
                    <SelectValue placeholder="Selecciona un método" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="card">Tarjeta de Crédito/Débito</SelectItem>
                    <SelectItem value="binance">Binance (USDT)</SelectItem>
                    <SelectItem value="oxxo">OXXO (QR)</SelectItem>
                    <SelectItem value="transfer">Transferencia Bancaria / ACH</SelectItem>
                  </SelectContent>
                </Select>
              </div>
              <Button type="submit" className="w-full">Continuar al Pago</Button>
            </form>
          </div>

          <div>
            <Card>
              <CardHeader>
                <CardTitle>Resumen del Pedido</CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                <div className="flex justify-between border-b pb-4">
                  <span>Producto:</span>
                  <span className="font-bold">{product.name}</span>
                </div>
                <div className="flex justify-between text-2xl font-bold pt-4">
                  <span>Total:</span>
                  <span>${product.price.toLocaleString()} USD</span>
                </div>
                <p className="text-sm text-neutral-500 italic">
                  * El precio en MXN se calculará al tipo de cambio del día durante el pago.
                </p>
              </CardContent>
            </Card>
          </div>
        </div>
      </Container>
      <Footer />
    </main>
  );
}
