"use client";

import React, { useState } from "react";
import { useCart } from "@/context/CartContext";
import {
  X,
  CheckCircle2,
  Truck,
  CreditCard,
  ShieldCheck,
  Building,
  User,
  Phone,
  Mail,
  MapPin,
  Lock,
  Package,
  Printer,
  Sparkles,
  ArrowLeft,
  ChevronRight,
} from "lucide-react";

const PROVINCES = [
  "Gauteng",
  "Western Cape",
  "KwaZulu-Natal",
  "Eastern Cape",
  "Free State",
  "Limpopo",
  "Mpumalanga",
  "North West",
  "Northern Cape",
];

export const CheckoutModal: React.FC = () => {
  const {
    cart,
    subtotal,
    discountAmount,
    vatAmount,
    amountNeededForFreeShipping,
    clearCart,
    isCheckoutOpen,
    setIsCheckoutOpen,
    setIsTrackerOpen,
  } = useCart();

  const [step, setStep] = useState<"details" | "payment" | "success">("details");
  const [isSubmitting, setIsSubmitting] = useState(false);

  // Form State
  const [customerName, setCustomerName] = useState("");
  const [email, setEmail] = useState("");
  const [phone, setPhone] = useState("");
  const [street, setStreet] = useState("");
  const [suburb, setSuburb] = useState("");
  const [city, setCity] = useState("");
  const [province, setProvince] = useState("Gauteng");
  const [postalCode, setPostalCode] = useState("");
  const [deliveryNotes, setDeliveryNotes] = useState("");

  const [shippingMethod, setShippingMethod] = useState<"standard" | "express" | "pickup">("standard");
  const [paymentMethod, setPaymentMethod] = useState<"ozow" | "payfast" | "card" | "eft">("ozow");

  // Success state
  const [completedOrder, setCompletedOrder] = useState<any>(null);

  if (!isCheckoutOpen) return null;

  // Calculate Courier Fee
  let shippingCost = 0;
  if (shippingMethod === "pickup") {
    shippingCost = 0;
  } else if (shippingMethod === "express") {
    shippingCost = 145;
  } else {
    shippingCost = amountNeededForFreeShipping === 0 ? 0 : 85;
  }

  const finalTotal = Math.max(0, subtotal - discountAmount + shippingCost);

  const handleSubmitOrder = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!customerName || !email || !street || !city) return;

    setIsSubmitting(true);
    try {
      const orderPayload = {
        customerName,
        email,
        phone,
        shippingAddress: {
          street,
          suburb,
          city,
          province,
          postalCode,
          notes: deliveryNotes,
        },
        shippingMethod:
          shippingMethod === "express"
            ? "Express Courier (Overnight)"
            : shippingMethod === "pickup"
            ? "Free Collection (Johannesburg Hub)"
            : "Standard Door Courier (24-48h)",
        shippingCost,
        paymentMethod:
          paymentMethod === "ozow"
            ? "Ozow Instant EFT"
            : paymentMethod === "payfast"
            ? "PayFast Gateway"
            : paymentMethod === "card"
            ? "Credit / Debit Card (Visa/Mastercard)"
            : "Direct Bank Transfer (EFT)",
        items: cart.map((c) => ({
          id: c.product.id,
          name: c.product.name,
          image: c.product.image,
          price: c.product.price,
          quantity: c.quantity,
        })),
        subtotal,
        discount: discountAmount,
        vat: vatAmount,
        total: finalTotal,
      };

      const res = await fetch("/api/orders", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(orderPayload),
      });

      const data = await res.json();
      if (data.success) {
        setCompletedOrder(data);
        clearCart();
        setStep("success");
      } else {
        alert(data.error || "Order placement failed. Please try again.");
      }
    } catch (err) {
      console.error(err);
      alert("An error occurred while placing your order. Please check connection.");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto bg-slate-950/70 backdrop-blur-sm flex items-center justify-center p-3 sm:p-6 animate-fadeIn">
      <div className="relative bg-white rounded-3xl shadow-2xl border border-slate-200 w-full max-w-4xl max-h-[92vh] overflow-y-auto my-auto">
        {/* Close Button */}
        <button
          onClick={() => setIsCheckoutOpen(false)}
          className="absolute top-4 right-4 z-20 bg-slate-100 hover:bg-slate-200 text-slate-700 p-2 rounded-full transition-colors"
        >
          <X className="w-5 h-5" />
        </button>

        {step !== "success" ? (
          <div className="p-5 sm:p-8">
            <div className="flex items-center gap-3 pb-5 mb-6 border-b border-slate-200">
              <div className="w-10 h-10 rounded-xl bg-amber-500/20 text-amber-700 flex items-center justify-center">
                <Lock className="w-5 h-5" />
              </div>
              <div>
                <h2 className="font-extrabold text-xl text-slate-900">Secure SA Express Checkout</h2>
                <p className="text-xs text-slate-500">100% Encrypted & Local SA Door Delivery</p>
              </div>
            </div>

            <form onSubmit={handleSubmitOrder} className="grid lg:grid-cols-12 gap-8">
              {/* Left Column Input Fields */}
              <div className="lg:col-span-7 space-y-6">
                {/* Customer Contact */}
                <div className="space-y-3">
                  <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                    <User className="w-4 h-4 text-blue-900" />
                    <span>1. Customer & Contact Details</span>
                  </h3>

                  <div className="grid sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">Full Name *</label>
                      <input
                        type="text"
                        placeholder="e.g. Lerato Nkosi"
                        value={customerName}
                        onChange={(e) => setCustomerName(e.target.value)}
                        required
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      />
                    </div>

                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">Email Address (for VAT Invoice) *</label>
                      <input
                        type="email"
                        placeholder="lerato@company.co.za"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                        required
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      />
                    </div>
                  </div>

                  <div>
                    <label className="block text-[11px] font-bold text-slate-600 mb-1">Cell Phone Number (for Courier SMS updates) *</label>
                    <input
                      type="tel"
                      placeholder="e.g. 082 123 4567"
                      value={phone}
                      onChange={(e) => setPhone(e.target.value)}
                      required
                      className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                    />
                  </div>
                </div>

                {/* Delivery Address */}
                <div className="space-y-3 pt-2 border-t border-slate-200">
                  <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                    <MapPin className="w-4 h-4 text-blue-900" />
                    <span>2. South Africa Shipping Address</span>
                  </h3>

                  <div>
                    <label className="block text-[11px] font-bold text-slate-600 mb-1">Street Address / Complex / Office Building *</label>
                    <input
                      type="text"
                      placeholder="e.g. 142 Jan Smuts Avenue, Office Block B"
                      value={street}
                      onChange={(e) => setStreet(e.target.value)}
                      required
                      className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                    />
                  </div>

                  <div className="grid sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">Suburb</label>
                      <input
                        type="text"
                        placeholder="e.g. Rosebank"
                        value={suburb}
                        onChange={(e) => setSuburb(e.target.value)}
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      />
                    </div>

                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">City / Town *</label>
                      <input
                        type="text"
                        placeholder="e.g. Johannesburg"
                        value={city}
                        onChange={(e) => setCity(e.target.value)}
                        required
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      />
                    </div>
                  </div>

                  <div className="grid sm:grid-cols-2 gap-3">
                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">Province *</label>
                      <select
                        value={province}
                        onChange={(e) => setProvince(e.target.value)}
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      >
                        {PROVINCES.map((p) => (
                          <option key={p} value={p}>{p}</option>
                        ))}
                      </select>
                    </div>

                    <div>
                      <label className="block text-[11px] font-bold text-slate-600 mb-1">Postal Code</label>
                      <input
                        type="text"
                        placeholder="e.g. 2196"
                        value={postalCode}
                        onChange={(e) => setPostalCode(e.target.value)}
                        className="w-full px-3 py-2 text-xs bg-slate-50 border border-slate-300 rounded-xl focus:bg-white focus:ring-1 focus:ring-blue-900"
                      />
                    </div>
                  </div>
                </div>

                {/* Shipping Method Selection */}
                <div className="space-y-3 pt-2 border-t border-slate-200">
                  <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                    <Truck className="w-4 h-4 text-blue-900" />
                    <span>3. Courier Delivery Method</span>
                  </h3>

                  <div className="space-y-2">
                    <label
                      onClick={() => setShippingMethod("standard")}
                      className={`p-3 rounded-2xl border flex items-center justify-between cursor-pointer transition-all ${
                        shippingMethod === "standard"
                          ? "border-amber-500 bg-amber-50/50 ring-1 ring-amber-500"
                          : "border-slate-200 bg-slate-50 hover:bg-slate-100"
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-4 h-4 rounded-full border border-slate-400 flex items-center justify-center">
                          {shippingMethod === "standard" && <div className="w-2 h-2 rounded-full bg-amber-600" />}
                        </div>
                        <div>
                          <div className="font-bold text-xs text-slate-900">Standard Door Courier (The Courier Guy / Aramex)</div>
                          <div className="text-[11px] text-slate-500">Delivered in 24 to 48 hours in major centers</div>
                        </div>
                      </div>
                      <span className="font-black text-xs text-slate-900">
                        {amountNeededForFreeShipping === 0 ? "FREE" : "R85.00"}
                      </span>
                    </label>

                    <label
                      onClick={() => setShippingMethod("express")}
                      className={`p-3 rounded-2xl border flex items-center justify-between cursor-pointer transition-all ${
                        shippingMethod === "express"
                          ? "border-amber-500 bg-amber-50/50 ring-1 ring-amber-500"
                          : "border-slate-200 bg-slate-50 hover:bg-slate-100"
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-4 h-4 rounded-full border border-slate-400 flex items-center justify-center">
                          {shippingMethod === "express" && <div className="w-2 h-2 rounded-full bg-amber-600" />}
                        </div>
                        <div>
                          <div className="font-bold text-xs text-slate-900">Priority Overnight Express</div>
                          <div className="text-[11px] text-slate-500">Next business day morning dispatch</div>
                        </div>
                      </div>
                      <span className="font-black text-xs text-slate-900">R145.00</span>
                    </label>

                    <label
                      onClick={() => setShippingMethod("pickup")}
                      className={`p-3 rounded-2xl border flex items-center justify-between cursor-pointer transition-all ${
                        shippingMethod === "pickup"
                          ? "border-amber-500 bg-amber-50/50 ring-1 ring-amber-500"
                          : "border-slate-200 bg-slate-50 hover:bg-slate-100"
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div className="w-4 h-4 rounded-full border border-slate-400 flex items-center justify-center">
                          {shippingMethod === "pickup" && <div className="w-2 h-2 rounded-full bg-amber-600" />}
                        </div>
                        <div>
                          <div className="font-bold text-xs text-slate-900">Self Pickup (Johannesburg Distribution Hub)</div>
                          <div className="text-[11px] text-slate-500">Collect free from Midrand Hub</div>
                        </div>
                      </div>
                      <span className="font-black text-xs text-emerald-700">FREE</span>
                    </label>
                  </div>
                </div>

                {/* Payment Gateway Options */}
                <div className="space-y-3 pt-2 border-t border-slate-200">
                  <h3 className="font-bold text-slate-900 text-sm flex items-center gap-2">
                    <CreditCard className="w-4 h-4 text-blue-900" />
                    <span>4. Payment Option</span>
                  </h3>

                  <div className="grid grid-cols-2 gap-3">
                    <button
                      type="button"
                      onClick={() => setPaymentMethod("ozow")}
                      className={`p-3 rounded-2xl border text-left transition-all cursor-pointer ${
                        paymentMethod === "ozow"
                          ? "border-amber-500 bg-amber-500/10 ring-2 ring-amber-500/50"
                          : "border-slate-200 bg-slate-50"
                      }`}
                    >
                      <div className="font-bold text-xs text-slate-900">Ozow Instant EFT</div>
                      <div className="text-[10px] text-slate-500">Capitec, FNB, Absa, Standard Bank, Nedbank</div>
                    </button>

                    <button
                      type="button"
                      onClick={() => setPaymentMethod("card")}
                      className={`p-3 rounded-2xl border text-left transition-all cursor-pointer ${
                        paymentMethod === "card"
                          ? "border-amber-500 bg-amber-500/10 ring-2 ring-amber-500/50"
                          : "border-slate-200 bg-slate-50"
                      }`}
                    >
                      <div className="font-bold text-xs text-slate-900">Card (Visa / Mastercard)</div>
                      <div className="text-[10px] text-slate-500">Safe 3D Secure Card Payment</div>
                    </button>
                  </div>
                </div>
              </div>

              {/* Right Column Order Summary */}
              <div className="lg:col-span-5 bg-slate-50 p-5 rounded-3xl border border-slate-200 flex flex-col justify-between space-y-4">
                <div>
                  <h3 className="font-extrabold text-slate-900 text-base border-b border-slate-200 pb-3 mb-3">
                    Order Summary ({cart.length} items)
                  </h3>

                  <div className="space-y-3 max-h-56 overflow-y-auto pr-1">
                    {cart.map((c) => {
                      const p = typeof c.product.price === "number" ? c.product.price : parseFloat(c.product.price);
                      return (
                        <div key={c.product.id} className="flex items-center gap-3 text-xs">
                          <img
                            src={c.product.image}
                            alt=""
                            className="w-12 h-12 object-cover rounded-lg border border-slate-200 bg-white"
                          />
                          <div className="flex-1 min-w-0">
                            <div className="font-bold text-slate-900 truncate">{c.product.name}</div>
                            <div className="text-[11px] text-slate-500">Qty: {c.quantity} &bull; R{p.toFixed(2)} each</div>
                          </div>
                          <span className="font-black text-slate-950">R{(p * c.quantity).toFixed(2)}</span>
                        </div>
                      );
                    })}
                  </div>

                  {/* Pricing breakdown */}
                  <div className="space-y-2 text-xs pt-4 border-t border-slate-200 text-slate-700 mt-4">
                    <div className="flex justify-between">
                      <span>Items Subtotal</span>
                      <span className="font-semibold">R{subtotal.toFixed(2)}</span>
                    </div>

                    {discountAmount > 0 && (
                      <div className="flex justify-between text-emerald-700 font-bold">
                        <span>Discount Voucher</span>
                        <span>-R{discountAmount.toFixed(2)}</span>
                      </div>
                    )}

                    <div className="flex justify-between">
                      <span>Courier Shipping</span>
                      <span className="font-semibold">{shippingCost === 0 ? "FREE" : `R${shippingCost.toFixed(2)}`}</span>
                    </div>

                    <div className="flex justify-between text-[11px] text-slate-500">
                      <span>Included SA 15% VAT</span>
                      <span>R{vatAmount.toFixed(2)}</span>
                    </div>

                    <div className="flex justify-between text-base font-black text-slate-950 pt-2 border-t border-slate-200">
                      <span>Grand Total (ZAR)</span>
                      <span className="text-blue-950 text-xl">R{finalTotal.toFixed(2)}</span>
                    </div>
                  </div>
                </div>

                <div className="space-y-3 pt-2">
                  <button
                    type="submit"
                    disabled={isSubmitting}
                    className="w-full py-4 bg-gradient-to-r from-emerald-600 to-emerald-700 hover:from-emerald-700 hover:to-emerald-800 text-white font-extrabold text-sm rounded-2xl shadow-lg transition-all flex items-center justify-center gap-2 cursor-pointer"
                  >
                    {isSubmitting ? (
                      <span className="animate-pulse">Processing Order...</span>
                    ) : (
                      <>
                        <ShieldCheck className="w-5 h-5 text-amber-300" />
                        <span>PLACE ORDER & PAY R{finalTotal.toFixed(2)}</span>
                      </>
                    )}
                  </button>

                  <p className="text-[10px] text-slate-500 text-center font-medium">
                    🔒 By placing this order, you agree to Diverse Stationery Terms & Conditions. An official VAT Tax Invoice will be emailed to {email || "your address"}.
                  </p>
                </div>
              </div>
            </form>
          </div>
        ) : (
          /* Order Success Confirmation screen */
          <div className="p-8 text-center space-y-6 max-w-2xl mx-auto">
            <div className="w-20 h-20 rounded-full bg-emerald-100 text-emerald-600 flex items-center justify-center mx-auto animate-bounce">
              <CheckCircle2 className="w-10 h-10" />
            </div>

            <div>
              <span className="text-xs font-bold text-emerald-700 uppercase tracking-wider bg-emerald-100 px-3 py-1 rounded-full">
                Payment Received & Confirmed
              </span>
              <h2 className="text-2xl sm:text-3xl font-black text-slate-900 mt-3">
                Thank You for Your Order!
              </h2>
              <p className="text-sm text-slate-600 mt-1">
                Your order reference is <strong className="text-blue-950 font-mono text-base">{completedOrder?.orderId || "DS-84920"}</strong>.
              </p>
            </div>

            <div className="p-5 bg-slate-50 rounded-3xl border border-slate-200 text-left text-xs space-y-2 text-slate-700">
              <div className="flex justify-between border-b border-slate-200 pb-2 font-bold text-slate-900">
                <span>Tax Invoice Details</span>
                <span>Diverse Stationery Co. SA</span>
              </div>
              <p><strong>Customer:</strong> {customerName}</p>
              <p><strong>Delivery Address:</strong> {street}, {suburb ? `${suburb}, ` : ""}{city}, {province}</p>
              <p><strong>Method:</strong> {shippingMethod === "express" ? "Priority Overnight Courier" : "Standard Door Courier Guy"}</p>
              <p><strong>Amount Paid:</strong> R{finalTotal.toFixed(2)} (Incl VAT)</p>
            </div>

            <div className="flex flex-col sm:flex-row items-center justify-center gap-3 pt-2">
              <button
                onClick={() => {
                  setIsCheckoutOpen(false);
                  setIsTrackerOpen(true);
                }}
                className="w-full sm:w-auto px-6 py-3 bg-blue-950 text-white font-extrabold text-xs rounded-xl hover:bg-slate-900 transition-colors flex items-center justify-center gap-2"
              >
                <Package className="w-4 h-4 text-amber-400" />
                <span>Track Order {completedOrder?.orderId}</span>
              </button>

              <button
                onClick={() => setIsCheckoutOpen(false)}
                className="w-full sm:w-auto px-6 py-3 bg-slate-200 text-slate-800 font-extrabold text-xs rounded-xl hover:bg-slate-300 transition-colors"
              >
                Continue Shopping
              </button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
};
