"use client";
import { useState, useCallback } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import {
  Shield,
  Lock,
  ChevronRight,
  MapPin,
  Package,
  CreditCard,
  Truck,
  Edit3,
  Check,
  X,
  AlertCircle,
  Star,
  Percent,
} from "lucide-react";
import { usePayment } from "@/lib/PaymentContext";
import { CHECKOUT_ITEM } from "./mockData";
import { useFormatPrice } from "@/hooks/useFormatPrice";
import type { BuyerInfo, PaymentMethod } from "./types";

// ─── PayPal SVG ───────────────────────────────────────────────────────────────
function PayPalLogo() {
  return (
    <svg width="60" height="16" viewBox="0 0 60 16" fill="none">
      <text x="0" y="13" fontFamily="Arial" fontSize="14" fontWeight="700" fill="#003087">Pay</text>
      <text x="22" y="13" fontFamily="Arial" fontSize="14" fontWeight="700" fill="#009cde">Pal</text>
    </svg>
  );
}

// ─── Step indicator ───────────────────────────────────────────────────────────
const STEPS = ["Review", "Payment", "Confirm"];

function StepBar({ step }: { step: number }) {
  return (
    <div className="flex items-center justify-center gap-0 mb-8">
      {STEPS.map((label, i) => (
        <div key={label} className="flex items-center">
          <div className="flex flex-col items-center gap-1">
            <motion.div
              animate={{
                background: i <= step ? "var(--accent)" : "rgba(255,255,255,0.1)",
                borderColor: i <= step ? "var(--accent)" : "rgba(255,255,255,0.2)",
              }}
              className="w-8 h-8 rounded-full flex items-center justify-center border-2 text-xs font-bold"
              style={{
                color: i <= step ? "#fff" : "var(--text-muted)",
              }}
            >
              {i < step ? <Check size={14} /> : i + 1}
            </motion.div>
            <span
              className="text-[10px] font-medium whitespace-nowrap"
              style={{ color: i <= step ? "var(--text-primary)" : "var(--text-muted)" }}
            >
              {label}
            </span>
          </div>
          {i < STEPS.length - 1 && (
            <div
              className="w-16 h-0.5 mx-2 mb-5"
              style={{ background: i < step ? "var(--accent)" : "rgba(255,255,255,0.1)" }}
            />
          )}
        </div>
      ))}
    </div>
  );
}

// ─── Secure badge row ─────────────────────────────────────────────────────────
function TrustBar() {
  return (
    <div className="flex items-center justify-center flex-wrap gap-4 py-3 px-4 rounded-xl mb-6"
      style={{ background: "rgba(34,197,94,0.06)", border: "1px solid rgba(34,197,94,0.15)" }}>
      {[
        { icon: Shield, text: "Buyer Protection" },
        { icon: Lock, text: "SSL Encrypted" },
        { icon: Star, text: "Verified Sellers" },
      ].map(({ icon: Icon, text }) => (
        <div key={text} className="flex items-center gap-1.5">
          <Icon size={13} className="text-green-400 shrink-0" />
          <span className="text-[11px] font-medium text-green-400">{text}</span>
        </div>
      ))}
    </div>
  );
}

// ─── Buyer info editable card ─────────────────────────────────────────────────
function BuyerCard({ info, onUpdate }: { info: BuyerInfo; onUpdate: (i: BuyerInfo) => void }) {
  const [editing, setEditing] = useState(false);
  const [draft, setDraft] = useState<BuyerInfo>(info);

  const save = () => {
    onUpdate(draft);
    setEditing(false);
  };

  return (
    <div className="rounded-2xl overflow-hidden border border-[var(--border)]" style={{ background: "var(--card)" }}>
      <div className="flex items-center justify-between px-5 py-4 border-b border-[var(--border)]">
        <div className="flex items-center gap-2">
          <MapPin size={15} className="text-[var(--accent)]" />
          <span className="font-semibold text-sm text-[var(--text-primary)]">Delivery & Contact</span>
        </div>
        <button
          onClick={() => setEditing(!editing)}
          className="flex items-center gap-1 text-xs text-[var(--accent)] hover:opacity-80 transition-opacity"
        >
          {editing ? <X size={13} /> : <Edit3 size={13} />}
          {editing ? "Cancel" : "Edit"}
        </button>
      </div>

      <AnimatePresence mode="wait">
        {editing ? (
          <motion.div
            key="edit"
            initial={{ opacity: 0, y: -8 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -8 }}
            className="p-5 space-y-3"
          >
            {(["name", "email", "phone", "address", "city", "pincode"] as const).map((field) => (
              <div key={field}>
                <label className="text-[10px] text-[var(--text-muted)] uppercase tracking-wide font-semibold mb-1 block">
                  {field === "pincode" ? "PIN Code" : field.charAt(0).toUpperCase() + field.slice(1)}
                </label>
                <input
                  value={draft[field]}
                  onChange={(e) => setDraft((p) => ({ ...p, [field]: e.target.value }))}
                  className="w-full px-3 py-2.5 rounded-xl text-sm outline-none text-[var(--text-primary)] placeholder:text-[var(--text-muted)]"
                  style={{ background: "var(--deep)", border: "1px solid var(--border)" }}
                />
              </div>
            ))}
            <motion.button
              whileTap={{ scale: 0.97 }}
              onClick={save}
              className="w-full py-2.5 rounded-xl text-sm font-semibold text-white mt-2"
              style={{ background: "var(--accent)" }}
            >
              Save Details
            </motion.button>
          </motion.div>
        ) : (
          <motion.div
            key="view"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            className="p-5 space-y-2"
          >
            <p className="font-semibold text-sm text-[var(--text-primary)]">{info.name}</p>
            <p className="text-sm text-[var(--text-muted)]">{info.email}</p>
            <p className="text-sm text-[var(--text-muted)]">{info.phone}</p>
            <p className="text-sm text-[var(--text-muted)]">
              {info.address}, {info.city} — {info.pincode}
            </p>
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

// ─── Payment method selector ──────────────────────────────────────────────────
interface MethodCardProps {
  method: PaymentMethod;
  selected: boolean;
  onSelect: () => void;
}

function MethodCard({ method, selected, onSelect }: MethodCardProps) {
  const isPayPal = method === "paypal";

  return (
    <motion.button
      whileTap={{ scale: 0.98 }}
      onClick={onSelect}
      className="w-full text-left rounded-2xl p-5 transition-all relative overflow-hidden border-2"
      style={{
        background: selected ? "rgba(252,0,0,0.06)" : "var(--card)",
        borderColor: selected ? "var(--accent)" : "var(--border)",
      }}
    >
      {selected && (
        <motion.div
          layoutId="method-glow"
          className="absolute inset-0 rounded-2xl pointer-events-none"
          style={{
            background: "radial-gradient(ellipse at top left, rgba(252,0,0,0.08) 0%, transparent 70%)",
          }}
        />
      )}

      <div className="flex items-start gap-4 relative z-10">
        {/* Icon */}
        <div
          className="w-12 h-12 rounded-xl flex items-center justify-center shrink-0"
          style={{
            background: isPayPal ? "#003087" : "rgba(255,255,255,0.06)",
          }}
        >
          {isPayPal ? (
            <span className="text-white font-black text-sm">PP</span>
          ) : (
            <Truck size={20} className="text-[var(--text-muted)]" />
          )}
        </div>

        <div className="flex-1 min-w-0">
          <div className="flex items-center justify-between mb-1">
            <span className="font-bold text-sm text-[var(--text-primary)]">
              {isPayPal ? "Pay with PayPal" : "Cash on Delivery"}
            </span>
            <div
              className="w-5 h-5 rounded-full border-2 flex items-center justify-center shrink-0 transition-all"
              style={{
                borderColor: selected ? "var(--accent)" : "rgba(255,255,255,0.2)",
                background: selected ? "var(--accent)" : "transparent",
              }}
            >
              {selected && <Check size={11} className="text-white" />}
            </div>
          </div>

          <p className="text-xs text-[var(--text-muted)] leading-relaxed">
            {isPayPal
              ? "Secure payment via PayPal. Buyer protection included. Pay now and we'll escrow the funds until delivery."
              : "Pay cash when you receive the item. Inspect before paying. Seller must confirm payment after receiving cash."}
          </p>

          <div className="flex items-center gap-2 mt-2.5">
            {isPayPal ? (
              <>
                <span className="text-[10px] px-2 py-0.5 rounded-full font-medium bg-blue-500/10 text-blue-400">
                  Instant
                </span>
                <span className="text-[10px] px-2 py-0.5 rounded-full font-medium bg-green-500/10 text-green-400">
                  Protected
                </span>
              </>
            ) : (
              <>
                <span className="text-[10px] px-2 py-0.5 rounded-full font-medium bg-orange-500/10 text-orange-400">
                  No Online Risk
                </span>
                <span className="text-[10px] px-2 py-0.5 rounded-full font-medium bg-yellow-500/10 text-yellow-400">
                  Inspect First
                </span>
              </>
            )}
          </div>
        </div>
      </div>
    </motion.button>
  );
}

// ─── Order summary card ───────────────────────────────────────────────────────
function OrderSummary({ item }: { item: typeof CHECKOUT_ITEM }) {
  const formatPrice = useFormatPrice();
  return (
    <div className="rounded-2xl overflow-hidden border border-[var(--border)]" style={{ background: "var(--card)" }}>
      {/* Product */}
      <div className="flex gap-4 p-5 border-b border-[var(--border)]">
        <div className="relative shrink-0">
          <img
            src={item.listingImage}
            alt={item.listingTitle}
            className="w-20 h-20 rounded-xl object-cover"
          />
          <span
            className="absolute -top-1.5 -right-1.5 text-[9px] px-1.5 py-0.5 rounded-full font-semibold"
            style={{ background: "var(--accent)", color: "#fff" }}
          >
            {item.listingCondition}
          </span>
        </div>
        <div className="flex-1 min-w-0">
          <p className="font-semibold text-sm text-[var(--text-primary)] leading-tight mb-1 line-clamp-2">
            {item.listingTitle}
          </p>
          <div className="flex items-center gap-2 mb-2">
            <img src={item.sellerAvatar} alt="" className="w-5 h-5 rounded-full object-cover" />
            <span className="text-xs text-[var(--text-muted)]">{item.sellerName}</span>
            {item.sellerVerified && (
              <span className="text-[9px] bg-[var(--accent)]/15 text-[var(--accent)] px-1 rounded font-medium">✓</span>
            )}
          </div>
          <div className="flex items-center gap-2">
            <Package size={11} className="text-[var(--text-muted)]" />
            <span className="text-xs text-[var(--text-muted)]">Qty: {item.quantity}</span>
          </div>
        </div>
      </div>

      {/* Price breakdown */}
      <div className="p-5 space-y-2.5">
        {[
          { label: "Item Price", value: item.listingPrice, muted: false },
          { label: "Service Fee (1%)", value: item.serviceFee, muted: true },
          { label: "Delivery", value: item.deliveryFee, muted: true, prefix: item.deliveryFee === 0 ? "FREE" : null },
          { label: "Tax (GST 18%)", value: item.tax, muted: true },
          ...(item.discount > 0 ? [{ label: "Discount", value: -item.discount, muted: true }] : []),
        ].map(({ label, value, muted, prefix }) => (
          <div key={label} className="flex items-center justify-between">
            <span className="text-xs text-[var(--text-muted)]">{label}</span>
            <span className={`text-xs font-medium ${value < 0 ? "text-green-400" : muted ? "text-[var(--text-muted)]" : "text-[var(--text-primary)]"}`}>
              {prefix ?? (value < 0 ? `-${formatPrice(-value)}` : formatPrice(value))}
            </span>
          </div>
        ))}

        <div className="pt-2 border-t border-[var(--border)]">
          <div className="flex items-center justify-between">
            <span className="font-bold text-sm text-[var(--text-primary)]">Total Payable</span>
            <span className="font-black text-lg text-[var(--accent)]">
              {formatPrice(item.totalAmount)}
            </span>
          </div>
        </div>

        <div
          className="flex items-center gap-2 px-3 py-2 rounded-xl mt-1"
          style={{ background: "rgba(34,197,94,0.06)", border: "1px solid rgba(34,197,94,0.15)" }}
        >
          <Shield size={12} className="text-green-400 shrink-0" />
          <span className="text-[10px] text-green-400">
            Your payment is protected by Doliplay Buyer Guarantee
          </span>
        </div>
      </div>
    </div>
  );
}

// ─── Main CheckoutPage ────────────────────────────────────────────────────────
export function CheckoutPage() {
  const router = useRouter();
  const formatPrice = useFormatPrice();
  const { selectedMethod, selectPaymentMethod, updateBuyerInfo, placeOrder, buyerInfo } = usePayment();
  const [step, setStep] = useState(0);
  const [placing, setPlacing] = useState(false);
  const item = CHECKOUT_ITEM;

  const handlePay = useCallback(async () => {
    setPlacing(true);
    await new Promise((r) => setTimeout(r, 800));
    const order = placeOrder();
    if (!order) { setPlacing(false); return; }

    if (selectedMethod === "paypal") {
      router.push("/marketplace/payment/pending");
    } else {
      router.push("/marketplace/payment/success?method=cod");
    }
  }, [selectedMethod, placeOrder, router]);

  return (
    <div className="min-h-full pb-28 md:pb-8" style={{ background: "var(--bg)" }}>
      <div className="max-w-6xl mx-auto px-4 py-6">
        {/* Header */}
        <div className="text-center mb-6">
          <div className="flex items-center justify-center gap-2 mb-1">
            <Lock size={14} className="text-green-400" />
            <span className="text-xs text-green-400 font-medium">Secure Checkout</span>
          </div>
          <h1 className="text-xl font-black text-[var(--text-primary)]">Complete Your Order</h1>
        </div>

        <StepBar step={step} />
        <TrustBar />

        <div className="grid grid-cols-1 lg:grid-cols-[1fr_400px] gap-6">
          {/* Left column */}
          <div className="space-y-5">
            {/* Buyer info */}
            <div>
              <h2 className="text-sm font-bold text-[var(--text-primary)] mb-3 flex items-center gap-2">
                <span className="w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-black text-white" style={{ background: "var(--accent)" }}>1</span>
                Delivery Details
              </h2>
              <BuyerCard info={buyerInfo} onUpdate={updateBuyerInfo} />
            </div>

            {/* Payment method */}
            <div>
              <h2 className="text-sm font-bold text-[var(--text-primary)] mb-3 flex items-center gap-2">
                <span className="w-6 h-6 rounded-full flex items-center justify-center text-[11px] font-black text-white" style={{ background: "var(--accent)" }}>2</span>
                Payment Method
              </h2>
              <div className="space-y-3">
                <MethodCard
                  method="paypal"
                  selected={selectedMethod === "paypal"}
                  onSelect={() => { selectPaymentMethod("paypal"); setStep(1); }}
                />
                <MethodCard
                  method="cod"
                  selected={selectedMethod === "cod"}
                  onSelect={() => { selectPaymentMethod("cod"); setStep(1); }}
                />
              </div>
            </div>

            {/* COD notice */}
            <AnimatePresence>
              {selectedMethod === "cod" && (
                <motion.div
                  initial={{ opacity: 0, y: -8 }}
                  animate={{ opacity: 1, y: 0 }}
                  exit={{ opacity: 0, y: -8 }}
                  className="flex gap-3 p-4 rounded-xl"
                  style={{ background: "rgba(251,146,60,0.08)", border: "1px solid rgba(251,146,60,0.2)" }}
                >
                  <AlertCircle size={15} className="text-orange-400 shrink-0 mt-0.5" />
                  <div>
                    <p className="text-xs font-semibold text-orange-400 mb-1">Cash on Delivery Info</p>
                    <p className="text-xs text-[var(--text-muted)] leading-relaxed">
                      Arrange a meeting with the seller. Inspect the item thoroughly before paying. The seller must confirm receipt of payment to complete the order.
                    </p>
                  </div>
                </motion.div>
              )}
            </AnimatePresence>

            {/* Desktop order summary (hidden on mobile, shown in right col on desktop) */}
            <div className="lg:hidden">
              <OrderSummary item={item} />
            </div>
          </div>

          {/* Right column — sticky on desktop */}
          <div className="hidden lg:block">
            <div className="sticky top-20 space-y-4">
              <OrderSummary item={item} />

              {/* Pay button (desktop) */}
              <motion.button
                whileTap={{ scale: 0.97 }}
                onClick={handlePay}
                disabled={placing}
                className="w-full py-4 rounded-2xl text-white font-bold text-sm relative overflow-hidden disabled:opacity-70"
                style={{
                  background: selectedMethod === "paypal"
                    ? "linear-gradient(135deg, #003087, #009cde)"
                    : "linear-gradient(135deg, var(--accent), #ff4040)",
                  boxShadow: "0 8px 24px rgba(0,0,0,0.3)",
                }}
              >
                {placing ? (
                  <span className="flex items-center justify-center gap-2">
                    <motion.span
                      className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full"
                      animate={{ rotate: 360 }}
                      transition={{ duration: 0.8, repeat: Infinity, ease: "linear" }}
                    />
                    Processing...
                  </span>
                ) : selectedMethod === "paypal" ? (
                  <span className="flex items-center justify-center gap-2">
                    <Lock size={14} />
                    Continue to PayPal
                  </span>
                ) : (
                  <span className="flex items-center justify-center gap-2">
                    <Package size={14} />
                    Place COD Order
                  </span>
                )}
              </motion.button>

              <p className="text-center text-[10px] text-[var(--text-muted)]">
                By placing your order you agree to our Terms of Service and Privacy Policy.
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* Mobile sticky pay bar */}
      <motion.div
        initial={{ y: 100 }}
        animate={{ y: 0 }}
        className="lg:hidden fixed bottom-16 left-0 right-0 z-30 px-4 py-3 border-t border-[var(--border)]"
        style={{ background: "var(--card)", backdropFilter: "blur(12px)" }}
      >
        <div className="flex items-center justify-between mb-2">
          <span className="text-xs text-[var(--text-muted)]">Total</span>
          <span className="text-lg font-black text-[var(--accent)]">
            {formatPrice(item.totalAmount)}
          </span>
        </div>
        <motion.button
          whileTap={{ scale: 0.97 }}
          onClick={handlePay}
          disabled={placing}
          className="w-full py-3.5 rounded-xl text-white font-bold text-sm"
          style={{
            background: selectedMethod === "paypal"
              ? "linear-gradient(135deg, #003087, #009cde)"
              : "linear-gradient(135deg, var(--accent), #ff4040)",
            boxShadow: "0 6px 20px rgba(0,0,0,0.3)",
          }}
        >
          {placing ? "Processing..." : selectedMethod === "paypal" ? "Continue to PayPal →" : "Place COD Order →"}
        </motion.button>
      </motion.div>
    </div>
  );
}
