import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:intl/intl.dart';
import '../../core/theme_manager.dart';
import '../../services/storage_service.dart';

class HistoryScreen extends StatelessWidget {
  const HistoryScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final theme = context.watch<ThemeManager>().currentColors;
    final history = StorageService.instance.matchHistory;

    return Scaffold(
      backgroundColor: theme.background,
      appBar: AppBar(
        title: Text("STORICO PARTITE", style: TextStyle(fontWeight: FontWeight.w900, color: theme.text, letterSpacing: 2)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: IconThemeData(color: theme.text),
      ),
      body: history.isEmpty
          ? Center(
        child: Text(
          "Nessuna partita giocata.\nScendi in campo!",
          textAlign: TextAlign.center,
          style: TextStyle(color: theme.text.withOpacity(0.5), fontSize: 18, fontWeight: FontWeight.bold),
        ),
      )
          : ListView.builder(
        padding: const EdgeInsets.all(20),
        itemCount: history.length,
        itemBuilder: (context, index) {
          final match = history[index];

          DateTime date = DateTime.parse(match['date']);
          String formattedDate = DateFormat('dd MMM yyyy - HH:mm').format(date);

          // Leggiamo entrambi i nomi
          String myName = match['myName'] ?? "IO"; // Usa 'IO' se è una partita vecchia
          String opponent = match['opponent'];

          int myScore = match['myScore'];
          int oppScore = match['oppScore'];
          bool isOnline = match['isOnline'];

          bool isWin = myScore > oppScore;
          bool isDraw = myScore == oppScore;

          Color resultColor = isWin ? Colors.green : (isDraw ? Colors.grey : theme.playerRed);
          String resultText = isWin ? "VITTORIA" : (isDraw ? "PAREGGIO" : "SCONFITTA");

          return Container(
            margin: const EdgeInsets.only(bottom: 15),
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              color: theme.text.withOpacity(0.05),
              borderRadius: BorderRadius.circular(20),
              border: Border.all(color: resultColor.withOpacity(0.5), width: 2),
              boxShadow: [
                BoxShadow(color: Colors.black.withOpacity(0.2), offset: const Offset(0, 4), blurRadius: 6),
              ],
            ),
            child: Row(
              children: [
                // Icona Tipo di Partita
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: resultColor.withOpacity(0.1),
                    shape: BoxShape.circle,
                  ),
                  child: Icon(
                    isOnline ? Icons.public : (opponent.contains("CPU") ? Icons.smart_toy : Icons.people_alt),
                    color: resultColor,
                    size: 28,
                  ),
                ),
                const SizedBox(width: 15),

                // Dati Partita (Ora con i nomi chiari)
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(resultText, style: TextStyle(color: resultColor, fontWeight: FontWeight.w900, fontSize: 16, letterSpacing: 1.5)),
                      const SizedBox(height: 5),
                      // NOMI GIOCATORI
                      RichText(
                          text: TextSpan(
                              children: [
                                TextSpan(text: myName, style: TextStyle(color: theme.playerBlue, fontWeight: FontWeight.bold, fontSize: 15)),
                                TextSpan(text: " vs ", style: TextStyle(color: theme.text.withOpacity(0.5), fontStyle: FontStyle.italic, fontSize: 12)),
                                TextSpan(text: opponent, style: TextStyle(color: theme.playerRed, fontWeight: FontWeight.bold, fontSize: 15)),
                              ]
                          )
                      ),
                      const SizedBox(height: 5),
                      Text(formattedDate, style: TextStyle(color: theme.text.withOpacity(0.5), fontSize: 12)),
                    ],
                  ),
                ),

                // Punteggio
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: theme.background,
                    borderRadius: BorderRadius.circular(15),
                    border: Border.all(color: theme.gridLine.withOpacity(0.3)),
                  ),
                  child: Row(
                    children: [
                      Text("$myScore", style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: theme.playerBlue)),
                      Text(" - ", style: TextStyle(fontSize: 18, color: theme.text.withOpacity(0.5))),
                      Text("$oppScore", style: TextStyle(fontSize: 22, fontWeight: FontWeight.w900, color: theme.playerRed)),
                    ],
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}