import 'dart:async';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'app_state.dart';

class TindCodeContent extends StatefulWidget {
  const TindCodeContent({Key? key}) : super(key: key);

  @override
  State<TindCodeContent> createState() => _TindCodeContentState();
}

class _TindCodeContentState extends State<TindCodeContent> {
  late TindCodeState state;
  double _startX = 0.0;
  double _currentX = 0.0;
  double _deltaX = 0.0;
  bool _isSwiping = false;
  int currentImageIndex = 0;
  List<int> remainingI = [-1];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    state = Provider.of<TindCodeState>(context);
    if (remainingI.contains(-1)){
      getList();
      currentImageIndex = remainingI.removeAt(0);
    }
  }

  void getList() {
    remainingI = List<int>.
        generate(state.data.length, (i) => i).
        where((i) => ! state.favorites.contains(i)).
        toList();

    if (remainingI.length==0) {
      remainingI = List<int>.
          generate(state.data.length, (i) => i);

    }

    remainingI.shuffle();
  }


  @override
  Widget build(BuildContext context) {

    return LayoutBuilder(
      builder: (context, constraints) {
        double containerWidth = constraints.maxWidth;
        double containerHeight = constraints.maxHeight;

        void handleSwipe(int direction) {
          if (remainingI.length == 0){
            showDialog(
              context: context,
              builder: (_) => NoMoreBooksWidget(),
            );
            getList();
          }

          if (direction == 1) {
            // Swipe right
            state.addIndexToFav(currentImageIndex);
            currentImageIndex = remainingI.removeAt(0);

          } else {
            // Swipe left
            currentImageIndex = remainingI.removeAt(0);

          }
        }

        return GestureDetector(
          onHorizontalDragStart: (details) {
            _startX = details.globalPosition.dx;
            _isSwiping = true;
          },
          onHorizontalDragUpdate: (details) {
            if (_isSwiping) {
              _currentX = details.globalPosition.dx;
              _deltaX = _currentX - _startX;
              setState(() {});
            }
          },
          onHorizontalDragEnd: (details) {
            if (_isSwiping) {
              _isSwiping = false;
              if (_deltaX > 50) {
                handleSwipe(1);
                showDialog(
                  context: context,
                  builder: (_) => SwipeFeedback(isSwipeRight: true),
                );
              } else if (_deltaX < -50) {
                handleSwipe(-1);
                showDialog(
                  context: context,
                  builder: (_) => SwipeFeedback(isSwipeRight: false),
                );
              }
            }
            _startX = 0.0;
            _currentX = 0.0;
            _deltaX = 0.0;
          },
          child: Stack(
            children: [
              Positioned.fill(child: Container(
                color: Color.fromRGBO(250, 237, 205, 1),
                height: containerHeight / 3,
                width: containerWidth / 3,
              )),
              Positioned(
                top: 20,
                left: 20,
                right: 20,
                bottom: 20,
                child: Transform.translate(
                  offset: Offset(_deltaX, 0.0),
                  child: Transform.rotate(
                    angle: _deltaX * 0.0002,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(120),
                      child: Image.asset(
                        state.data[currentImageIndex]['image'],
                        height: containerHeight / 3,
                        width: containerWidth / 3,
                        fit: BoxFit.contain,
                      ),
                    ),
                  ),
                ),
              ),
              Positioned(
                top: 20,
                left: 20,
                right: 20,
                child: Container(
                  padding: EdgeInsets.all(10),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.5),
                    borderRadius: BorderRadius.circular(10),
                    boxShadow: [BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 10,
                      offset: Offset(0, 4),
                    )],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        state.data[currentImageIndex]['title'],
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 5),
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        padding: EdgeInsets.all(8),
                        child: Text(
                          state.data[currentImageIndex]['description'],
                          style: TextStyle(
                            color: Colors.black,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}

class NoMoreBooksWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text('No More Media for you'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text('You have swipped all the media'),
          Image.asset('assets/images/nobook.jpg',fit: BoxFit.contain,), 
          
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.of(context).pop();
          },
          child: Text('OK'),
        ),
      ],
    );
  }
}

class SwipeFeedback extends StatefulWidget {
  final bool isSwipeRight;

  const SwipeFeedback({Key? key, required this.isSwipeRight}) : super(key: key);

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

class _SwipeFeedbackState extends State<SwipeFeedback> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 200),
    );

    _animation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(_controller);

    _controller.forward();

    _controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        _timer = Timer(Duration(milliseconds: 200), () {
          Navigator.of(context).pop();
        });
      } else if (status == AnimationStatus.dismissed) {
        _controller.dispose();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: AnimatedBuilder(
        animation: _animation,
        builder: (context, child) {
          return Opacity(
            opacity: 1.0 - _animation.value,
            child: Transform.scale(
              scale: 1.0 + _animation.value * 0.5,
              child: Icon(
                widget.isSwipeRight ? Icons.favorite : Icons.close,
                color: widget.isSwipeRight ? Colors.green : Colors.red,
                size: 400.0,
              ),
            ),
          );
        },
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    _timer.cancel();
    super.dispose();
  }
}
