"use client";

import { useState } from "react";
import type { Payment, VaBank } from "@/types/order";

// Official Midtrans-hosted logo assets (same static files Snap itself uses),
// content-hashed filenames so they're safe to reference directly — see
// snap-assets.midtrans.com in the Snap payment-method list.
const MIDTRANS_ASSETS = "https://snap-assets.midtrans.com/snap/v4/assets";
const QRIS_LOGO = `${MIDTRANS_ASSETS}/qris-5ab65ea8ea12e00daee664042ed976a75c574fcd2fb1acd04e6cfc773d9bda54.svg`;

const VA_BANKS: { value: VaBank; label: string; logo: string }[] = [
  { value: "bca", label: "BCA", logo: `${MIDTRANS_ASSETS}/bca-906e4db60303060666c5a10498c5a749962311037cf45e4f73866e9138dd9805.svg` },
  { value: "bni", label: "BNI", logo: `${MIDTRANS_ASSETS}/bni-163d98085f5fe9df4068b91d64c50f5e5b347ca2ee306d27954e37b424ec4863.svg` },
  { value: "bri", label: "BRI", logo: `${MIDTRANS_ASSETS}/bri-39f5d44b1c42e70ad089fc52b909ef410d708d563119eb0da3a6abd49c4a595c.svg` },
  { value: "permata", label: "Permata", logo: `${MIDTRANS_ASSETS}/permata-b9fb2fe16efa8dab34e60b85e07c9b18e72c5dc97178351ec3c0c4f4af926102.svg` },
];

/**
 * Lets the customer pick QRIS or a bank's Virtual Account, then charges
 * Core API via `POST /api/checkout/{orderId}/pay` — the custom-UI
 * replacement for opening Midtrans's Snap widget. Calls `onCharged` with the
 * resulting Payment (VA number / QR URL / expiry) once the charge succeeds.
 */
export function PaymentMethodSelector({
  orderId,
  onCharged,
}: {
  orderId: number;
  onCharged: (payment: Payment) => void;
}) {
  const [bank, setBank] = useState<VaBank | null>(null);
  const [isCharging, setIsCharging] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function charge(method: "qris" | "bank_transfer", selectedBank?: VaBank) {
    setError(null);
    setIsCharging(true);

    try {
      const res = await fetch(`/api/checkout/${orderId}/pay`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ method, bank: selectedBank }),
      });

      const body = await res.json().catch(() => null);

      if (!res.ok) {
        setError(body?.errors?.midtrans?.[0] ?? body?.errors?.order?.[0] ?? body?.message ?? "Failed to process payment.");
        return;
      }

      onCharged(body.data as Payment);
    } catch {
      setError("Unable to reach the server. Please check your connection and try again.");
    } finally {
      setIsCharging(false);
    }
  }

  return (
    <div className="flex flex-col gap-4">
      <button
        type="button"
        onClick={() => charge("qris")}
        disabled={isCharging}
        className="flex items-center justify-between rounded-xl border border-neutral-200 bg-white px-4 py-3 text-left transition-colors hover:bg-neutral-50 disabled:cursor-not-allowed disabled:opacity-50"
      >
        <div className="flex items-center gap-3">
          {/* eslint-disable-next-line @next/next/no-img-element -- external Midtrans-hosted logo, not a local asset */}
          <img src={QRIS_LOGO} alt="QRIS" className="h-8 w-8 shrink-0 object-contain" />
          <div>
            <p className="font-medium">QRIS</p>
            <p className="text-sm text-neutral-500">Scan with GoPay, OVO, Dana, or any m-banking app.</p>
          </div>
        </div>
        {isCharging && <span className="text-sm text-neutral-400">Processing...</span>}
      </button>

      <div className="rounded-xl border border-neutral-200 bg-white p-4">
        <p className="font-medium">Bank Transfer (Virtual Account)</p>
        <p className="mt-1 text-sm text-neutral-500">Choose a bank to get a VA number.</p>
        <div className="mt-3 grid grid-cols-2 gap-2 sm:grid-cols-4">
          {VA_BANKS.map((b) => (
            <button
              key={b.value}
              type="button"
              onClick={() => {
                setBank(b.value);
                charge("bank_transfer", b.value);
              }}
              disabled={isCharging}
              className="flex flex-col items-center gap-2 rounded-lg border border-neutral-200 px-3 py-3 text-sm font-medium transition-colors hover:bg-neutral-50 disabled:cursor-not-allowed disabled:opacity-50"
            >
              {/* eslint-disable-next-line @next/next/no-img-element -- external Midtrans-hosted logo, not a local asset */}
              <img src={b.logo} alt={b.label} className="h-6 w-auto max-w-full object-contain" />
              {isCharging && bank === b.value ? "..." : b.label}
            </button>
          ))}
        </div>
      </div>

      {error && <p className="text-sm text-red-600">{error}</p>}
    </div>
  );
}
