import 'dart:ui';

import 'package:anyway/core/constants.dart';
import 'package:anyway/presentation/providers/onboarding_state_provider.dart';
import 'package:anyway/presentation/widgets/onbarding_agreement_card.dart';
import 'package:anyway/presentation/widgets/onboarding_card.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';


List<Widget> onboardingCards = [
  const OnboardingCard(
    title: "Welcome to anyway!",
    description: "Anyway helps you plan a city trip that suits your wishes.",
    imagePath: "assets/cld-server.svg"
  ),
  const OnboardingCard(
    title: "Do your thing",
    description: "Bored by churches? No problem! Hate shopping? No worries! Instead of suggesting the generic trips that bore you, anyway will try to give you recommendations that really suit you.",
    imagePath: "assets/con-drill.svg"
  ),
  const OnboardingCard(
    title: "Change your mind",
    description: "Feet get sore, the weather changes. Anyway understands that! Move or remove destinations, visit hidden gems along your journey, do your own thing. Anyway adapts to your spontaneous decisions.",
    imagePath: "assets/cel-snow-globe.svg"
  ),
  const OnboardingCard(
    title: "Feeling lost?",
    description: "Whenever you are confused or need help with the app, look out for the question mark in the top right corner. Help is just a tap away!",
    imagePath: "assets/gen-lifebelt.svg"
  ),
];


class OnboardingPage extends ConsumerStatefulWidget {
  const OnboardingPage({super.key});

  @override
  ConsumerState<OnboardingPage> createState() => _OnboardingPageState();
}

class _OnboardingPageState extends ConsumerState<OnboardingPage> {
  final PageController _controller = PageController();
  late List<Widget> fullCards;



  @override
  Widget build(BuildContext context) {

    Widget agreementCard = OnboardingAgreementCard(
      title: "The annoying stuff",
      description: "By using anyway, you agree to our terms and conditions and privacy policy. We don't use cookies or tracking, we don't store the data you submit. We are not responsible for any damage or loss caused by using anyway.",
      imagePath: "assets/con-warning.svg",
      agreementTextPath: "assets/terms_and_conditions.md",
      onAgreementChanged: onAgreementChanged,
    );
    // need to add the agreement from within the function because it needs to be able to call setState
    fullCards = onboardingCards + [agreementCard];


    return Scaffold(
      body: Stack(
        children: [
          AnimatedBuilder(
            animation: _controller,
            builder: (context, child) {
              return Stack(
                children: [
                  Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: APP_GRADIENT.colors,
                        stops: [
                          (_controller.hasClients ? (_controller.page ?? _controller.initialPage) : _controller.initialPage) / onboardingCards.length,
                          (_controller.hasClients ? (_controller.page ?? _controller.initialPage) + 1 : _controller.initialPage + 1) / onboardingCards.length,
                        ],
                      ),
                    ),
                  ),
                  BackdropFilter(
                    filter: ImageFilter.blur(sigmaX: 100, sigmaY: 100),
                    child: Container(
                      color: Colors.black.withValues(alpha: 0.2)
                    ),
                  ),
                ],
              );
            },
          ),
          PageView(
            controller: _controller,
            children: List.generate(
              fullCards.length,
              (index) {
                return Container(
                  alignment: Alignment.center,
                  child: fullCards[index],
                );
              }
            ),
          ),
        ],
      ),

      floatingActionButton: nextButton(_controller)
    );
  }

  Widget nextButton(PageController controller) => AnimatedBuilder(
    animation: _controller,
    builder: (context, child) {
      if ((_controller.hasClients ? (_controller.page ?? _controller.initialPage) : 0) != fullCards.length - 1) {
        return FloatingActionButton.extended(
          onPressed: () {
            controller.nextPage(duration: const Duration(milliseconds: 500), curve: Curves.ease);
          },
          label: const Icon(Icons.arrow_forward)
        );
      } else {
          // only allow the user to proceed if they have agreed to the terms and conditions
          // the information is accessible through ref.watch(onboardingStateProvider)

          Widget disabledWidget = FloatingActionButton.extended(
            onPressed: null,
            label: const Row(
              children: [
                Text("Start planning!"),
                Padding(padding: EdgeInsets.only(right: 8.0)),
                Icon(Icons.map_outlined)
              ],
            )
          );

          return ref.watch(onboardingStateProvider).when(
            data: (isOnboarded) {
              if (isOnboarded) {
                return FloatingActionButton.extended(
                  onPressed: () {
                    // proceed to the next page - pop the onboarding page so the StartPage can decide what to show next
                    Navigator.of(context).pop();
                  },
                  label: const Row(
                    children: [
                      Text("Start planning!"),
                      Padding(padding: EdgeInsets.only(right: 8.0)),
                      Icon(Icons.map_outlined)
                    ],
                  )
                );
              } else {
                return disabledWidget;
              }
            },
            loading: () => disabledWidget,
            error: (error, stack) => disabledWidget,
          );
      }
    }
  );

  void onAgreementChanged(bool value) async {
      await ref.read(onboardingControllerProvider).setOnboarded(value);

    setState(() {
      // rebuild to show the next button

    });
  }
}
