import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:skillcourt/game_session_model.dart';

import 'package:provider/provider.dart';

import 'package:skillcourt/game_session.dart';
import 'package:intl/intl.dart';
import 'dart:ui';

import 'package:skillcourt/widgets/sad_statement.dart';

class HeaderSpaceFill extends StatefulWidget {
  final int hits;
  final int misses;

  const HeaderSpaceFill({
    required this.hits,
    required this.misses,
  });

  @override
  _HeaderSpaceFillState createState() => _HeaderSpaceFillState();
}

class _HeaderSpaceFillState extends State<HeaderSpaceFill> {
  bool showDeletedConfirmation = false;

  @override
  Widget build(BuildContext context) {
    return Consumer<GameSessionModel>(
      builder: (context, gameSessionModel, child) {
        final gameSessions = gameSessionModel.gameSessions;

        return CustomScrollView(
          slivers: [
            SliverAppBar(
              backgroundColor: Colors.white,
              elevation: 0.0,
              toolbarHeight: 100,
              automaticallyImplyLeading: false,
              pinned: true,
              flexibleSpace: FlexibleSpaceBar(
                titlePadding: EdgeInsets.only(left: 25.0, bottom: 3.0),
                title: Align(
                  alignment: Alignment.bottomLeft,
                  child: Text(
                    'My stats',
                    style: const TextStyle(
                      fontFamily: 'Product Sans',
                      fontWeight: FontWeight.w900,
                      fontSize: 46.0,
                      color: Color(0xFF323438),
                    ),
                  ),
                ),
                background: Container(
                  color: Colors.white,
                ),
              ),
              actions: [
                if (gameSessions.isNotEmpty)
                  Padding(
                    padding: EdgeInsets.only(right: 10),
                    child: IconButton(
                      alignment: Alignment.bottomLeft,
                      icon: Image.asset(
                        'assets/images/Trash_Delete_icon.png',
                      ),
                      onPressed: () {
                        showModalBottomSheet(
                          context: context,
                          backgroundColor: Colors.transparent,
                          builder: (BuildContext context) {
                            return Container(
                              height: 364,
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.only(
                                  topLeft: Radius.circular(12),
                                  topRight: Radius.circular(12),
                                ),
                              ),
                              child: Column(
                                children: [
                                  SizedBox(height: 16),
                                  Container(
                                    width: 32,
                                    height: 4,
                                    decoration: BoxDecoration(
                                      color: Color(0xFFDEDEDE),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                  ),
                                  SizedBox(height: 24),
                                  Text(
                                    'Delete stats?',
                                    style: TextStyle(
                                      color: Color(0xFF323438),
                                      fontSize: 44,
                                      fontFamily: 'Product Sans',
                                      fontWeight: FontWeight.w700,
                                    ),
                                  ),
                                  SizedBox(height: 16),
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                      horizontal: 32,
                                    ),
                                    child: Text(
                                      'Are you sure you want to delete all your stats? You may also swipe left on a specific session to delete it.',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        color: Color(0xFF323438),
                                        fontSize: 18,
                                        fontFamily: 'Product Sans',
                                        fontWeight: FontWeight.w400,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 32),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      TextButton(
                                        onPressed: () {
                                          gameSessionModel.clearGameSessions();
                                          Navigator.pop(context);
                                          setState(() {
                                            showDeletedConfirmation = true;
                                          });
                                        },
                                        style: ButtonStyle(
                                          shape: MaterialStateProperty.all<
                                              RoundedRectangleBorder>(
                                            RoundedRectangleBorder(
                                              borderRadius:
                                                  BorderRadius.circular(24),
                                            ),
                                          ),
                                          backgroundColor:
                                              MaterialStateProperty.all<Color>(
                                            Color(0xFFF5F5F5),
                                          ),
                                        ),
                                        child: Text(
                                          'Yes',
                                          style: TextStyle(
                                            color: Color(0xFF323438),
                                            fontSize: 24,
                                            fontFamily: 'Product Sans',
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                      TextButton(
                                        onPressed: () {
                                          Navigator.pop(context);
                                        },
                                        child: Text(
                                          'Cancel',
                                          style: TextStyle(
                                            color: Color(0xFF595959),
                                            fontSize: 18,
                                            fontFamily: 'Product Sans',
                                            fontWeight: FontWeight.w400,
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            );
                          },
                        );
                      },
                    ),
                  ),
              ],
            ),
            SliverToBoxAdapter(
              child: Column(
                children: [
                  if (gameSessions.isEmpty) _noSessionsWidget(),
                  if (showDeletedConfirmation) _deletedConfirmationWidget(),
                  if (gameSessions.isNotEmpty) SessionListWidget(),
                ],
              ),
            ),
          ],
        );
      },
    );
  }

  Widget _noSessionsWidget() {
    return SadStatement(sadMessage: 'No sessions yet');
  }

  Widget _deletedConfirmationWidget() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 570),
      child: Container(
        width: 311,
        height: 56,
        decoration: BoxDecoration(color: Color(0xFF323438)),
        child: Row(
          children: [
            Expanded(
              child: Align(
                alignment: Alignment.centerLeft,
                child: Padding(
                  padding: const EdgeInsets.only(left: 10),
                  child: SizedBox(
                    width: 240,
                    height: 24,
                    child: Text(
                      'All stats deleted successfully',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16,
                        fontFamily: 'Product Sans',
                        fontWeight: FontWeight.w400,
                      ),
                    ),
                  ),
                ),
              ),
            ),
            GestureDetector(
              onTap: () {
                // Handle the removal logic here
                // For example, you can use a state management approach
                setState(() {
                  showDeletedConfirmation = false;
                });
              },
              child: Container(
                width: 40,
                height: 24,
                child: Stack(
                  children: [
                    Positioned(
                      left: 0,
                      top: 0,
                      child: Container(width: 24, height: 24),
                    ),
                    Positioned(
                      right: 20,
                      top: 3.51,
                      child: Container(
                        width: 16.97,
                        height: 16.97,
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage('assets/images/Close_icon.png'),
                            fit: BoxFit.fill,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SessionListWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final gameSessionModel = Provider.of<GameSessionModel>(context);
    final gameSessions = gameSessionModel.gameSessions;
    final screenHeight = MediaQuery.of(context).size.height;

    return ListView.builder(
      padding: EdgeInsets.only(top: 5.0),
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: gameSessions.length,
      itemBuilder: (context, index) =>
          sessionsWidget(context, gameSessions[index], index, screenHeight),
    );
  }

  Widget sessionsWidget(BuildContext context, GameSession session, int index,
      double screenHeight) {
    final sessionDateFormatted =
        DateFormat('E MMM d').format(session.sessionDate);
    int hits = session.hits;
    int misses = session.misses;
    final gameSessionModel =
        Provider.of<GameSessionModel>(context, listen: false);

    // Format the session duration to a string
    String sessionDurationFormatted =
        '${session.sessionDuration.inMinutes} min ${session.sessionDuration.inSeconds.remainder(60)} sec';

    return Padding(
      padding: const EdgeInsets.symmetric(
          horizontal: 24,
          vertical: 8), // Adjust the vertical padding as per your preference
      child: Container(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(8),
          child: Dismissible(
            key: Key(session.sessionNumber.toString()),
            direction: DismissDirection.endToStart,
            onDismissed: (direction) {
              Provider.of<GameSessionModel>(context, listen: false)
                  .removeSession(index);
            },
            background: Container(
              color: Colors.red,
              child: Align(
                alignment: Alignment.centerRight,
                child: Padding(
                  padding: const EdgeInsets.only(right: 16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Icon(
                        Icons.delete,
                        color: Colors.white,
                        size: 24.0,
                      ),
                      SizedBox(width: 8.0),
                      Text(
                        'Delete',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            child: Container(
              height: 96,
              decoration: ShapeDecoration(
                color: gameSessionModel.pressedSessionIndex == index
                    ? Color(0xFFE7F3F0)
                    : Colors.white,
                shape: RoundedRectangleBorder(
                  side: BorderSide(
                    width: 2,
                    color: gameSessionModel.pressedSessionIndex == index
                        ? Color(0xFFE7F3F0)
                        : Color(0xFFDEDEDE),
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
              child: Stack(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          'Session ${session.sessionNumber}',
                          style: TextStyle(
                            color: Color(0xFF323438),
                            fontSize: 20,
                            fontFamily: 'Product Sans',
                            fontWeight: FontWeight.w700,
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text(
                          sessionDateFormatted,
                          textAlign: TextAlign.right,
                          style: TextStyle(
                            color: Color(0xFF595959),
                            fontSize: 14,
                            fontFamily: 'Product Sans',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ),
                    ],
                  ),
                  Positioned(
                    bottom: 8,
                    left: 8,
                    child: Row(
                      children: [
                        Image.asset('assets/images/Game_time_icon.png'),
                        SizedBox(width: 2),
                        Text(
                          sessionDurationFormatted,
                          style: TextStyle(
                            color: Color(0xFF595959),
                            fontSize: 20,
                            fontFamily: 'Product Sans',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    bottom: 8,
                    right: 8,
                    child: Row(
                      children: [
                        Image.asset('assets/images/Pad_HIT_icon.png'),
                        SizedBox(width: 8),
                        Text(
                          '$hits/$misses',
                          textAlign: TextAlign.right,
                          style: TextStyle(
                            color: Color(0xFF595959),
                            fontSize: 18,
                            fontFamily: 'Product Sans',
                            fontWeight: FontWeight.w400,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class StatisticsPage extends StatefulWidget {
  static const String routeName = '/statistics';

  final GameSession? gameSession;

  const StatisticsPage({Key? key, this.gameSession}) : super(key: key);

  @override
  _StatisticsPageState createState() => _StatisticsPageState();
}

class _StatisticsPageState extends State<StatisticsPage> {
  int hits = 0;
  int misses = 0;

  @override
  void initState() {
    super.initState();

    if (widget.gameSession != null) {
      hits = widget.gameSession!.hits;
      misses = widget.gameSession!.misses;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<GameSessionModel>(
      builder: (context, gameSessionModel, _) {
        return Scaffold(
          backgroundColor: Colors.white,
          body: HeaderSpaceFill(
            hits: hits,
            misses: misses,
          ),
        );
      },
    );
  }
}
