import 'package:flutter/material.dart';

import 'package:mobdr/service/shared_prefs.dart';
import 'package:mobdr/config/global_style.dart';

class SyncPage extends StatefulWidget {
  @override
  _SyncPageState createState() => _SyncPageState();
}

class _SyncPageState extends State<SyncPage>
    with SingleTickerProviderStateMixin {
  AnimationController? _animationController;
  late Animation<double> _rotationAnimation;

  bool _isSyncing = false;
  bool _syncCompleted = false;

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

    _animationController = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );

    _rotationAnimation = Tween<double>(
      begin: 0,
      end: 1,
    ).animate(_animationController!);

    _animationController!.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        setState(() {
          _syncCompleted = true;
        });
      }
    });

    // Lancement automatique de la synchronisation au démarrage
    //startSync();
  }

  @override
  void dispose() {
    _animationController!.dispose();
    super.dispose();
  }

  void startSync() {
    setState(() {
      _isSyncing = true;
      _syncCompleted = false;
    });

    _animationController!.repeat();

    // Simulation d'une tâche de synchronisation
    Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        _isSyncing = false;
        _syncCompleted = true;
      });
      _animationController!.stop();
    });
  }

  @override
  Widget build(BuildContext context) {
    final double screenWidth = MediaQuery.of(context).size.width;
    final double screenHeight = MediaQuery.of(context).size.height;

    // Calcul du positionnement du premier cercle
    final double circleSize = 55;
    final double circleLeft = (screenWidth - circleSize) / 2 - 23;
    final double circleTop = (screenHeight - circleSize) / 2 + 30;

    // Calcul du positionnement du deuxième cercle
    final double secondCircleSize = 29;
    final double secondCircleLeft = (screenWidth - circleSize) / 2 + 142;
    final double secondCircleTop = (screenHeight - circleSize) / 2 + 75;

    // Définition de la couleur du premier cercle en fonction de l'état de synchronisation
    Color circleColor;
    if (_isSyncing) {
      circleColor = Colors.lightBlue;
    } else if (_syncCompleted) {
      circleColor = Colors.green;
    } else {
      circleColor = Colors.transparent;
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('Page de synchronisation'),
      ),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/images/synchro.png'),
                fit: BoxFit.contain,
              ),
            ),
          ),
          Container(
            padding: EdgeInsets.fromLTRB(16, 16, 16, 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Calendar', style: GlobalStyle.horizontalTitle),
                Row(
                  children: [
                    Icon(Icons.refresh),
                    Text(SharedPrefs().lastCalendarRefresh.isNotEmpty
                        ? SharedPrefs().lastCalendarRefresh
                        : "Never"),
                  ],
                ),
              ],
            ),
          ),
          if (_isSyncing || _syncCompleted)
            Positioned(
              left: circleLeft,
              top: circleTop,
              child: Container(
                width: circleSize,
                height: circleSize,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: circleColor,
                ),
                child: _syncCompleted
                    ? Icon(
                        Icons.check,
                        color: Colors.white,
                        size: circleSize - 20,
                      )
                    : null,
              ),
            ),
          if (_isSyncing || _syncCompleted)
            Positioned(
              left: secondCircleLeft,
              top: secondCircleTop,
              child: Container(
                width: secondCircleSize,
                height: secondCircleSize,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: circleColor,
                ),
                child: _syncCompleted
                    ? Icon(
                        Icons.check,
                        color: Colors.white,
                        size: secondCircleSize - 15,
                      )
                    : null,
              ),
            ),
          if (_isSyncing)
            Positioned(
              left: circleLeft + (circleSize - 70) / 2,
              top: circleTop + (circleSize - 70) / 2,
              child: Align(
                alignment: Alignment.center,
                child: AnimatedBuilder(
                  animation: _animationController!,
                  builder: (BuildContext context, Widget? child) {
                    return Transform.rotate(
                      angle: _rotationAnimation.value * 2.0 * 3.14,
                      child: Icon(
                        Icons.refresh,
                        color: Colors.white,
                        size: 70,
                      ),
                    );
                  },
                ),
              ),
            ),
          if (_isSyncing)
            Positioned(
              left: secondCircleLeft + (secondCircleSize - 35) / 2,
              top: secondCircleTop + (secondCircleSize - 34) / 2,
              child: AnimatedBuilder(
                animation: _animationController!,
                builder: (BuildContext context, Widget? child) {
                  return Transform.rotate(
                    angle: _rotationAnimation.value * 2.0 * 3.14,
                    child: Icon(
                      Icons.refresh,
                      color: Colors.white,
                      size: 35,
                    ),
                  );
                },
              ),
            ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                SizedBox(height: 20),
                if (_isSyncing)
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: LinearProgressIndicator(),
                  ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: _isSyncing ? null : startSync,
                  child: Text('Lancer la synchronisation'),
                ),
                SizedBox(height: 20),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
