import React, { useEffect, useState } from 'react';
import Dialog from '@mui/material/Dialog';
import { createTheme, ThemeProvider } from '@mui/material/styles';

const darkTheme = createTheme({ palette: { mode: 'dark' } });

const DIALOG_SX = {
  '& .MuiDialog-paper': {
    background: '#07090d',
    backgroundImage: `
      linear-gradient(rgba(35, 111, 135, 0.08) 1px, transparent 1px),
      linear-gradient(90deg, rgba(35, 111, 135, 0.08) 1px, transparent 1px)
    `,
    backgroundSize: '46px 46px',
    border: '1px solid rgba(35, 111, 135, 0.4)',
    borderRadius: '12px',
    boxShadow: '0 0 80px rgba(35, 111, 135, 0.15), 0 32px 80px rgba(0,0,0,0.9)',
    width: '580px',
    maxWidth: '94vw',
    overflow: 'hidden',
    color: '#fff',
  },
  '& .MuiBackdrop-root': {
    background: 'rgba(2, 4, 8, 0.88)',
    backdropFilter: 'blur(4px)',
  },
};

const RESULT_META = {
  win: {
    label: 'Victory',
    color: '#5ee89a',
    bg: 'rgba(42,158,96,0.15)',
    border: 'rgba(42,158,96,0.4)',
    icon: 'fa-trophy',
  },
  loss: {
    label: 'Defeated',
    color: '#f67d52',
    bg: 'rgba(173,10,5,0.15)',
    border: 'rgba(173,10,5,0.4)',
    icon: 'fa-flag',
  },
  draw: {
    label: 'Draw',
    color: '#95cff5',
    bg: 'rgba(149,207,245,0.1)',
    border: 'rgba(149,207,245,0.3)',
    icon: 'fa-minus',
  },
};

function Avatar({ name, color, avatarUrl, bonusPoints = 0 }) {
  const isRed = 'red' === color;
  const initials = (name || '?').slice(0, 2).toUpperCase();

  const gradient = isRed
    ? 'linear-gradient(135deg, rgba(173,10,5,0.6) 0%, rgba(246,125,82,0.4) 100%)'
    : 'linear-gradient(135deg, rgba(35,111,135,0.6) 0%, rgba(41,128,185,0.4) 100%)';
  const glow = isRed
    ? '0 0 0 3px rgba(173,10,5,0.2), 0 0 28px rgba(173,10,5,0.35)'
    : '0 0 0 3px rgba(35,111,135,0.2), 0 0 28px rgba(35,111,135,0.35)';
  const border = isRed
    ? 'rgba(173,10,5,0.5)'
    : 'rgba(35,111,135,0.5)';
  const textColor = isRed ? '#f67d52' : '#95cff5';

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, position: 'relative' }}>
      <div style={{ position: 'relative' }}>
        <div style={{
          width: 72, height: 72, borderRadius: '50%',
          background: avatarUrl ? 'transparent' : gradient,
          border: `2px solid ${border}`,
          boxShadow: glow,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          font: '800 24px \'Rajdhani\', sans-serif',
          color: textColor,
          letterSpacing: 2,
          overflow: 'hidden',
        }}
        >
          {avatarUrl ? (
            <img
              src={avatarUrl}
              alt={name}
              style={{
                width: '100%',
                height: '100%',
                objectFit: 'cover',
              }}
            />
          ) : (
            initials
          )}
        </div>
        {0 < bonusPoints && (
          <div style={{
            position: 'absolute',
            bottom: -6,
            right: -6,
            background: '#ffd700',
            borderRadius: '50%',
            width: 28,
            height: 28,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: '0 0 12px rgba(255, 215, 0, 0.6), 0 0 0 2px rgba(7, 9, 13, 1)',
            border: '2px solid rgba(0,0,0,0.5)',
            zIndex: 10,
          }}
          >
            <i className="fa fa-star" style={{ color: '#000', fontSize: 14 }} />
          </div>
        )}
      </div>
      <span style={{
        font: '700 15px \'Rajdhani\', sans-serif',
        color: textColor,
        letterSpacing: 1,
        maxWidth: 120, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        textAlign: 'center',
      }}
      >
        {name}
      </span>
      <span style={{
        font: '600 10px \'Rajdhani\', sans-serif',
        textTransform: 'uppercase',
        letterSpacing: 2,
        color: 'rgba(255,255,255,0.3)',
      }}
      >
        {isRed ? 'Red' : 'Blue'}
      </span>
    </div>
  );
}

function StatRow({ icon, label, value, valueColor }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center',
      gap: 10, padding: '9px 0',
      borderBottom: '1px solid rgba(255,255,255,0.05)',
    }}
    >
      <i className={`fa ${icon}`} style={{ width: 16, color: 'rgba(149,207,245,0.4)', fontSize: 13 }} />
      <span style={{
        font: '500 13px \'Rajdhani\', sans-serif',
        color: 'rgba(255,255,255,0.45)',
        flex: 1,
        letterSpacing: 0.5,
      }}
      >
        {label}
      </span>
      <span style={{
        font: '700 13px \'Rajdhani\', sans-serif',
        color: valueColor || 'rgba(255,255,255,0.75)',
        letterSpacing: 0.5,
      }}
      >
        {value}
      </span>
    </div>
  );
}

export default function BattleDialog({ games }) {
  const [open, setOpen] = useState(false);
  const [game, setGame] = useState(null);
  const [copied, setCopied] = useState(false);

  useEffect(() => {
    const handler = e => {
      const row = e.target.closest('[data-game-index]');
      if (!row) return;
      const idx = parseInt(row.dataset.gameIndex, 10);
      if (!isNaN(idx) && games[idx]) {
        setGame(games[idx]);
        setOpen(true);
      }
    };
    document.addEventListener('click', handler);
    return () => document.removeEventListener('click', handler);
  }, [games]);

  if (!game) {
    return <ThemeProvider theme={darkTheme}><Dialog open={false} sx={DIALOG_SX} /></ThemeProvider>;
  }

  const meta = RESULT_META[game.result] ?? RESULT_META.draw;
  const resign = game.resign;
  const endReason = resign
    ? `${resign.charAt(0).toUpperCase() + resign.slice(1)} resigned`
    : 'Points';
  const shareUrl = `${window.location.origin}/battle/${game.uuid}`;

  const formatDuration = (from, to) => {
    if (!from || !to) return null;
    const diffMs = new Date(to.replace(' ', 'T')) - new Date(from.replace(' ', 'T'));
    if (isNaN(diffMs) || 0 >= diffMs) return null;
    const totalSec = Math.floor(diffMs / 1000);
    const h = Math.floor(totalSec / 3600);
    const m = Math.floor((totalSec % 3600) / 60);
    const s = totalSec % 60;
    if (0 < h) return `${h}h ${m}m ${s}s`;
    if (0 < m) return `${m}m ${s}s`;
    return `${s}s`;
  };
  const duration = formatDuration(game.created, game.date);
  const pointDiff = Math.abs((game.redPoints ?? 0) - (game.bluePoints ?? 0));
  const winnerColor = (game.redPoints ?? 0) > (game.bluePoints ?? 0) ? '#f67d52'
    : (game.bluePoints ?? 0) > (game.redPoints ?? 0) ? '#95cff5'
      : 'rgba(255,255,255,0.45)';

  const handleShare = () => {
    navigator.clipboard.writeText(shareUrl).then(() => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2200);
    });
  };

  return (
    <ThemeProvider theme={darkTheme}>
      <Dialog open={open} onClose={() => setOpen(false)} sx={DIALOG_SX}>
        <div className="bd">
          <div className="bd-header">
            <div className="bd-header-left">
              <span className="bd-label">Battle Report</span>
              <h2 className="bd-title">
                <i className="fa fa-crosshairs" /> Match Details
              </h2>
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <button
                className={`bd-share${copied ? ' bd-share--copied' : ''}`}
                onClick={handleShare}
                aria-label="Copy share link"
                title="Copy share link"
              >
                <i className={`fa ${copied ? 'fa-check' : 'fa-share-alt'}`} />
                {copied ? 'Copied!' : 'Share'}
              </button>
              <button className="bd-close" onClick={() => setOpen(false)} aria-label="Close">
                <i className="fa fa-times" />
              </button>
            </div>
          </div>
          <div className="bd-vs-panel">
            <Avatar name={game.redName} color="red" avatarUrl={game.redAvatar} bonusPoints={game.redBonusPoints > game.blueBonusPoints ? game.redBonusPoints : 0} />
            <div className="bd-vs-center">
              <div className="bd-vs-score">
                <span className="bd-vs-score__red">{game.redPoints ?? '—'}</span>
                <span className="bd-vs-score__sep">:</span>
                <span className="bd-vs-score__blue">{game.bluePoints ?? '—'}</span>
              </div>
              <div className="bd-vs-score" style={{ marginBottom: 8 }}>
                <span style={{ font: '700 13px \'Rajdhani\', sans-serif', color: '#f67d52', display: 'flex', alignItems: 'center', gap: 4 }}>
                  <i className="fa fa-star" style={{ fontSize: 11 }} /> {(game.redBonusPoints ?? 0).toFixed(1)}
                </span>
                <span className="bd-vs-score__sep">:</span>
                <span style={{ font: '700 13px \'Rajdhani\', sans-serif', color: '#95cff5', display: 'flex', alignItems: 'center', gap: 4 }}>
                  {(game.blueBonusPoints ?? 0).toFixed(1)} <i className="fa fa-star" style={{ fontSize: 11 }} />
                </span>
              </div>
              <div className="bd-vs-label">VS</div>
              <div
                className="bd-result-badge"
                style={{ background: meta.bg, border: `1px solid ${meta.border}`, color: meta.color }}
              >
                <i className={`fa ${meta.icon}`} /> {meta.label}
              </div>
            </div>
            <Avatar name={game.blueName} color="blue" avatarUrl={game.blueAvatar} bonusPoints={game.blueBonusPoints > game.redBonusPoints ? game.blueBonusPoints : 0} />
          </div>
          <div className="bd-stats">
            <StatRow icon="fa-calendar" label="Date" value={game.date ?? '—'} />
            {game.created && game.date && game.created !== game.date && (
              <StatRow icon="fa-clock" label="Started" value={game.created} />
            )}
            {duration && (
              <StatRow icon="fa-hourglass-half" label="Match duration" value={duration} />
            )}
            <StatRow icon="fa-flag-checkered" label="End reason" value={endReason} />
            {0 < pointDiff && (
              <StatRow icon="fa-balance-scale" label="Winning margin" value={`${pointDiff} mine${1 === pointDiff ? '' : 's'}`} valueColor={winnerColor} />
            )}
            <StatRow
              icon="fa-bomb" label="Red used bomb"
              value={game.redExplodedBomb ? 'Yes' : 'No'}
              valueColor={game.redExplodedBomb ? '#f67d52' : 'rgba(255,255,255,0.45)'}
            />
            <StatRow
              icon="fa-bomb" label="Blue used bomb"
              value={game.blueExplodedBomb ? 'Yes' : 'No'}
              valueColor={game.blueExplodedBomb ? '#95cff5' : 'rgba(255,255,255,0.45)'}
            />
          </div>

          {(0 < game.redBonusPoints
            || 0 < game.blueBonusPoints
            || game.redBonusStats?.blindHits
            || game.blueBonusStats?.blindHits
          ) && (
            <div style={{ padding: '16px 20px 0', borderTop: '1px solid rgba(255,255,255,0.08)', marginTop: 16, marginBottom: 16 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                {/* Red Bonus */}
                <div style={{
                  padding: 16,
                  border: '1px solid rgba(173,10,5,0.2)',
                  borderRadius: 6,
                  background: 'rgba(173,10,5,0.05)',
                }}
                >
                  <span style={{ font: '700 12px \'Rajdhani\', sans-serif', textTransform: 'uppercase', letterSpacing: 2, color: '#ffd700', display: 'block', marginBottom: 12 }}>
                    <i className="fa fa-star" style={{ marginRight: 8 }} /> Red Bonus Statistics
                  </span>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                    <StatRow icon="fa-star" label="Total Bonus Points" value={(game.redBonusPoints ?? 0).toFixed(1)} valueColor="#ffd700" />
                    {0 < game.redBonusStats?.blindHits && <StatRow icon="fa-bullseye" label="Blind hits" value={game.redBonusStats.blindHits} />}
                    {0 < game.redBonusStats?.chainBest && <StatRow icon="fa-link" label="Best chain" value={game.redBonusStats.chainBest} />}
                    {0 < game.redBonusStats?.edgeMines && <StatRow icon="fa-border-all" label="Edge mines" value={game.redBonusStats.edgeMines} />}
                    {0 < game.redBonusStats?.lastMineHits && <StatRow icon="fa-hourglass-end" label="Endgame mines" value={game.redBonusStats.lastMineHits} />}
                    {0 < game.redBonusStats?.biggestReveal && <StatRow icon="fa-expand" label="Biggest reveal" value={game.redBonusStats.biggestReveal} />}
                    {!game.redBonusStats?.blindHits && !game.redBonusStats?.chainBest && !game.redBonusStats?.edgeMines && !game.redBonusStats?.lastMineHits && !game.redBonusStats?.biggestReveal
                      && <StatRow icon="fa-minus-circle" label="Status" value="No bonuses" valueColor="rgba(255,255,255,0.3)" />}
                  </div>
                </div>

                {/* Blue Bonus */}
                <div style={{
                  padding: 16,
                  border: '1px solid rgba(149,207,245,0.2)',
                  borderRadius: 6,
                  background: 'rgba(149,207,245,0.05)',
                }}
                >
                  <span style={{ font: '700 12px \'Rajdhani\', sans-serif', textTransform: 'uppercase', letterSpacing: 2, color: '#ffd700', display: 'block', marginBottom: 12 }}>
                    <i className="fa fa-star" style={{ marginRight: 8 }} /> Blue Bonus Statistics
                  </span>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
                    <StatRow icon="fa-star" label="Total Bonus Points" value={(game.blueBonusPoints ?? 0).toFixed(1)} valueColor="#ffd700" />
                    {0 < game.blueBonusStats?.blindHits && <StatRow icon="fa-bullseye" label="Blind hits" value={game.blueBonusStats.blindHits} />}
                    {0 < game.blueBonusStats?.chainBest && <StatRow icon="fa-link" label="Best chain" value={game.blueBonusStats.chainBest} />}
                    {0 < game.blueBonusStats?.edgeMines && <StatRow icon="fa-border-all" label="Edge mines" value={game.blueBonusStats.edgeMines} />}
                    {0 < game.blueBonusStats?.lastMineHits && <StatRow icon="fa-hourglass-end" label="Endgame mines" value={game.blueBonusStats.lastMineHits} />}
                    {0 < game.blueBonusStats?.biggestReveal && <StatRow icon="fa-expand" label="Biggest reveal" value={game.blueBonusStats.biggestReveal} />}
                    {!game.blueBonusStats?.blindHits && !game.blueBonusStats?.chainBest && !game.blueBonusStats?.edgeMines && !game.blueBonusStats?.lastMineHits && !game.blueBonusStats?.biggestReveal
                      && <StatRow icon="fa-minus-circle" label="Status" value="No bonuses" valueColor="rgba(255,255,255,0.3)" />}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </Dialog>
    </ThemeProvider>
  );
}
