"use client";

import { useEffect, useState } from "react";
import {
  X,
  ShieldCheck,
  Loader2,
  AlertCircle,
  MapPin,
  Minus,
  Plus,
  ArrowLeft,
  CheckCircle,
  PackageCheck,
} from "lucide-react";
import { paymentService } from "@/services/paymentService";
import { profileService } from "@/services/profileService";
import {
  orderService,
  isPaymentBypassEnabled,
  makeTestTransactionId,
  type MarketplaceOrder,
} from "@/services/orderService";
import { PayPalCheckout } from "@/components/payment/PayPalButtons";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import { useAppSelector } from "@/store/hooks";

export interface BuyNowListing {
  id: string;
  title: string;
  price: number;
  image?: string;
  /** Stock from get_listing_detail — caps the quantity selector. */
  availableQuantity?: number;
}

interface BuyNowModalProps {
  listing: BuyNowListing | null;
  onClose: () => void;
  onSuccess: (orderId: number) => void;
  onError: (message: string) => void;
}

interface AddressForm {
  address: string;
  city: string;
  state: string;
  country: string;
  pincode: string;
}

const MAX_QTY = 10;

export function BuyNowModal({
  listing,
  onClose,
  onSuccess,
  onError,
}: BuyNowModalProps) {
  const [clientId, setClientId] = useState("");
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [step, setStep] = useState<"form" | "payment" | "done">("form");
  const [quantity, setQuantity] = useState(1);
  const [form, setForm] = useState<AddressForm>({
    address: "",
    city: "",
    state: "",
    country: "",
    pincode: "",
  });
  const [formError, setFormError] = useState("");
  const [placing, setPlacing] = useState(false);
  const [confirming, setConfirming] = useState(false);
  const [order, setOrder] = useState<MarketplaceOrder | null>(null);
  const [cancelNotice, setCancelNotice] = useState("");
  const [savedAddress, setSavedAddress] = useState<AddressForm | null>(null);

  const { settings } = useGeneralSettings();
  const authUser = useAppSelector((s) => s.auth.user);
  const sym = settings?.currencySymbol ?? "$";
  const isOpen = !!listing;
  const total = (listing?.price ?? 0) * quantity;
  const maxQty = Math.min(
    MAX_QTY,
    Math.max(1, listing?.availableQuantity ?? MAX_QTY),
  );

  /* Reset + prefill whenever the modal opens */
  useEffect(() => {
    if (!isOpen) return;
    setStep("form");
    setQuantity(1);
    setOrder(null);
    setFormError("");
    setCancelNotice("");
    setForm((f) => ({
      ...f,
      city: authUser?.city ?? f.city,
      state: authUser?.state ?? f.state,
    }));
    setSavedAddress(null);
    profileService
      .getProfile()
      .then((res) => {
        const p = res.result?.[0];
        if (
          p?.address?.trim() &&
          p?.city?.trim() &&
          p?.state?.trim() &&
          p?.country?.trim() &&
          Number(p?.pincode) > 0
        ) {
          setSavedAddress({
            address: p.address.trim(),
            city: p.city.trim(),
            state: p.state.trim(),
            country: p.country.trim(),
            pincode: String(p.pincode),
          });
        }
      })
      .catch(() => {
        // saved address is optional — the form still works without it
      });
    setLoading(true);
    setLoadError("");
    paymentService
      .getOptions()
      .then((opts) => {
        const paypal = opts.find((o) => o.name === "paypal");
        if (!paypal?.publicKey) {
          setLoadError("PayPal is not configured. Please try again later.");
        } else {
          setClientId(paypal.publicKey);
        }
      })
      .catch(() => setLoadError("Failed to load PayPal checkout."))
      .finally(() => setLoading(false));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return;
    document.body.style.overflow = "hidden";
    return () => {
      document.body.style.overflow = "";
    };
  }, [isOpen]);

  if (!isOpen || !listing) return null;

  const setField = (key: keyof AddressForm, value: string) => {
    setForm((f) => ({ ...f, [key]: value }));
    setFormError("");
  };

  const handleContinue = async () => {
    const missing = (
      ["address", "city", "state", "country", "pincode"] as const
    ).filter((k) => !form[k].trim());
    if (missing.length > 0) {
      setFormError("Please fill in all delivery address fields.");
      return;
    }
    if (!/^\d{4,10}$/.test(form.pincode.trim())) {
      setFormError("Please enter a valid pincode.");
      return;
    }
    if (quantity > maxQty) {
      setFormError(`Only ${maxQty} unit${maxQty > 1 ? "s" : ""} available.`);
      return;
    }
    setPlacing(true);
    setFormError("");
    try {
      const created = await orderService.initiateOrder({
        listingId: listing.id,
        quantity,
        address: form.address.trim(),
        city: form.city.trim(),
        state: form.state.trim(),
        country: form.country.trim(),
        pincode: form.pincode.trim(),
      });
      setOrder(created);
      setStep("payment");
    } catch (err) {
      setFormError(
        err instanceof Error && err.message
          ? err.message
          : "Could not place the order. Please try again.",
      );
    } finally {
      setPlacing(false);
    }
  };

  const handlePayPalSuccess = async (captureId: string) => {
    if (!order) return;
    setConfirming(true);
    try {
      await orderService.confirmOrderPayment(order.id, 1, captureId);
    } catch {
      // Payment was captured — the backend will reconcile via transaction id.
    }
    setConfirming(false);
    setStep("done");
    window.setTimeout(() => onSuccess(order.id), 1500);
  };

  const handlePayPalError = async (message: string) => {
    if (message === "Payment cancelled") {
      // Keep the order pending so the buyer can retry from this modal.
      setCancelNotice("Payment was cancelled. You can try again below.");
      return;
    }
    if (order) {
      try {
        await orderService.confirmOrderPayment(order.id, 2);
      } catch {
        // best effort — order stays payment-pending on the backend
      }
    }
    onError(message);
  };

  const inputStyle: React.CSSProperties = {
    background: "var(--btn-ghost)",
    border: "1px solid var(--border-soft)",
    color: "var(--text-primary)",
  };

  return (
    <>
      <div
        className="fixed inset-0 z-[120]"
        style={{ background: "rgba(0,0,0,0.78)", backdropFilter: "blur(10px)" }}
        onClick={confirming || step === "done" ? undefined : onClose}
      />
      <div
        className="fixed z-[121] flex flex-col overflow-hidden"
        style={{
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: "min(440px, 94vw)",
          maxHeight: "min(640px, 90vh)",
          background: "var(--card)",
          borderRadius: 20,
          border: "1px solid var(--border)",
          boxShadow: "0 32px 96px rgba(0,0,0,0.5)",
        }}
      >
        <div
          className="flex items-center justify-between px-5 pt-5 pb-4 shrink-0"
          style={{ borderBottom: "1px solid var(--border-soft)" }}
        >
          <div className="flex items-center gap-2">
            {step === "payment" && !confirming && (
              <button
                onClick={() => {
                  setStep("form");
                  setCancelNotice("");
                }}
                className="w-6 h-6 rounded-full flex items-center justify-center transition-all hover:brightness-125"
                style={{ background: "var(--btn-ghost-hover)" }}
              >
                <ArrowLeft size={12} color="#888" />
              </button>
            )}
            <ShieldCheck size={16} color="#10b981" strokeWidth={1.8} />
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {step === "form"
                ? "Buy It Now"
                : step === "payment"
                  ? "Secure Payment"
                  : "Order Confirmed"}
            </span>
          </div>
          {step !== "done" && (
            <button
              onClick={confirming ? undefined : onClose}
              className="w-7 h-7 rounded-full flex items-center justify-center transition-all hover:brightness-125"
              style={{ background: "var(--btn-ghost-hover)" }}
            >
              <X size={13} color="#888" />
            </button>
          )}
        </div>

        <div className="flex-1 overflow-y-auto scrollbar-thin px-5 py-4">
          {/* Item summary */}
          <div
            className="flex items-center gap-3 px-4 py-3 rounded-xl mb-4"
            style={{
              background: "var(--btn-ghost)",
              border: "1px solid var(--border-soft)",
            }}
          >
            {listing.image && (
              <img
                src={listing.image}
                alt={listing.title}
                className="w-12 h-12 rounded-lg object-cover shrink-0"
              />
            )}
            <div className="min-w-0 flex-1">
              <p
                className="text-[12px] font-semibold truncate"
                style={{ color: "var(--text-primary)" }}
              >
                {listing.title}
              </p>
              <p className="text-[10px]" style={{ color: "var(--text-muted)" }}>
                Qty: {quantity} · {sym}
                {listing.price.toLocaleString()} each
              </p>
            </div>
            <span
              className="text-base font-black shrink-0"
              style={{ color: "var(--text-primary)" }}
            >
              {sym}
              {total.toLocaleString()}
            </span>
          </div>

          {step === "form" && (
            <>
              {/* Quantity */}
              <div className="flex items-center justify-between mb-4">
                <div>
                  <span
                    className="text-xs font-semibold"
                    style={{ color: "var(--text-primary)" }}
                  >
                    Quantity
                  </span>
                  {listing.availableQuantity !== undefined && (
                    <p
                      className="text-[10px] mt-0.5"
                      style={{
                        color:
                          listing.availableQuantity <= 3
                            ? "#f59e0b"
                            : "var(--text-muted)",
                      }}
                    >
                      {listing.availableQuantity} available
                    </p>
                  )}
                </div>
                <div
                  className="flex items-center gap-3 rounded-xl px-2 py-1.5"
                  style={{
                    background: "var(--btn-ghost)",
                    border: "1px solid var(--border-soft)",
                  }}
                >
                  <button
                    onClick={() => setQuantity((q) => Math.max(1, q - 1))}
                    disabled={quantity <= 1}
                    className="w-6 h-6 rounded-lg flex items-center justify-center disabled:opacity-30"
                    style={{ background: "var(--btn-ghost-hover)" }}
                  >
                    <Minus size={11} color="#888" />
                  </button>
                  <span
                    className="text-sm font-bold w-6 text-center"
                    style={{ color: "var(--text-primary)" }}
                  >
                    {quantity}
                  </span>
                  <button
                    onClick={() => setQuantity((q) => Math.min(maxQty, q + 1))}
                    disabled={quantity >= maxQty}
                    className="w-6 h-6 rounded-lg flex items-center justify-center disabled:opacity-30"
                    style={{ background: "var(--btn-ghost-hover)" }}
                  >
                    <Plus size={11} color="#888" />
                  </button>
                </div>
              </div>

              {/* Delivery address */}
              <div className="flex items-center gap-1.5 mb-2">
                <MapPin size={12} color="var(--accent)" />
                <span
                  className="text-xs font-semibold"
                  style={{ color: "var(--text-primary)" }}
                >
                  Delivery Address
                </span>
                {savedAddress && (
                  <button
                    onClick={() => {
                      setForm(savedAddress);
                      setFormError("");
                    }}
                    className="ml-auto text-[10px] font-bold px-2.5 py-1 rounded-full transition-all hover:brightness-110"
                    style={{
                      background: "rgba(16,185,129,0.1)",
                      color: "#10b981",
                      border: "1px solid rgba(16,185,129,0.25)",
                    }}
                  >
                    Use saved address
                  </button>
                )}
              </div>
              <div className="space-y-2.5 mb-4">
                <input
                  value={form.address}
                  onChange={(e) => setField("address", e.target.value)}
                  placeholder="Street address / area"
                  className="w-full rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                  style={inputStyle}
                />
                <div className="grid grid-cols-2 gap-2.5">
                  <input
                    value={form.city}
                    onChange={(e) => setField("city", e.target.value)}
                    placeholder="City"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                  <input
                    value={form.state}
                    onChange={(e) => setField("state", e.target.value)}
                    placeholder="State"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                </div>
                <div className="grid grid-cols-2 gap-2.5">
                  <input
                    value={form.country}
                    onChange={(e) => setField("country", e.target.value)}
                    placeholder="Country"
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                  <input
                    value={form.pincode}
                    onChange={(e) =>
                      setField("pincode", e.target.value.replace(/\D/g, ""))
                    }
                    placeholder="Pincode"
                    inputMode="numeric"
                    maxLength={10}
                    className="rounded-xl px-3.5 py-2.5 text-[13px] outline-none"
                    style={inputStyle}
                  />
                </div>
              </div>

              {formError && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mb-3"
                  style={{
                    background: "rgba(244,63,94,0.08)",
                    color: "#f43f5e",
                    border: "1px solid rgba(244,63,94,0.15)",
                  }}
                >
                  <AlertCircle size={14} strokeWidth={1.8} className="shrink-0" />
                  {formError}
                </div>
              )}

              <button
                onClick={handleContinue}
                disabled={
                  placing ||
                  loading ||
                  (!!loadError && !isPaymentBypassEnabled())
                }
                className="w-full flex items-center justify-center gap-2 rounded-xl py-3 text-sm font-bold text-white transition-all hover:brightness-110 disabled:opacity-50"
                style={{ background: "var(--accent)" }}
              >
                {placing ? (
                  <>
                    <Loader2 size={15} className="animate-spin" />
                    Initiating order…
                  </>
                ) : (
                  <>
                    Initiate Order · {sym}
                    {total.toLocaleString()}
                  </>
                )}
              </button>

              {!loading && loadError && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mt-3"
                  style={{
                    background: "rgba(244,63,94,0.08)",
                    color: "#f43f5e",
                    border: "1px solid rgba(244,63,94,0.15)",
                  }}
                >
                  <AlertCircle size={14} strokeWidth={1.8} className="shrink-0" />
                  {loadError}
                </div>
              )}
            </>
          )}

          {step === "payment" && (
            <>
              {/* Order created banner */}
              {order && (
                <div
                  className="flex items-center gap-2.5 px-4 py-3 rounded-xl mb-4"
                  style={{
                    background: "rgba(16,185,129,0.08)",
                    border: "1px solid rgba(16,185,129,0.2)",
                  }}
                >
                  <PackageCheck size={16} color="#10b981" className="shrink-0" />
                  <div className="min-w-0">
                    <p
                      className="text-[12px] font-bold"
                      style={{ color: "#10b981" }}
                    >
                      Order #{order.id} initiated
                    </p>
                    <p
                      className="text-[10px]"
                      style={{ color: "var(--text-muted)" }}
                    >
                      Complete the payment below to confirm your order.
                    </p>
                  </div>
                </div>
              )}

              {/* Delivery summary */}
              <div
                className="flex items-start gap-2 px-4 py-3 rounded-xl mb-4"
                style={{
                  background: "var(--btn-ghost)",
                  border: "1px solid var(--border-soft)",
                }}
              >
                <MapPin
                  size={13}
                  color="var(--accent)"
                  className="mt-0.5 shrink-0"
                />
                <p
                  className="text-[11px] leading-relaxed"
                  style={{ color: "var(--text-muted)" }}
                >
                  {form.address}, {form.city}, {form.state}, {form.country} —{" "}
                  {form.pincode}
                </p>
              </div>

              {cancelNotice && (
                <div
                  className="flex items-center gap-2 py-2.5 px-4 rounded-xl text-[12px] mb-3"
                  style={{
                    background: "rgba(245,158,11,0.08)",
                    color: "#f59e0b",
                    border: "1px solid rgba(245,158,11,0.15)",
                  }}
                >
                  <AlertCircle size={14} strokeWidth={1.8} className="shrink-0" />
                  {cancelNotice}
                </div>
              )}

              {confirming ? (
                <div className="flex flex-col items-center gap-3 py-10">
                  <Loader2
                    size={28}
                    color="var(--accent)"
                    className="animate-spin"
                  />
                  <p className="text-xs" style={{ color: "#666" }}>
                    Confirming your payment…
                  </p>
                </div>
              ) : (
                <>
                  {clientId && (
                    <PayPalCheckout
                      clientId={clientId}
                      amount={total}
                      currency={settings?.currencyCode ?? "USD"}
                      itemName={listing.title}
                      quantity={quantity}
                      onSuccess={handlePayPalSuccess}
                      onError={handlePayPalError}
                    />
                  )}
                  {isPaymentBypassEnabled() && order && (
                    <button
                      onClick={() =>
                        handlePayPalSuccess(makeTestTransactionId(order.id))
                      }
                      className="w-full flex items-center justify-center gap-2 rounded-xl py-2.5 mt-3 text-xs font-bold transition-all hover:brightness-110"
                      style={{
                        background: "rgba(245,158,11,0.08)",
                        color: "#f59e0b",
                        border: "1px dashed rgba(245,158,11,0.4)",
                      }}
                    >
                      ⚡ Skip Payment (Test Mode)
                    </button>
                  )}
                </>
              )}
            </>
          )}

          {step === "done" && order && (
            <div className="flex flex-col items-center gap-3 py-8">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center"
                style={{ background: "rgba(16,185,129,0.12)" }}
              >
                <CheckCircle size={32} color="#10b981" />
              </div>
              <p
                className="text-sm font-bold"
                style={{ color: "var(--text-primary)" }}
              >
                Payment Confirmed!
              </p>
              <p
                className="text-[11px] text-center"
                style={{ color: "var(--text-muted)" }}
              >
                Order #{order.id} has been placed successfully.
                <br />
                Taking you to your order…
              </p>
              <Loader2
                size={16}
                color="var(--accent)"
                className="animate-spin"
              />
            </div>
          )}

          <div className="flex items-center justify-center gap-1.5 mt-4">
            <ShieldCheck size={10} color="#555" />
            <span className="text-[9px]" style={{ color: "#444" }}>
              256-bit SSL encrypted · Secure checkout via PayPal
            </span>
          </div>
        </div>
      </div>
    </>
  );
}
