// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:cached_memory_image/cached_memory_image.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:general_package/DB/db.dart';
import 'package:general_package/dynamic_form/src/view/dynamic_form_button.dart';
import 'package:general_package/responsive/responsive.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../constants/constants.dart';
import '../utils/paddings.dart';
import '../model/onboard_model.dart';

class OnboardBody extends StatelessWidget {
  final OnboardModel onboardModel;

  const OnboardBody({
    Key? key,
    required this.onboardModel,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Expanded(
          flex: 6,
          child: Padding(
          padding: GeneralConstants.instance.padding15.copyWith(bottom: 0),
            child: Text(
              onboardModel.title,
              style: Theme.of(context).textTheme.headline1,
              textAlign: TextAlign.left,
            ),
          ),
        ),
        const SizedBox(
          height: 10,
        ),
        Expanded(
          flex: 5,
          child: Padding(
            padding:GeneralConstants.instance.padding15,
            child: Text(
              onboardModel.description,
              style: Theme.of(context).textTheme.headline4,
            ),
          ),
        ),
        Expanded(
          flex: 25,
          child: CachedMemoryImage(
            uniqueKey: onboardModel.image,
            base64: onboardModel.image,
            filterQuality: FilterQuality.high,
            fit: BoxFit.cover,
            alignment: onboardModel.imageAlignment,
            width: double.infinity,
          ),
          // child: Image.memory(
          //   base64Decode(onboardModel.image),
          //   // onboardModel.image,
          //   filterQuality: FilterQuality.high,
          //   fit: BoxFit.fill,
          // ),
        ),
      ],
    );
  }
}

class PermissionOnboardBody extends StatefulWidget {
  final OnboardPermissionModel onboardPermissionModel;
  final Function removePermission;
  final int count;
  final String nextScreen;
  const PermissionOnboardBody({
    Key? key,
    required this.onboardPermissionModel,
    required this.removePermission,
    required this.count,
    required this.nextScreen,
  }) : super(key: key);

  @override
  State<PermissionOnboardBody> createState() => _PermissionOnboardBodyState();
}

class _PermissionOnboardBodyState extends State<PermissionOnboardBody> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkPermission();
  }

  riseRemoveAndRedirect() async {
    await widget.onboardPermissionModel.request.request().then((value) {
      if (kDebugMode) {
        print(
            "${widget.onboardPermissionModel.request} - $value - after request");
      }
      if (value.isGranted) {
        if (widget.count == 1) {
          // Navigator.pushNamed(context, nextScreen);
          LocalDB().writeData(GeneralConstants.instance.onBoardScreenShowedKey, "true");
          Get.toNamed(widget.nextScreen);
        } else {
          widget.removePermission();
        }
      }
    });
  }

  checkPermission() async {
    var status = await widget.onboardPermissionModel.request.status;
    if (kDebugMode) {
      print("$status - ${widget.onboardPermissionModel.request}");
    }
    if (status.isGranted) {
      if (widget.count == 1) {
        // Navigator.pushNamed(context, nextScreen);
          LocalDB().writeData(GeneralConstants.instance.onBoardScreenShowedKey, "true");
        Get.toNamed(widget.nextScreen);
      } else {
        widget.removePermission();
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const PaddingAll.low(),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            flex: 5,
            child: Text(
              widget.onboardPermissionModel.title,
              style: Theme.of(context).textTheme.headline1,
              textAlign: TextAlign.left,
            ),
          ),
          const Spacer(flex: 2),
          Expanded(
            flex: 12,
            child: Center(
              child: CachedMemoryImage(
                uniqueKey: widget.onboardPermissionModel.image,
                base64: widget.onboardPermissionModel.image,
                filterQuality: FilterQuality.high,
                fit: BoxFit.fill,
              ),
              // child: Image.memory(
              //   base64Decode(onboardPermissionModel.image),
              //   // onboardPermissionModel.image,
              //   filterQuality: FilterQuality.high,
              //   fit: BoxFit.fill,
              // ),
            ),
          ),
          const Spacer(flex: 3),
          Expanded(
              flex: 20,
              child: ListView.builder(
                itemCount:
                    widget.onboardPermissionModel.permissionDescription.length,
                itemBuilder: (context, index) => Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        SizedBox(
                          width: ScreenTypeData.fullWidth(context) * .55,
                          child: Text(
                            widget.onboardPermissionModel
                                .permissionDescription[index].title,
                            style: Theme.of(context).textTheme.subtitle1,
                            textAlign: TextAlign.left,
                          ),
                        ),
                        CachedMemoryImage(
                          uniqueKey: widget.onboardPermissionModel
                              .permissionDescription[index].image,
                          base64: widget.onboardPermissionModel
                              .permissionDescription[index].image,
                          fit: BoxFit.fill,
                          width: 120,
                        ),
                        // Card(
                        //   // elevation: 2,
                        //   shape: RoundedRectangleBorder(
                        //     borderRadius: BorderRadius.circular(15),
                        //     //set border radius more than 50% of height and width to make circle
                        //   ),
                        //   child: ClipRRect(
                        //     borderRadius: BorderRadius.circular(15.0),
                        //     child: CachedMemoryImage(
                        //       uniqueKey: onboardPermissionModel
                        //           .permissionDescription[index].image,
                        //       base64: onboardPermissionModel
                        //           .permissionDescription[index].image,
                        //       fit: BoxFit.fill,
                        //       width: 120,
                        //     ),
                        //     //   child: Image.memory(
                        //     //     base64Decode(
                        //     //       onboardPermissionModel
                        //     //           .permissionDescription[index].image,
                        //     //     ),
                        //     //     // onboardPermissionModel
                        //     //     //     .permissionDescription[index]
                        //     //     //     .image,
                        //     //     width: 120,
                        //     //     fit: BoxFit.fill,
                        //     //   ),
                        //   ),
                        // ),
                      ],
                    ),
                    const SizedBox(
                      height: 5,
                    )
                  ],
                ),
              )),
          Expanded(
              flex: 5,
              child: Center(
                child: DynamicFormButton.bgButton(context, "Grant Access",
                    onPressed: (() async {
                  var status =
                      await widget.onboardPermissionModel.request.status;
                  if (kDebugMode) {
                    print("$status - ${widget.onboardPermissionModel.request}");
                  }
                  if (status.isGranted) {
                    if (widget.count == 1) {
                      // Navigator.pushNamed(context, nextScreen);
                      LocalDB().writeData(GeneralConstants.instance.onBoardScreenShowedKey, "true");
                      Get.toNamed(widget.nextScreen);
                    } else {
                      widget.removePermission();
                    }
                  }
                  if (status.isDenied) {
                    await riseRemoveAndRedirect();
                    if (kDebugMode) {
                      print(
                          "${widget.onboardPermissionModel.request} - isDenied");
                    }
                  }
                  if (status.isPermanentlyDenied) {
                    await riseRemoveAndRedirect();
                    if (kDebugMode) {
                      print(
                          "${widget.onboardPermissionModel.request} - isPermanentlyDenied");
                    }
                  }
                  if (await widget
                      .onboardPermissionModel.request.isRestricted) {
                    await riseRemoveAndRedirect();
                    if (kDebugMode) {
                      print(
                          "${widget.onboardPermissionModel.request} - isRestricted");
                    }
                  }
                })),
              )),
        ],
      ),
    );
  }
}
