"use client";

import { useState } from "react";

type PayButtonProps = {
  children: React.ReactNode;
  size?: "sm" | "md" | "lg";
  className?: string;
  channel?: "alipay" | "wxpay";
};

const sizeClasses = {
  sm: "px-3 py-1.5 text-xs sm:px-4 sm:py-2 sm:text-sm",
  md: "px-5 py-2.5 text-base",
  lg: "px-8 py-4 text-lg sm:px-10",
};

export function PayButton({ children, size = "md", className = "", channel = "alipay" }: PayButtonProps) {
  const [loading, setLoading] = useState(false);

  const handlePay = () => {
    if (loading) return;
    setLoading(true);
    const form = document.createElement("form");
    form.method = "POST";
    form.action = "/api/pay";
    form.style.display = "none";

    const fields = {
      user_id: `user_${Date.now()}`,
      return_url: typeof window !== "undefined" ? `${window.location.origin}/pay/paid` : "",
      total_fee: 80,
      type: "meetup",
      channel,
      html: "1",
    };

    for (const [k, v] of Object.entries(fields)) {
      const input = document.createElement("input");
      input.name = k;
      input.value = String(v);
      form.appendChild(input);
    }

    document.body.appendChild(form);
    form.submit();
  };

  return (
    <button
      type="button"
      onClick={handlePay}
      disabled={loading}
      className={`inline-flex items-center justify-center gap-2 rounded-full bg-[var(--accent)] font-medium text-[var(--accent-foreground)] transition hover:opacity-90 disabled:opacity-70 ${sizeClasses[size]} ${className}`}
    >
      {loading ? "跳转中..." : children}
    </button>
  );
}
