"use client";

import { useState } from "react";

type Package = {
  id: string;
  name: string;
  budgetBonus: number;
  price: number;
  description: string | null;
};

const ICONS: Record<string, string> = {
  "pkg-silver": "🥈",
  "pkg-gold": "🥇",
  "pkg-diamond": "💎",
};

export default function ShopClient({ packages }: { packages: Package[] }) {
  const [loading, setLoading] = useState<string | null>(null);

  async function handleBuy(packageId: string) {
    setLoading(packageId);
    const res = await fetch("/api/payment/request", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ packageId }),
    });
    const data = await res.json();
    if (res.ok && data.paymentUrl) {
      window.location.href = data.paymentUrl;
    } else {
      alert(data.error ?? "خطا در اتصال به درگاه");
      setLoading(null);
    }
  }

  return (
    <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
      {packages.map((pkg) => (
        <div key={pkg.id}
          className={`bg-white rounded-2xl shadow-lg p-6 flex flex-col items-center text-center border-2 transition hover:shadow-xl ${
            pkg.id === "pkg-gold" ? "border-yellow-400 scale-105" : "border-transparent"
          }`}>
          {pkg.id === "pkg-gold" && (
            <div className="bg-yellow-400 text-yellow-900 text-xs font-bold px-3 py-1 rounded-full mb-3">
              محبوب‌ترین
            </div>
          )}
          <div className="text-5xl mb-4">{ICONS[pkg.id] ?? "📦"}</div>
          <h3 className="text-xl font-bold mb-2">{pkg.name}</h3>
          <p className="text-gray-500 text-sm mb-4">{pkg.description}</p>
          <div className="bg-green-50 rounded-xl px-6 py-3 mb-6 w-full">
            <div className="text-3xl font-bold text-green-700">+{pkg.budgetBonus}M</div>
            <div className="text-xs text-gray-500">افزایش بودجه</div>
          </div>
          <div className="text-2xl font-bold mb-4">
            {pkg.price.toLocaleString("fa-IR")} تومان
          </div>
          <button
            onClick={() => handleBuy(pkg.id)}
            disabled={loading === pkg.id}
            className={`w-full py-3 rounded-xl font-bold transition disabled:opacity-50 ${
              pkg.id === "pkg-gold"
                ? "bg-yellow-400 text-yellow-900 hover:bg-yellow-500"
                : "bg-green-700 text-white hover:bg-green-800"
            }`}
          >
            {loading === pkg.id ? "در حال اتصال..." : "خرید"}
          </button>
        </div>
      ))}
    </div>
  );
}
