'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 Props = {
  bookmakerId: BookmakerCode;
  matchId: string;
  selection: string;
  odds: number;
  disabled?: boolean;
};

export function QuickBetButton({ bookmakerId, matchId, selection, odds, disabled = false }: Props) {
  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 handleClick = () => {
    if (disabled) {
      return;
    }
    setIsRedirecting(true);
    window.open(href, '_blank', 'noopener,noreferrer');
    window.setTimeout(() => setIsRedirecting(false), 900);
  };

  return (
    <button
      type="button"
      onClick={handleClick}
      disabled={disabled}
      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 ${
        disabled ? 'cursor-not-allowed opacity-60' : 'hover:bg-[#5f1f11]'
      }`}
    >
      <span className="dot-matrix text-sm">{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>
  );
}
