'use client';

import { useMemo, useState } from 'react';
import { BookmakerCode, generateBetSlipUrl } from '@/lib/betting-utils';

const logoMap: Record<BookmakerCode, string> = {
  bet365: 'Bet365',
  pinnacle: 'Pinnacle',
  draftkings: 'DraftKings',
};

type 球員道具盤 = {
  bookmakerId: BookmakerCode;
  matchId: string;
  selection: string;
  odds: number;
  disabled?: boolean;
};

export function QuickBetButton({ bookmakerId, matchId, selection, odds, disabled = false }: 球員道具盤) {
  const [isRedirecting, setIsRedirecting] = useState(false);

  const label = logoMap[bookmakerId];
  const oddsText = odds.toFixed(2);

  const href = useMemo(
    () =>
      generateBetSlipUrl({
        bookmakerId,
        matchId,
        selection,
        odds,
      }),
    [bookmakerId, matchId, selection, odds],
  );
  const isUnavailable = disabled || !href;

  const handleClick = () => {
    if (disabled || !href) {
      return;
    }
    setIsRedirecting(true);
    window.open(href, '_blank', 'noopener,noreferrer');
    window.setTimeout(() => setIsRedirecting(false), 900);
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={isUnavailable}
      title={href ? '開啟已驗證投注平台連結' : '尚未接入合法且可驗證的投注平台一鍵帶入連結'}
      className={`group relative inline-flex min-w-40 items-center justify-center rounded-full bg-[#7d2a15] px-4 py-2 text-sm text-white transition ${
        isUnavailable ? 'cursor-not-allowed opacity-60' : 'hover:bg-[#5f1f11]'
      }`}
    >
      <span className="dot-matrix text-sm">{!href ? `${label} 待接入` : isRedirecting ? '帶入中...' : `${label} ${oddsText}`}</span>
      {!isRedirecting ? (
        <span className="absolute -top-1 -right-2 hidden rounded-full bg-[#d1432d] px-2 py-0.5 text-[10px] text-white transition group-hover:inline">{oddsText}</span>
      ) : null}
      {isRedirecting ? (
        <span className="dot-matrix ml-2 inline-block dot-matrix-loading text-[10px]">10110</span>
      ) : null}
    </button>
  );
}
