"use client";

import { useState } from "react";
import Link from "next/link";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { ShoppingBag, CreditCard, Banknote, Smartphone, Loader2 } from "lucide-react";
import { useCartStore } from "@/store/cart";
import { formatPrice } from "@/lib/utils";
import toast from "react-hot-toast";

const paymentMethods = [
  { id: "mpesa", label: "M-Pesa", icon: Smartphone, desc: "Pay via M-Pesa paybill" },
  { id: "bank", label: "Bank Transfer", icon: Banknote, desc: "Direct bank deposit" },
  { id: "card", label: "Credit/Debit Card", icon: CreditCard, desc: "Visa, Mastercard" },
  { id: "cash", label: "Cash on Delivery", icon: ShoppingBag, desc: "Pay when delivered" },
];

export default function CheckoutPage() {
  const router = useRouter();
  const { data: session } = useSession();
  const { items, total, clearCart, closeCart } = useCartStore();
  const [loading, setLoading] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState("mpesa");
  const [form, setForm] = useState({ name: session?.user?.name || "", email: session?.user?.email || "", phone: "", address: "", city: "Nairobi", county: "" });
  const cartTotal = total();
  const shipping = cartTotal >= 10000 ? 0 : 300;

  const update = (k: string, v: string) => setForm((f) => ({ ...f, [k]: v }));

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!session) { router.push("/login"); return; }
    if (items.length === 0) { toast.error("Your cart is empty"); return; }
    setLoading(true);
    try {
      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          ...form,
          items: items.map((i) => ({ productId: i.id, quantity: i.quantity, price: i.price, name: i.name, image: i.image })),
          shipping,
          paymentMethod,
        }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.error);
      clearCart();
      closeCart();
      router.push(`/checkout/success?order=${data.orderNumber}`);
    } catch (e) {
      toast.error((e as Error).message || "Failed to place order");
    } finally {
      setLoading(false);
    }
  };

  if (items.length === 0) return (
    <div className="min-h-screen flex flex-col items-center justify-center gap-4 text-center px-4">
      <ShoppingBag className="w-16 h-16 text-sky-200" />
      <h1 className="text-2xl font-black text-slate-800">Your cart is empty</h1>
      <Link href="/" className="bg-sky-500 text-white px-8 py-3 rounded-xl font-bold hover:bg-sky-600 transition-colors">Start Shopping</Link>
    </div>
  );

  return (
    <div className="max-w-6xl mx-auto px-4 py-8">
      <h1 className="text-2xl font-black text-slate-900 mb-8">Checkout</h1>
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        {/* Form */}
        <div className="lg:col-span-2 space-y-6">
          {!session && (
            <div className="bg-sky-50 border border-sky-200 rounded-2xl p-4 flex items-center justify-between">
              <p className="text-sky-700 text-sm font-medium">Sign in for a faster checkout experience</p>
              <Link href="/login" className="bg-sky-500 text-white px-4 py-2 rounded-lg text-sm font-bold hover:bg-sky-600 transition-colors">Sign In</Link>
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-6">
            {/* Shipping */}
            <div className="bg-white rounded-2xl border border-slate-100 p-6">
              <h2 className="font-black text-slate-800 mb-4">Shipping Information</h2>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                {[
                  { k: "name", label: "Full Name", placeholder: "John Mwangi", col: 2 },
                  { k: "email", label: "Email", placeholder: "john@email.com", col: 1, type: "email" },
                  { k: "phone", label: "Phone", placeholder: "0712 345 678", col: 1, type: "tel" },
                  { k: "address", label: "Address", placeholder: "Tom Mboya Street", col: 2 },
                  { k: "city", label: "City", placeholder: "Nairobi", col: 1 },
                  { k: "county", label: "County", placeholder: "Nairobi County", col: 1 },
                ].map(({ k, label, placeholder, col, type }) => (
                  <div key={k} className={col === 2 ? "sm:col-span-2" : ""}>
                    <label className="block text-sm font-bold text-slate-700 mb-1.5">{label}</label>
                    <input type={type || "text"} value={form[k as keyof typeof form]} onChange={(e) => update(k, e.target.value)}
                      placeholder={placeholder} required={k !== "county"}
                      className="w-full px-4 py-3 rounded-xl border-2 border-slate-200 focus:border-sky-400 focus:outline-none text-sm transition-colors" />
                  </div>
                ))}
              </div>
            </div>

            {/* Payment */}
            <div className="bg-white rounded-2xl border border-slate-100 p-6">
              <h2 className="font-black text-slate-800 mb-4">Payment Method</h2>
              <div className="grid grid-cols-2 gap-3">
                {paymentMethods.map((pm) => (
                  <button key={pm.id} type="button" onClick={() => setPaymentMethod(pm.id)}
                    className={`flex items-center gap-3 p-4 rounded-xl border-2 text-left transition-all ${paymentMethod === pm.id ? "border-sky-500 bg-sky-50" : "border-slate-200 hover:border-sky-200"}`}>
                    <pm.icon className={`w-5 h-5 ${paymentMethod === pm.id ? "text-sky-600" : "text-slate-500"}`} />
                    <div>
                      <p className={`text-sm font-bold ${paymentMethod === pm.id ? "text-sky-700" : "text-slate-700"}`}>{pm.label}</p>
                      <p className="text-xs text-slate-500">{pm.desc}</p>
                    </div>
                  </button>
                ))}
              </div>
              {paymentMethod === "mpesa" && (
                <div className="mt-4 p-4 bg-green-50 rounded-xl border border-green-200">
                  <p className="text-green-800 text-sm font-medium">M-Pesa Paybill: <strong>123456</strong></p>
                  <p className="text-green-700 text-xs mt-1">Account: Your Order Number (provided after order)</p>
                </div>
              )}
            </div>

            <button type="submit" disabled={loading}
              className="w-full flex items-center justify-center gap-2 bg-gradient-to-r from-sky-600 to-sky-500 text-white py-4 rounded-xl font-bold text-lg hover:from-sky-700 hover:to-sky-600 transition-all disabled:opacity-50 shadow-lg shadow-sky-200">
              {loading ? <Loader2 className="w-5 h-5 animate-spin" /> : null}
              {loading ? "Placing Order..." : `Place Order — ${formatPrice(cartTotal + shipping)}`}
            </button>
          </form>
        </div>

        {/* Order Summary */}
        <div className="lg:col-span-1">
          <div className="bg-white rounded-2xl border border-slate-100 p-6 sticky top-24">
            <h2 className="font-black text-slate-800 mb-4">Order Summary</h2>
            <div className="space-y-3 mb-4">
              {items.map((item) => (
                <div key={item.id} className="flex gap-3">
                  <div className="relative w-16 h-16 rounded-xl overflow-hidden bg-slate-50 shrink-0">
                    <Image src={item.image || "/images/placeholder.png"} alt={item.name} fill className="object-cover" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <p className="text-sm font-semibold text-slate-800 line-clamp-2">{item.name}</p>
                    <p className="text-xs text-slate-500 mt-0.5">Qty: {item.quantity}</p>
                    <p className="text-sm font-bold text-sky-600">{formatPrice(item.price * item.quantity)}</p>
                  </div>
                </div>
              ))}
            </div>
            <div className="border-t border-slate-100 pt-4 space-y-2">
              <div className="flex justify-between text-sm">
                <span className="text-slate-500">Subtotal</span>
                <span className="font-bold">{formatPrice(cartTotal)}</span>
              </div>
              <div className="flex justify-between text-sm">
                <span className="text-slate-500">Delivery</span>
                <span className={shipping === 0 ? "text-green-600 font-bold" : "font-bold"}>
                  {shipping === 0 ? "FREE" : formatPrice(shipping)}
                </span>
              </div>
              <div className="flex justify-between font-black text-lg pt-2 border-t border-slate-100">
                <span>Total</span>
                <span className="text-sky-600">{formatPrice(cartTotal + shipping)}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
