"use client";

import { useEffect, useState, useCallback } from "react";
import {
  X,
  ShieldCheck,
  CheckCircle2,
  AlertCircle,
  ChevronRight,
  Loader2,
} from "lucide-react";
import {
  paymentService,
  GATEWAY_DISPLAY,
  type PaymentOption,
} from "@/services/paymentService";
import { PayPalCheckout } from "@/components/payment/PayPalButtons";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";

/* ── Context types ──────────────────────────────────────────────────────────── */

export type PaymentContext =
  | {
      type: "subscription";
      packageId: string;
      packageName: string;
      price: number;
    }
  | {
      type: "coin";
      packageId: string;
      packageName: string;
      price: number;
      coin: number;
    }
  | { type: "rent"; contentId: string; contentName: string; price: number };

export interface PaymentModalProps {
  context: PaymentContext | null;
  onClose: () => void;
  onSuccess?: () => void;
}

/* ── Flow states ────────────────────────────────────────────────────────────── */

type FlowState =
  | "loading"
  | "select"
  | "paypal"
  | "processing"
  | "recording"
  | "success"
  | "error";

/* ── Gateway icon (SVG paths) ───────────────────────────────────────────────── */

function GatewayIcon({ name, color }: { name: string; color: string }) {
  const s = { width: 20, height: 20 };
  switch (name) {
    case "paypal":
      return (
        <svg {...s} viewBox="0 0 24 24" fill={color}>
          <path d="M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.26-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.565-5.946.36-1.847.174-3.388-.777-4.477z" />
        </svg>
      );
    case "stripe":
      return (
        <svg {...s} viewBox="0 0 24 24" fill={color}>
          <path d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.594-7.305h.003z" />
        </svg>
      );
    case "razorpay":
      return (
        <svg {...s} viewBox="0 0 24 24" fill={color}>
          <path d="M22.586 0L13.81 8.167l2.075 4.959L24 4.777zM15.69 11.863L9.586 0 0 24h6.917l4.308-9.569 4.773-2.135-.308-.433z" />
        </svg>
      );
    default:
      return (
        <div
          className="w-5 h-5 rounded-md flex items-center justify-center text-[10px] font-black"
          style={{ background: color, color: "#fff" }}
        >
          {name.slice(0, 1).toUpperCase()}
        </div>
      );
  }
}

/* ── Method card ────────────────────────────────────────────────────────────── */

function MethodCard({
  option,
  selected,
  onClick,
}: {
  option: PaymentOption;
  selected: boolean;
  onClick: () => void;
}) {
  const cfg = GATEWAY_DISPLAY[option.name] ?? {
    label: option.displayName,
    color: "#888",
    bg: "var(--btn-ghost-hover)",
  };

  return (
    <button
      type="button"
      onClick={onClick}
      className="relative flex flex-col items-center gap-2.5 p-3.5 rounded-xl transition-all duration-200 active:scale-95 text-center w-full"
      style={{
        background: selected ? cfg.bg : "var(--btn-ghost)",
        border: `1.5px solid ${selected ? cfg.color : "var(--border)"}`,
        boxShadow: selected
          ? `0 0 16px ${cfg.color}25, 0 4px 12px rgba(0,0,0,0.3)`
          : "none",
      }}
    >
      {selected && (
        <div
          className="absolute top-2 right-2 w-4 h-4 rounded-full flex items-center justify-center"
          style={{ background: cfg.color }}
        >
          <CheckCircle2 size={10} color="#fff" strokeWidth={2.5} />
        </div>
      )}
      <div
        className="w-10 h-10 rounded-xl flex items-center justify-center"
        style={{
          background: selected ? `${cfg.color}20` : "var(--border-soft)",
        }}
      >
        <GatewayIcon name={option.name} color={selected ? cfg.color : "#888"} />
      </div>
      <span
        className="text-[11px] font-bold leading-tight"
        style={{ color: selected ? cfg.color : "#aaa" }}
      >
        {cfg.label}
      </span>
      {!option.isLive && (
        <span
          className="text-[8px] font-semibold px-1.5 py-0.5 rounded"
          style={{ background: "rgba(245,158,11,0.12)", color: "#f59e0b" }}
        >
          TEST
        </span>
      )}
    </button>
  );
}

/* ── Order summary strip ────────────────────────────────────────────────────── */

function OrderSummary({ ctx }: { ctx: PaymentContext }) {
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";
  const label =
    ctx.type === "subscription"
      ? ctx.packageName
      : ctx.type === "coin"
        ? `${ctx.packageName} — ${ctx.coin.toLocaleString()} coins`
        : ctx.contentName;
  const badge =
    ctx.type === "subscription"
      ? "PLAN"
      : ctx.type === "coin"
        ? "COINS"
        : "RENT";
  const badgeColor =
    ctx.type === "subscription"
      ? "#a855f7"
      : ctx.type === "coin"
        ? "#f59e0b"
        : "#22d3ee";

  return (
    <div
      className="flex items-center justify-between gap-3 px-4 py-3 rounded-xl"
      style={{
        background: "var(--btn-ghost)",
        border: "1px solid var(--border-soft)",
      }}
    >
      <div className="flex items-center gap-2.5 min-w-0">
        <span
          className="text-[9px] font-black px-2 py-1 rounded tracking-widest flex-shrink-0"
          style={{ background: `${badgeColor}15`, color: badgeColor }}
        >
          {badge}
        </span>
        <span
          className="text-[12px] font-medium truncate"
          style={{ color: "var(--text-primary)" }}
        >
          {label}
        </span>
      </div>
      <span
        className="text-base font-black flex-shrink-0"
        style={{
          fontVariantNumeric: "tabular-nums",
          color: "var(--text-primary)",
        }}
      >
        {sym}
        {ctx.price}
      </span>
    </div>
  );
}

/* ── Step indicator ─────────────────────────────────────────────────────────── */

function Steps({ step }: { step: 1 | 2 | 3 }) {
  const steps = ["Select", "Authorize", "Done"];
  return (
    <div className="flex items-center gap-0 mb-5">
      {steps.map((s, i) => {
        const n = i + 1;
        const done = step > n;
        const active = step === n;
        return (
          <div key={s} className="flex items-center flex-1">
            <div className="flex flex-col items-center gap-1">
              <div
                className="w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-black transition-all duration-300"
                style={{
                  background: done
                    ? "#10b981"
                    : active
                      ? "var(--accent)"
                      : "var(--btn-ghost-hover)",
                  color: done || active ? "#fff" : "var(--text-muted)",
                }}
              >
                {done ? "✓" : n}
              </div>
              <span
                className="text-[9px] font-semibold"
                style={{
                  color: active
                    ? "var(--accent)"
                    : done
                      ? "#10b981"
                      : "var(--text-muted)",
                }}
              >
                {s}
              </span>
            </div>
            {i < steps.length - 1 && (
              <div
                className="flex-1 h-px mx-2 mb-4 transition-all duration-500"
                style={{
                  background: done ? "#10b981" : "var(--border)",
                }}
              />
            )}
          </div>
        );
      })}
    </div>
  );
}

/* ── Main modal ─────────────────────────────────────────────────────────────── */

export function PaymentModal({
  context,
  onClose,
  onSuccess,
}: PaymentModalProps) {
  const [options, setOptions] = useState<PaymentOption[]>([]);
  const [selected, setSelected] = useState<PaymentOption | null>(null);
  const [flow, setFlow] = useState<FlowState>("loading");
  const [errorMsg, setErrorMsg] = useState("");
  const { settings: gSettings } = useGeneralSettings();
  const sym = gSettings?.currencySymbol ?? "$";

  const isOpen = !!context;

  useEffect(() => {
    if (!isOpen) return;
    setFlow("loading");
    setSelected(null);
    setErrorMsg("");
    paymentService
      .getOptions()
      .then((opts) => {
        setOptions(opts);
        setFlow("select");
      })
      .catch(() => {
        setFlow("error");
        setErrorMsg("Failed to load payment methods.");
      });
  }, [isOpen]);

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

  const recordTransaction = useCallback(
    async (txnId: string) => {
      if (!context) return;
      setFlow("recording");
      try {
        if (context.type === "subscription") {
          await paymentService.addTransaction({
            packageId: context.packageId,
            price: context.price,
            transactionId: txnId,
            description: `Subscribed to ${context.packageName}`,
          });
        } else if (context.type === "coin") {
          await paymentService.addCoinTransaction({
            packageId: context.packageId,
            price: context.price,
            coin: context.coin,
            transactionId: txnId,
            description: `Purchased ${context.packageName}`,
          });
        } else if (context.type === "rent") {
          await paymentService.addRentTransaction({
            contentId: context.contentId,
            price: context.price,
            transactionId: txnId,
            description: `Rented: ${context.contentName}`,
          });
        }
        setFlow("success");
        onSuccess?.();
      } catch {
        setFlow("error");
        setErrorMsg("Transaction recording failed. Please contact support.");
      }
    },
    [context, onSuccess],
  );

  const handleProceed = useCallback(async () => {
    if (!selected || !context) return;

    if (selected.name === "paypal") {
      setFlow("paypal");
      return;
    }

    setFlow("processing");
    await new Promise((r) => setTimeout(r, 2200));
    const txnId = paymentService.generateTxnId(selected.name);
    await recordTransaction(txnId);
  }, [selected, context, recordTransaction]);

  if (!isOpen) return null;

  const selectedCfg = selected
    ? (GATEWAY_DISPLAY[selected.name] ?? { color: "var(--accent)", bg: "" })
    : null;
  const step: 1 | 2 | 3 = flow === "select" ? 1 : flow === "success" ? 3 : 2;

  const paypalOption = options.find((o) => o.name === "paypal");

  return (
    <>
      {/* Backdrop */}
      <div
        className="fixed inset-0 z-[120]"
        style={{
          background: "rgba(0,0,0,0.78)",
          backdropFilter: "blur(10px)",
          animation: "pay-fade 0.22s ease both",
        }}
        onClick={flow === "select" ? onClose : undefined}
      />

      {/* Modal */}
      <div
        className="fixed z-[121] flex flex-col overflow-hidden"
        style={{
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          width: "min(480px, 94vw)",
          maxHeight: "min(640px, 90vh)",
          background: "var(--card)",
          borderRadius: 20,
          border: "1px solid var(--border)",
          boxShadow:
            "0 0 0 1px var(--border-soft) inset, 0 32px 96px rgba(0,0,0,0.5)",
          animation: "pay-scale 0.3s cubic-bezier(0.34,1.4,0.64,1) both",
        }}
      >
        {/* Header */}
        <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">
            <ShieldCheck size={16} color="#10b981" strokeWidth={1.8} />
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              Secure Checkout
            </span>
          </div>
          {flow === "select" && (
            <button
              onClick={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">
          <Steps step={step} />

          {/* Order summary */}
          {context && <OrderSummary ctx={context} />}

          {/* ── Loading ── */}
          {flow === "loading" && (
            <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" }}>
                Loading payment methods…
              </p>
            </div>
          )}

          {/* ── Select method ── */}
          {flow === "select" && (
            <div className="mt-4">
              <p
                className="text-[11px] font-bold uppercase tracking-widest mb-3"
                style={{ color: "#555" }}
              >
                Choose Payment Method
              </p>
              <div className="grid grid-cols-3 gap-2.5">
                {options.map((opt) => (
                  <MethodCard
                    key={opt.id}
                    option={opt}
                    selected={selected?.id === opt.id}
                    onClick={() => setSelected(opt)}
                  />
                ))}
              </div>
            </div>
          )}

          {/* ── PayPal native flow ── */}
          {flow === "paypal" && (
            <div className="mt-4 flex flex-col gap-4">
              <p
                className="text-[11px] font-bold uppercase tracking-widest"
                style={{ color: "#555" }}
              >
                Pay with PayPal
              </p>
              <PayPalCheckout
                clientId={paypalOption?.publicKey ?? ""}
                amount={context?.price ?? 0}
                currency={gSettings?.currencyCode ?? "USD"}
                onSuccess={(captureId) => recordTransaction(captureId)}
                onError={(msg) => {
                  setFlow("error");
                  setErrorMsg(msg);
                }}
              />
              <button
                onClick={() => setFlow("select")}
                className="text-[11px] text-center transition-all"
                style={{ color: "#555" }}
              >
                ← Back to payment methods
              </button>
            </div>
          )}

          {/* ── Processing ── */}
          {(flow === "processing" || flow === "recording") && (
            <div className="flex flex-col items-center gap-5 py-10">
              <div className="relative w-20 h-20">
                <svg
                  width="80"
                  height="80"
                  viewBox="0 0 80 80"
                  className="-rotate-90"
                >
                  <circle
                    cx="40"
                    cy="40"
                    r="34"
                    fill="none"
                    strokeWidth="5"
                    style={{ stroke: "var(--border)" }}
                  />
                  <circle
                    cx="40"
                    cy="40"
                    r="34"
                    fill="none"
                    stroke={selectedCfg?.color ?? "var(--accent)"}
                    strokeWidth="5"
                    strokeLinecap="round"
                    strokeDasharray={`${2 * Math.PI * 34}`}
                    strokeDashoffset={
                      flow === "recording" ? "0" : `${2 * Math.PI * 34 * 0.25}`
                    }
                    style={{ transition: "stroke-dashoffset 2s ease" }}
                    className={
                      flow === "processing" ? "animate-spin origin-center" : ""
                    }
                  />
                </svg>
                <div className="absolute inset-0 flex items-center justify-center">
                  {selected && (
                    <GatewayIcon
                      name={selected.name}
                      color={selectedCfg?.color ?? "#888"}
                    />
                  )}
                </div>
              </div>
              <div className="text-center">
                <p
                  className="text-sm font-bold"
                  style={{ color: "var(--text-primary)" }}
                >
                  {flow === "processing"
                    ? `Connecting to ${selectedCfg?.label ?? "gateway"}…`
                    : "Recording transaction…"}
                </p>
                <p className="text-[11px] mt-1" style={{ color: "#555" }}>
                  {flow === "processing"
                    ? "Please wait, do not close this window"
                    : "Finalizing your payment…"}
                </p>
              </div>
            </div>
          )}

          {/* ── Success ── */}
          {flow === "success" && (
            <div
              className="flex flex-col items-center gap-4 py-10"
              style={{
                animation:
                  "pay-success 0.5s cubic-bezier(0.34,1.5,0.64,1) both",
              }}
            >
              <div
                className="w-18 h-18 rounded-full flex items-center justify-center"
                style={{
                  width: 72,
                  height: 72,
                  background: "rgba(16,185,129,0.1)",
                  border: "2px solid #10b981",
                  boxShadow: "0 0 30px rgba(16,185,129,0.2)",
                }}
              >
                <CheckCircle2 size={32} color="#10b981" strokeWidth={1.8} />
              </div>
              <div className="text-center">
                <p
                  className="text-base font-black"
                  style={{ color: "var(--text-primary)" }}
                >
                  Payment Successful!
                </p>
                <p className="text-[11px] mt-1" style={{ color: "#888" }}>
                  Your transaction has been recorded
                </p>
              </div>
              <button
                onClick={onClose}
                className="mt-2 px-8 py-2.5 rounded-xl text-[12px] font-bold text-[#ffffff] transition-all active:scale-95"
                style={{
                  background: "#10b981",
                  boxShadow: "0 4px 16px rgba(16,185,129,0.3)",
                }}
              >
                Done
              </button>
            </div>
          )}

          {/* ── Error ── */}
          {flow === "error" && (
            <div className="flex flex-col items-center gap-4 py-10">
              <div
                className="w-16 h-16 rounded-full flex items-center justify-center"
                style={{
                  background: "rgba(244,63,94,0.1)",
                  border: "2px solid #f43f5e",
                }}
              >
                <AlertCircle size={28} color="#f43f5e" strokeWidth={1.8} />
              </div>
              <div className="text-center">
                <p
                  className="text-sm font-bold"
                  style={{ color: "var(--text-primary)" }}
                >
                  Payment Failed
                </p>
                <p className="text-[11px] mt-1" style={{ color: "#888" }}>
                  {errorMsg}
                </p>
              </div>
              <div className="flex gap-3">
                <button
                  onClick={() => setFlow("select")}
                  className="px-5 py-2 rounded-xl text-[12px] font-bold transition-all active:scale-95"
                  style={{
                    background: "var(--btn-ghost-hover)",
                    color: "var(--text-primary)",
                  }}
                >
                  Try Again
                </button>
                <button
                  onClick={onClose}
                  className="px-5 py-2 rounded-xl text-[12px] font-semibold transition-all"
                  style={{ color: "#666" }}
                >
                  Cancel
                </button>
              </div>
            </div>
          )}
        </div>

        {/* Footer CTA — hidden during PayPal flow (PayPal renders its own buttons) */}
        {flow === "select" && (
          <div
            className="px-5 pb-5 pt-3 shrink-0"
            style={{ borderTop: "1px solid var(--border-soft)" }}
          >
            <button
              disabled={!selected}
              onClick={handleProceed}
              className="w-full h-12 rounded-xl text-[13px] font-black  flex items-center justify-center gap-2 transition-all duration-200 active:scale-[0.98] disabled:opacity-30 disabled:cursor-not-allowed"
              style={{
                color: "var(--text-muted)",
                background: selected
                  ? `linear-gradient(135deg, ${selectedCfg?.color}, ${selectedCfg?.color}cc)`
                  : "var(--btn-ghost-hover)",
                boxShadow: selected
                  ? `0 4px 20px ${selectedCfg?.color}35`
                  : "none",
              }}
            >
              {selected ? (
                <>
                  Pay {sym}
                  {context?.price} via {selectedCfg?.label}
                  <ChevronRight size={16} strokeWidth={2.5} />
                </>
              ) : (
                "Select a payment method"
              )}
            </button>
            <div className="flex items-center justify-center gap-1.5 mt-2.5">
              <ShieldCheck size={10} color="#555" />
              <span className="text-[9px]" style={{ color: "#444" }}>
                256-bit SSL encrypted · Secure checkout
              </span>
            </div>
          </div>
        )}
      </div>
    </>
  );
}
