import 'dart:io';

import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/material.dart' hide BoxDecoration, BoxShadow;
import 'package:flutter_inset_box_shadow/flutter_inset_box_shadow.dart';
import 'package:flutter/services.dart';
import 'package:onboarding/onboarding.dart';

class OnboardingScreen extends StatefulWidget {
  const OnboardingScreen({super.key});

  @override
  State<OnboardingScreen> createState() => _OnboardingScreenState();
}

class _OnboardingScreenState extends State<OnboardingScreen> {
  DateTime? backPressTime;

  int selectedPageIndex = 0;

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    final pageList = <Widget>[
      pageModelWidget(
          size,
          "assets/onboarding/image-1.png",
          tr(context, 'onboarding.text_1'),
          "Lorem ipsum dolor sit amet consectetur. Enim purus tempor enim aliquet enim. Pulvinar enim fermentum amet lectus quis arcu. Sit neque in arcu"),
      pageModelWidget(
          size,
          "assets/onboarding/image-2.png",
          tr(context, 'onboarding.text_2'),
          "Lorem ipsum dolor sit amet consectetur. Enim purus tempor enim aliquet enim. Pulvinar enim fermentum amet lectus quis arcu. Sit neque in arcu"),
      pageModelWidget(
          size,
          "assets/onboarding/image-3.png",
          tr(context, 'onboarding.text_3'),
          "Lorem ipsum dolor sit amet consectetur. Enim purus tempor enim aliquet enim. Pulvinar enim fermentum amet lectus quis arcu. Sit neque in arcu"),
    ];

    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, result) {
        bool backStatus = onWillPop();
        if (backStatus) {
          exit(0);
        }
      },
      child: AnnotatedRegion(
        value: const SystemUiOverlayStyle(
          statusBarColor: Colors.transparent,
          statusBarIconBrightness: Brightness.dark,
        ),
        child: Scaffold(
          body: ListView(
            shrinkWrap: true,
            padding: EdgeInsets.zero,
            children: [
              SizedBox(
                height: size.height,
                width: size.width,
                child: Stack(
                  children: [
                    bgBox(size),
                    topBgImage(),
                    onboardingContent(pageList)
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget topBgImage() {
    return Positioned(
      top: -100,
      right: -144,
      child: Image.asset(
        "assets/onboarding/bg-vector.png",
        height: 267.0,
        width: 283.0,
        fit: BoxFit.contain,
      ),
    );
  }

  Widget bgBox(Size size) {
    return Container(
      height: size.height - 100,
      width: double.maxFinite,
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: const BorderRadius.vertical(
          bottom: Radius.circular(40.0),
        ),
        boxShadow: [
          BoxShadow(
            color: originalBlackColor.withOpacity(0.25),
            blurRadius: 4.0,
            offset: const Offset(0, 4),
          ),
        ],
      ),
    );
  }

  Widget onboardingContent(List<Widget> pageList) {
    return Onboarding(
      startIndex: selectedPageIndex,
      onPageChanges:
          (netDragDistance, pagesLength, currentIndex, slideDirection) {
        setState(() {
          selectedPageIndex = currentIndex;
        });
      },
      swipeableBody: pageList,
      buildFooter: (context, netDragDistance, pagesLength, currentIndex,
          setIndex, slideDirection) {
        return Column(
          children: [
            heightSpace,
            heightSpace,
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: List.generate(
                pagesLength,
                (index) {
                  return Container(
                    height: 12.0,
                    width: 12.0,
                    margin: const EdgeInsets.symmetric(
                        horizontal: fixPadding * 0.5),
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: selectedPageIndex == index
                          ? primaryColor
                          : greyColor.withOpacity(0.3),
                    ),
                  );
                },
              ),
            ),
            heightBox(fixPadding * 5.6),
            selectedPageIndex == pagesLength - 1
                ? buttonWidget(tr(context, 'onboarding.login'), () {
                    Navigator.pushNamed(context, '/login');
                  })
                : buttonWidget(tr(context, 'onboarding.next'), () {
                    setState(() {
                      selectedPageIndex++;
                    });
                  }),
            heightBox(fixPadding * 3),
            skipButton(pagesLength),
            heightBox(fixPadding * 2),
          ],
        );
      },
    );
  }

  Widget skipButton(int pagesLength) {
    return selectedPageIndex == pagesLength - 1
        ? Text(
            tr(context, 'onboarding.skip'),
            style: regular18Grey.copyWith(
              color: Colors.transparent,
            ),
          )
        : InkWell(
            onTap: () {
              Navigator.pushNamed(context, '/login');
            },
            child: Text(
              tr(context, 'onboarding.skip'),
              style: regular18Grey,
            ),
          );
  }

  Widget buttonWidget(String title, Function() onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.symmetric(horizontal: fixPadding * 6.0),
        height: 50.0,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10.0),
          color: primaryColor,
          boxShadow: [
            BoxShadow(
              color: const Color(0xFFC66D4D).withOpacity(0.25),
              blurRadius: 12.0,
              offset: const Offset(0, 6),
              inset: true,
            ),
            BoxShadow(
              color: const Color(0xFFDF8C6E).withOpacity(0.15),
              blurRadius: 12.0,
              offset: const Offset(0, 6),
              inset: true,
            )
          ],
        ),
        alignment: Alignment.center,
        child: Text(
          title,
          style: medium20White,
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );
  }

  Widget pageModelWidget(
      Size size, String image, String title, String description) {
    return Container(
      color: Colors.transparent,
      child: Column(
        children: [
          heightBox(size.height * 0.05),
          Expanded(
            child: Center(
              child: Image.asset(
                image,
                height: size.height * 0.4,
                fit: BoxFit.cover,
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: fixPadding * 2.0),
            child: Column(
              children: [
                Text(
                  title,
                  style: medium20Primary,
                  textAlign: TextAlign.center,
                  overflow: TextOverflow.ellipsis,
                ),
                heightSpace,
                Text(
                  description,
                  style: regular15Grey,
                  textAlign: TextAlign.center,
                  maxLines: 3,
                  overflow: TextOverflow.ellipsis,
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  onWillPop() {
    DateTime now = DateTime.now();
    if (backPressTime == null ||
        now.difference(backPressTime!) >= const Duration(seconds: 2)) {
      backPressTime = now;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          backgroundColor: originalBlackColor,
          content: Text(
            tr(context, 'exit_app.exit_text'),
            style: medium15White,
          ),
          behavior: SnackBarBehavior.floating,
          duration: const Duration(milliseconds: 1500),
        ),
      );
      return false;
    } else {
      return true;
    }
  }
}
