"use client";

import { useState } from "react";
import { useRouter } from "next/navigation";
import {
  reconcileMidtransPaymentAction,
  startMidtransPaymentAction,
} from "@/features/booking/actions";

interface SnapCallbacks {
  onSuccess?: (result: unknown) => void;
  onPending?: (result: unknown) => void;
  onError?: (result: unknown) => void;
  onClose?: () => void;
}

interface SnapApi {
  pay: (token: string, callbacks?: SnapCallbacks) => void;
}

declare global {
  interface Window {
    snap?: SnapApi;
  }
}

const SCRIPT_ID = "midtrans-snap-script";

function loadSnapScript(snapJsUrl: string, clientKey: string): Promise<void> {
  return new Promise((resolve, reject) => {
    if (typeof window === "undefined") {
      reject(new Error("Snap hanya bisa dimuat di browser"));
      return;
    }
    if (window.snap) {
      resolve();
      return;
    }
    const existing = document.getElementById(SCRIPT_ID);
    if (existing) {
      existing.addEventListener("load", () => resolve());
      existing.addEventListener("error", () =>
        reject(new Error("Gagal memuat Snap.js"))
      );
      return;
    }
    const script = document.createElement("script");
    script.id = SCRIPT_ID;
    script.src = snapJsUrl;
    script.async = true;
    script.setAttribute("data-client-key", clientKey);
    script.onload = () => resolve();
    script.onerror = () => reject(new Error("Gagal memuat Snap.js"));
    document.body.appendChild(script);
  });
}

interface MidtransPayButtonProps {
  tripId: string;
}

export function MidtransPayButton({ tripId }: MidtransPayButtonProps) {
  const router = useRouter();
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState("");

  async function handleClick() {
    setLoading(true);
    setError("");

    const result = await startMidtransPaymentAction(tripId);
    if ("error" in result) {
      setError(result.error);
      setLoading(false);
      return;
    }

    try {
      await loadSnapScript(result.snapJsUrl, result.clientKey);
    } catch (e) {
      setError(e instanceof Error ? e.message : "Gagal memuat pembayaran");
      setLoading(false);
      return;
    }

    if (!window.snap) {
      setError("Snap belum siap, refresh halaman dan coba lagi");
      setLoading(false);
      return;
    }

    const orderId = result.orderId;
    // Tarik status terkini dari Midtrans server-side, lalu refresh halaman.
    // Tidak menunggu webhook supaya UI ter-update saat webhook belum sampai
    // (mis. di localhost) atau redirect flow di mana popup tidak dipakai.
    async function reconcileAndRefresh() {
      await reconcileMidtransPaymentAction(orderId);
      router.refresh();
    }

    window.snap.pay(result.snapToken, {
      onSuccess: reconcileAndRefresh,
      onPending: reconcileAndRefresh,
      onError: () => {
        setError(
          "Pembayaran gagal diproses. Coba lagi atau pakai metode lain."
        );
        void reconcileAndRefresh();
      },
      onClose: reconcileAndRefresh,
    });

    setLoading(false);
  }

  return (
    <div>
      {error && (
        <div className="mb-3 rounded-xl bg-red-50 px-4 py-3 text-sm font-medium text-red-600">
          {error}
        </div>
      )}
      <button
        type="button"
        onClick={handleClick}
        disabled={loading}
        className="w-full rounded-xl bg-secondary-600 py-3 text-sm font-bold text-white shadow-lg shadow-secondary-600/20 transition-colors hover:bg-secondary-700 disabled:cursor-not-allowed disabled:opacity-50"
      >
        {loading ? "Memuat Snap..." : "Bayar online via Midtrans"}
      </button>
      <p className="mt-2 text-center text-[11px] text-neutral-500">
        Bayar pakai BCA VA, GoPay, QRIS, kartu, dan lainnya. Status terupdate
        otomatis setelah pembayaran terkonfirmasi gateway.
      </p>
    </div>
  );
}
