import React, { useMemo } from 'react';
import './XRayViewer.css';

interface XRayViewerProps {
  data: string | null;
  error: string | null;
  loading: boolean;
  latency: number;
}

export default function XRayViewer({ data, error, loading, latency }: XRayViewerProps) {
  // 尝试解析 Moles 数据格式以进行美化展示
  const parsedMolesData = useMemo(() => {
    if (!data) return null;
    try {
      const parsed = JSON.parse(data);
      if (parsed.data && parsed.data.allBoards && typeof parsed.data.molesCount === 'number') {
        return parsed.data;
      }
    } catch {
      // Not valid JSON
    }
    return null;
  }, [data]);

  // 解析 Mines (扫雷) 数据
  const parsedMinesData = useMemo(() => {
    if (!data) return null;
    try {
      const parsed = JSON.parse(data);
      if (parsed.data && parsed.data.board && typeof parsed.data.minesCount === 'number') {
        return parsed.data;
      }
    } catch {
      // Not valid JSON
    }
    return null;
  }, [data]);

  const renderContent = () => {
    if (loading) {
      return (
        <div className="xray-placeholder">
          <span className="placeholder-icon rotating">⚙️</span>
          <p>正在发送请求并解析数据...</p>
        </div>
      );
    }

    if (error) {
      return (
        <div className="xray-error">
          <span className="error-icon">⚠️</span>
          <p className="error-text">{error}</p>
        </div>
      );
    }

    if (!data) {
      return (
        <div className="xray-placeholder">
          <span className="placeholder-icon">👁️</span>
          <p>点击上方“透视”按钮查看接口返回的原始数据</p>
        </div>
      );
    }

    if (parsedMolesData) {
      return (
        <div className="moles-viewer">
          <div className="moles-header">
            <div className="moles-badge">🐹 Moles 专属透析</div>
            <div className="moles-uid">UID: {parsedMolesData.uid}</div>
          </div>
          
          <div className="moles-stats">
            <div className="stat-card">
              <span className="stat-label">当前乘数</span>
              <span className="stat-value text-accent">{parseFloat(parsedMolesData.currentMultiplier).toFixed(2)}x</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">回合进度</span>
              <span className="stat-value">{parsedMolesData.currentRound} / {parsedMolesData.totalRounds}</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">埋雷数量 (Moles)</span>
              <span className="stat-value text-danger">{parsedMolesData.molesCount} 个</span>
            </div>
          </div>

          <h4 className="moles-section-title">🔮 预演图谱 (历史与未来序列)</h4>
          <div className="moles-boards">
            {parsedMolesData.allBoards.map((board: any, idx: number) => (
              <div key={idx} className={`board-card ${board.played ? 'played' : 'upcoming'}`}>
                <div className="board-round">第 {board.round} 回合</div>
                <div className="board-status">
                  {board.played ? (
                    <span className="status-badge played">已完成</span>
                  ) : (
                    <span className="status-badge upcoming">未开始</span>
                  )}
                </div>
                <div className="board-positions">
                  <span className="pos-label">地雷位置:</span>
                  <div className="pos-tags">
                    {board.molePositions.map((p: number, i: number) => (
                      <span key={i} className="pos-tag">[{p}]</span>
                    ))}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>
      );
    }

    if (parsedMinesData) {
      const gridSize = 5;
      const minesIndexes = (parsedMinesData.minesIndex || '').split(',').map(Number);
      return (
        <div className="mines-viewer">
          <div className="mines-header">
            <div className="mines-badge">💣 Mines 扫雷透析</div>
            <div className="mines-uid">UID: {parsedMinesData.uid}</div>
          </div>

          <div className="moles-stats">
            <div className="stat-card">
              <span className="stat-label">下一乘数</span>
              <span className="stat-value text-accent">
                {parsedMinesData.nextMultiplier ? `${parsedMinesData.nextMultiplier}x` : '--'}
              </span>
            </div>
            <div className="stat-card">
              <span className="stat-label">当前回合</span>
              <span className="stat-value">{parsedMinesData.currentRound}</span>
            </div>
            <div className="stat-card">
              <span className="stat-label">地雷数量</span>
              <span className="stat-value text-danger">{parsedMinesData.minesCount} 颗</span>
            </div>
          </div>

          <h4 className="moles-section-title">🗺️ 雷区地图 ({gridSize}×{gridSize})</h4>
          <div className="mines-grid">
            {parsedMinesData.board.map((cell: any) => (
              <div
                key={cell.id}
                className={`mines-cell ${cell.isBomb ? 'is-bomb' : 'is-safe'} ${cell.revealed ? 'revealed' : ''}`}
                title={`#${cell.index} ${cell.isBomb ? '💣 地雷' : '✅ 安全'}`}
              >
                <span className="cell-index">{cell.index}</span>
                <span className="cell-icon">{cell.isBomb ? '💣' : '💎'}</span>
              </div>
            ))}
          </div>

          <div className="mines-legend">
            <span className="legend-item safe"><span className="legend-dot safe" /> 安全区域</span>
            <span className="legend-item bomb"><span className="legend-dot bomb" /> 地雷位置</span>
            <span className="legend-raw">地雷索引: [{parsedMinesData.minesIndex}]</span>
          </div>
        </div>
      );
    }

    return <pre className="xray-json mono">{data}</pre>;
  };

  return (
    <div className="xray-panel">
      <div className="xray-titlebar">
        <div className="titlebar-left">
          <span className="xray-icon">🔍</span>
          <span className="xray-label">透视结果</span>
        </div>
        <div className="titlebar-right">
          {loading && <span className="xray-loading"><span className="spinner small"/> 请求中...</span>}
          {!loading && latency > 0 && (
            <span className="latency-badge online">
              <span className="latency-dot" />
              {latency} ms
            </span>
          )}
        </div>
      </div>

      <div className="xray-body">
        {renderContent()}
      </div>
    </div>
  );
}
