import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:skillcourt/navigation/bottom_nav_bar.dart';
import 'package:skillcourt/pages/play_setup/play_setup.dart';
import 'package:skillcourt/widgets/custom_appbar.dart';
import 'package:skillcourt/pages/login_screen.dart';
import 'package:skillcourt/pages/statistics.dart';
import 'package:skillcourt/pages/settings/settings.dart';
import 'package:skillcourt/services/auth.dart';
import 'package:skillcourt/widgets/color_picker.dart';

final getIt = GetIt.instance;

class HomePageNew extends StatefulWidget {
  static const routeName = 'HomePage';
  const HomePageNew({Key? key}) : super(key: key);

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

class _HomePageState extends State<HomePageNew> {
  final Auth _auth = getIt<Auth>();
  final SharedPreferences _sp = getIt<SharedPreferences>();

  String _numberOfPanels = '15';

  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _sp.setString('padCount', '5  ');
  }

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
    if (index == 2) {
      SettingsPage();
    }
  }

  @override
  Widget build(BuildContext context) {
    _numberOfPanels = _sp.getString('padCount')!;
    return StreamBuilder<AuthState>(
        stream: _auth.authState(),
        // ignore: body_might_complete_normally
        builder: (BuildContext context, AsyncSnapshot<AuthState> snapshot) {
          if (snapshot.data == AuthState.pending) {
            // Do something to await AuthState completion
          } else if (snapshot.data == AuthState.unauthenticated) {
            Navigator.pushNamed(context, LoginScreen.routeName);
          }

          return Scaffold(
              backgroundColor: Colors.white,
              bottomNavigationBar: BottomNavBar(
                  selectedIndex: _currentIndex,
                  onDestinationSelected: _onTabTapped),
              body: body());
        });
  }

  Widget body() {
    if (_currentIndex == 0) {
      return Home();
    } else if (_currentIndex == 1) {
      return StatisticsPage();
    } else {
      return SettingsPage();
    }
  }

  Widget Home() {
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: const CustomAppBar(
          title: 'Skillcourt',
        ),
        body: _numberOfPanels == '0'
            ? Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  flex: 1,
                  child: ListView(
                    padding: const EdgeInsets.symmetric(
                        vertical: 1.0, horizontal: 1.0),
                    children: [
                      _buildCustomWidget(),
                      noAgipads(),
                      const Padding(padding: EdgeInsets.only(top: 170.0)),
                      CTAButton(
                        label: 'Learn more',
                        onPressed: () {
                          // Handle button press
                        },
                      ),
                      // Added custom widget here
                    ],
                  )),
            ])
            : Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                  flex: 1,
                  child: ListView(
                    padding: const EdgeInsets.symmetric(
                        vertical: 1.0, horizontal: 1.0),
                    children: [
                      _buildCustomWidget(),
                      CustomCarouselSlider(),
                      const Padding(padding: EdgeInsets.only(top: 170.0)),
                      CTAButton(
                        label: 'Play',
                        onPressed: () {
                          // Handle button press
                          Navigator.of(context).pushNamed(PlaySetUp.routeName);
                        },
                      ),
                      // Added custom widget here
                    ],
                  )),
            ]));
  }

  Widget noAgipads() {
    return const Card(
      elevation: 0.0,
      borderOnForeground: true,
      child: Padding(
        padding: EdgeInsets.all(16.0),
        child: Row(children: [
          Expanded(
            flex: 2,
            child:
            Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
              Text("Don't have an Agipad?",
                  style: TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  )),
              Text(
                  'In order to fully use this mobile app, you\nmust connect an Agipad device.\n',
                  style: TextStyle(
                    fontSize: 14,
                  ))
            ]),
          )
        ]),
      ),
    );
  }

  PlatformTextButton _buildButton(
      {required BuildContext context,
        required String label,
        required String routeName}) {
    return PlatformTextButton(
        onPressed: () => Navigator.pushNamed(context, routeName),
        child: Text(label));
  }

  PlatformTextButton _buildIconButton(
      {required BuildContext context,
        required String label,
        required Icon icon,
        required String routeName}) {
    return PlatformTextButton(
        onPressed: () => Navigator.pushNamed(context, routeName),
        child: Row(children: [icon, Text(label)]));
  }

  Widget _buildCustomWidget() {
    return Semantics(
        label: '',
        child: Container(
          width: 200.0,
          height: 65.0,
          margin: const EdgeInsets.only(top: 24.0, left: 16.0, right: 16.0),
          decoration: BoxDecoration(
            color: Color(0xFFDEDEDE),
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Row(
            children: [
              // ignore: prefer_const_constructors
              Padding(
                padding: EdgeInsets.only(left: 16.0),
                child: Text(
                  _numberOfPanels,
                  semanticsLabel: '$_numberOfPanels ',
                  style: const TextStyle(
                    fontFamily: 'Product Sans',
                    fontWeight: FontWeight.w700,
                    fontSize: 24.0,
                    color: Color(0xFF323438),
                  ),
                ),
              ),
              const SizedBox(width: 16.0),
              const Text(
                'pads connected',
                style: TextStyle(
                    fontFamily: 'Product Sans',
                    fontWeight: FontWeight.w400,
                    fontSize: 18.0,
                    color: Color(0xFF323438)),
              ),
              const Spacer(),
              Padding(
                padding: EdgeInsets.only(right: 16.0),
                child: Transform.scale(
                    scale: 1.2,
                    child: const Icon(Icons.chevron_right,
                        size: 36.0, color: Color(0xFF323438))),
              ),
            ],
          ),
        ));
  }
}

class ColorCardWidget extends StatelessWidget {
  final String image;
  final String labelTop;
  final String labelBottom;
  final String buttonLabel;
  final VoidCallback? function; // Add a function parameter

  const ColorCardWidget({
    required this.image,
    required this.labelTop,
    required this.labelBottom,
    required this.buttonLabel,
    this.function, // Include it in the constructor
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      elevation: 0.0,
      borderOnForeground: true,
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Row(
          children: [
            Expanded(
              flex: 2,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    labelTop,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  SizedBox(
                    width: 150.0,
                    child: Text(
                      labelBottom,
                      style: const TextStyle(
                        fontSize: 14,
                      ),
                    ),
                  ),
                  const SizedBox(height: 15),
                  ElevatedButton(
                    onPressed: function, // Call the function if provided
                    style: ElevatedButton.styleFrom(
                      foregroundColor: Color(0xFF323438),
                      backgroundColor: Color(0xFFDEDEDE),
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15),
                      ),
                    ),
                    child: Text(buttonLabel),
                  ),
                ],
              ),
            ),
            Expanded(
              flex: 1,
              child: Image.asset(
                image,
                fit: BoxFit.cover,
              ),
            ),
          ],
        ),
      ),
    );
  }
}


class CustomCarouselSlider extends StatefulWidget {
  @override
  _CustomCarouselSliderState createState() => _CustomCarouselSliderState();
}

class _CustomCarouselSliderState extends State<CustomCarouselSlider> {
  final Auth _auth = getIt<Auth>();
  int _currentIndex = 0;
  final CarouselController _carouselController = CarouselController();

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<AuthState>(
      stream: _auth.authState(),
      // ignore: body_might_complete_normally
      builder: (BuildContext context, AsyncSnapshot<AuthState> snapshot) {
        if (snapshot.data == AuthState.pending) {
          // Do something to await AuthState completion
        } else if (snapshot.data == AuthState.unauthenticated) {
          Navigator.pushNamed(context, LoginScreen.routeName);
        }

        return Column(
          children: [
            CarouselSlider(
              carouselController: _carouselController,
              options: CarouselOptions(
                height: 175,
                viewportFraction: 1.0,
                enableInfiniteScroll: false,
                onPageChanged: (index, reason) {
                  setState(() {
                    _currentIndex = index;
                  });
                },
              ),
              items:  [
                ColorCardWidget(
                  image: 'assets/images/color_wheel.png',
                  labelTop: 'Customize the color',
                  labelBottom: 'of your agipad lights\n',
                  buttonLabel: 'Edit Color',
                    function: (){
                      Navigator.pushNamed(context, ColorPicker.routeName);
                    }
                ),
                ColorCardWidget(
                  image: 'assets/images/sun.png',
                  labelTop: 'Customize brightness',
                  labelBottom: 'of your agipad lights\n',
                  buttonLabel: 'Edit brightness',
                ),
                ColorCardWidget(
                  image: 'assets/images/agipads.png',
                  labelTop: 'Need an Agipad?',
                  labelBottom: 'Practice your skills and buiild up a sweat!',
                  buttonLabel: 'Learn more',
                ),
              ],
            ),
            const SizedBox(height: 12.0),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List<Widget>.generate(3, (index) {
                return GestureDetector(
                  onTap: () {
                    _carouselController.animateToPage(index);
                  },
                  child: Container(
                    width: 12.0,
                    height: 12.0,
                    margin: const EdgeInsets.symmetric(horizontal: 4.0),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: _currentIndex == index
                          ? const Color(0xFF323438)
                          : const Color(0xFFDEDEDE),
                    ),
                  ),
                );
              }),
            ),
          ],
        );
      },
    );
  }
}
Widget _SettingSelectorWidget({required String imagePath, required String textName, Function()?function}) {
  return GestureDetector(
    onTap: function, //que boberia
    child: Semantics

      (
        label: '',
        child: Container(
          width: 200.0,
          height: 65.0,
          margin: const EdgeInsets.only(top: 24.0, left: 16.0, right: 16.0),
          decoration: BoxDecoration(
            color: Color(0xFFDEDEDE),
            borderRadius: BorderRadius.circular(8.0),
          ),
          child: Row(
            children: [
              // ignore: prefer_const_constructors

              Padding(
                  padding: const EdgeInsets.only(left: 16.0),
                  child: Image.asset(imagePath,
                    fit: BoxFit.cover,
                  )
              ),
              const SizedBox(width: 16.0),
              Text(
                textName,
                style: const TextStyle(
                    fontFamily: 'Product Sans',
                    fontWeight: FontWeight.w400,
                    fontSize: 18.0,
                    color: Color(0xFF323438)
                ),
              ),
            ],
          ),
        )
    ),
  );
}
class CTAButton extends StatelessWidget {
  final String label;
  final VoidCallback onPressed;
  final Color? backGroundColor;
  final Color? textColor;

  const CTAButton(
      {required this.label,
        required this.onPressed,
        this.backGroundColor,
        this.textColor});

  @override
  Widget build(BuildContext context) {
    return Center(
        child: SizedBox(
          height: 48.0,
          width: 198.0,
          child: ElevatedButton(
            onPressed: onPressed,
            style: ElevatedButton.styleFrom(
              backgroundColor: backGroundColor ?? const Color(0xFF128566),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(15.0),
              ),
            ),
            child: Text(
              label,
              style: TextStyle(
                fontSize: 24.0,
                fontWeight: FontWeight.bold,
                color: textColor??Colors.white,
              ),
            ),
          ),
        ));
  }
}

