'use client';

import React, { useState } from 'react';
import { Gift, X, Coins } from 'lucide-react';
import { apiRequest, idempotencyKey } from '../lib/api';
import { Button } from './Button';
import { formatCoins } from '../lib/coins';

export function SignupBonusModal({
  amount,
  onClose,
  onClaimed,
}: {
  amount: number;
  onClose: () => void;
  onClaimed: () => void;
}) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  const claim = async () => {
    setBusy(true);
    setError('');
    try {
      await apiRequest('/wallet/claim-signup-bonus', {
        method: 'POST',
        idempotencyKey: idempotencyKey('bonus'),
      });
      onClaimed();
      onClose();
    } catch (e: any) {
      setError(e.message || 'Could not claim bonus');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="fixed inset-0 z-[60] flex items-end justify-center bg-black/50 p-4 sm:items-center">
      <div
        role="dialog"
        aria-modal="true"
        aria-labelledby="bonus-title"
        className="relative w-full max-w-sm overflow-hidden rounded-3xl bg-white shadow-xl"
      >
        <button
          type="button"
          onClick={onClose}
          className="absolute right-3 top-3 z-10 rounded-full bg-black/10 p-1.5 text-gray-700 hover:bg-black/15"
          aria-label="Close"
        >
          <X className="h-4 w-4" />
        </button>
        <div className="bg-gradient-to-br from-d11-red to-rose-700 px-6 pb-8 pt-10 text-center text-white">
          <div className="mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-white/20">
            <Gift className="h-7 w-7" />
          </div>
          <h2 id="bonus-title" className="font-display text-2xl font-extrabold">
            Claim your bonus
          </h2>
          <p className="mt-2 text-sm text-white/85">Welcome gift for joining MY11s</p>
          <p className="mt-4 inline-flex items-center justify-center gap-2 font-display text-4xl font-extrabold">
            <Coins className="h-8 w-8 text-amber-300" aria-hidden />
            {formatCoins(amount, { suffix: false })}
          </p>
          <p className="mt-1 text-xs text-white/70">Coins added to your bonus wallet</p>
        </div>
        <div className="space-y-3 p-5">
          {error && <p className="text-center text-xs text-d11-red">{error}</p>}
          <Button className="w-full rounded-xl" loading={busy} onClick={claim}>
            Claim now
          </Button>
          <button
            type="button"
            onClick={onClose}
            className="w-full text-center text-xs font-semibold text-d11-muted hover:text-d11-ink"
          >
            Maybe later
          </button>
        </div>
      </div>
    </div>
  );
}
