import React from 'react';
import { Bar, Doughnut, Line } from 'react-chartjs-2';
import { TrendingUp, Target, Calculator, Zap } from 'lucide-react';
import '../utils/chartSetup'; // Importar configuração do Chart.js

interface StatisticsProps {
  totalGames: number;
  currentGame: number;
  phases: number;
  gamesPerPhase: Record<number, number>;
}

const Statistics: React.FC<StatisticsProps> = ({
  totalGames,
  currentGame,
  phases,
  gamesPerPhase
}) => {
  // Dados para gráfico de barras - jogos por fase
  const barChartData = {
    labels: Object.keys(gamesPerPhase).map(phase => `Fase ${phase}`),
    datasets: [
      {
        label: 'Jogos por Fase',
        data: Object.values(gamesPerPhase),
        backgroundColor: [
          'rgba(59, 130, 246, 0.8)',
          'rgba(16, 185, 129, 0.8)',
          'rgba(245, 158, 11, 0.8)',
          'rgba(239, 68, 68, 0.8)',
        ],
        borderColor: [
          'rgb(59, 130, 246)',
          'rgb(16, 185, 129)',
          'rgb(245, 158, 11)',
          'rgb(239, 68, 68)',
        ],
        borderWidth: 2,
        borderRadius: 4,
      },
    ],
  };

  // Dados para gráfico de rosca - progresso
  const doughnutData = {
    labels: ['Jogos Concluídos', 'Jogos Restantes'],
    datasets: [
      {
        data: [currentGame, totalGames - currentGame],
        backgroundColor: [
          'rgba(34, 197, 94, 0.8)',
          'rgba(156, 163, 175, 0.3)',
        ],
        borderColor: [
          'rgb(34, 197, 94)',
          'rgb(156, 163, 175)',
        ],
        borderWidth: 2,
      },
    ],
  };

  // Simulação de probabilidades (dados reais viriam de análise histórica)
  const probabilityData = {
    17: 15.2,
    18: 8.7,
    19: 3.1,
    20: 0.8,
  };

  const probabilityChartData = {
    labels: ['17 pontos', '18 pontos', '19 pontos', '20 pontos'],
    datasets: [
      {
        label: 'Probabilidade (%)',
        data: Object.values(probabilityData),
        borderColor: 'rgb(59, 130, 246)',
        backgroundColor: 'rgba(59, 130, 246, 0.1)',
        tension: 0.4,
        fill: true,
      },
    ],
  };

  const chartOptions = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top' as const,
      },
      title: {
        display: false,
      },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  const StatCard: React.FC<{
    title: string;
    value: string | number;
    icon: React.ReactNode;
    color: string;
    description?: string;
  }> = ({ title, value, icon, color, description }) => (
    <div className="bg-white p-6 rounded-xl shadow-lg border border-gray-200 hover:shadow-xl transition-all duration-300">
      <div className="flex items-center justify-between">
        <div>
          <p className="text-sm font-medium text-gray-600 mb-1">{title}</p>
          <p className={`text-2xl font-bold ${color}`}>{value}</p>
          {description && (
            <p className="text-xs text-gray-500 mt-1">{description}</p>
          )}
        </div>
        <div className={`p-3 rounded-full ${color.replace('text-', 'bg-').replace('-600', '-100')}`}>
          {icon}
        </div>
      </div>
    </div>
  );

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-gradient-to-r from-blue-600 to-blue-700 p-6 rounded-xl text-white">
        <h2 className="text-2xl font-bold mb-2">Estatísticas da Estratégia</h2>
        <p className="text-blue-100">
          Análise completa do desempenho e padrões da sua estratégia
        </p>
      </div>

      {/* Cards de Estatísticas Principais */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <StatCard
          title="Total de Jogos"
          value={totalGames.toLocaleString()}
          icon={<Calculator className="w-6 h-6 text-blue-600" />}
          color="text-blue-600"
          description="Jogos na estratégia completa"
        />
        
        <StatCard
          title="Jogo Atual"
          value={currentGame}
          icon={<Target className="w-6 h-6 text-green-600" />}
          color="text-green-600"
          description={`${Math.round((currentGame / totalGames) * 100)}% concluído`}
        />
        
        <StatCard
          title="Fases"
          value={phases}
          icon={<TrendingUp className="w-6 h-6 text-orange-600" />}
          color="text-orange-600"
          description="Fases da estratégia"
        />
        
        <StatCard
          title="Jogos Restantes"
          value={(totalGames - currentGame).toLocaleString()}
          icon={<Zap className="w-6 h-6 text-purple-600" />}
          color="text-purple-600"
          description="Para completar a estratégia"
        />
      </div>

      {/* Gráficos */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Jogos por Fase */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4 text-gray-800">
            Distribuição de Jogos por Fase
          </h3>
          <Bar data={barChartData} options={chartOptions} />
        </div>

        {/* Progresso Geral */}
        <div className="card">
          <h3 className="text-lg font-semibold mb-4 text-gray-800">
            Progresso da Estratégia
          </h3>
          <div className="flex justify-center">
            <div style={{ width: '300px', height: '300px' }}>
              <Doughnut 
                data={doughnutData} 
                options={{
                  responsive: true,
                  maintainAspectRatio: false,
                  plugins: {
                    legend: {
                      position: 'bottom',
                    },
                  },
                }}
              />
            </div>
          </div>
        </div>
      </div>

      {/* Probabilidades */}
      <div className="card">
        <h3 className="text-lg font-semibold mb-4 text-gray-800">
          Probabilidades de Acerto (Estimativas)
        </h3>
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          <div>
            <Line 
              data={probabilityChartData} 
              options={{
                ...chartOptions,
                scales: {
                  y: {
                    beginAtZero: true,
                    max: 20,
                    ticks: {
                      callback: function(value) {
                        return value + '%';
                      }
                    }
                  }
                }
              }} 
            />
          </div>
          <div className="space-y-4">
            {Object.entries(probabilityData).map(([points, probability]) => (
              <div key={points} className="flex items-center justify-between p-4 bg-gray-50 rounded-lg">
                <div className="flex items-center space-x-3">
                  <div className={`w-4 h-4 rounded-full ${
                    points === '20' ? 'bg-red-500' :
                    points === '19' ? 'bg-orange-500' :
                    points === '18' ? 'bg-yellow-500' : 'bg-green-500'
                  }`}></div>
                  <span className="font-medium text-gray-800">{points} pontos</span>
                </div>
                <span className="text-lg font-bold text-gray-900">{probability}%</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Análise Detalhada */}
      <div className="card">
        <h3 className="text-lg font-semibold mb-4 text-gray-800">
          Análise Detalhada da Estratégia
        </h3>
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="text-center p-4 bg-blue-50 rounded-lg">
            <div className="text-2xl font-bold text-blue-600 mb-2">
              {Math.round(totalGames / phases)}
            </div>
            <div className="text-sm text-blue-800 font-medium">
              Jogos por Fase (Média)
            </div>
          </div>
          
          <div className="text-center p-4 bg-green-50 rounded-lg">
            <div className="text-2xl font-bold text-green-600 mb-2">
              50
            </div>
            <div className="text-sm text-green-800 font-medium">
              Números por Jogo
            </div>
          </div>
          
          <div className="text-center p-4 bg-orange-50 rounded-lg">
            <div className="text-2xl font-bold text-orange-600 mb-2">
              5
            </div>
            <div className="text-sm text-orange-800 font-medium">
              Colunas Marcadas
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Statistics;
