import 'package:flutter/material.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:provider/provider.dart';
import 'package:test_sa/controllers/providers/api/user_provider.dart';
import 'package:test_sa/controllers/providers/settings/setting_provider.dart';
import 'package:test_sa/extensions/context_extension.dart';
import 'package:test_sa/extensions/int_extensions.dart';
import 'package:test_sa/extensions/text_extensions.dart';
import 'package:test_sa/extensions/widget_extensions.dart';
import 'package:test_sa/new_views/app_style/app_color.dart';
import 'package:test_sa/new_views/common_widgets/app_drawer.dart';
import 'package:test_sa/new_views/pages/login_page.dart';
import 'package:test_sa/new_views/swipe_module/circular_animated_widget.dart';
import 'package:test_sa/new_views/swipe_module/swipe_history_view.dart';
import 'package:test_sa/new_views/swipe_module/utils/swipe_general_utils.dart';
import 'package:test_sa/views/widgets/dialogs/dialog.dart';

class SwipeView extends StatefulWidget {
  static const String routeName = "/swipe-view";

  const SwipeView({
    Key? key,
  }) : super(key: key);

  @override
  State<SwipeView> createState() => _SwipeViewState();
}

class _SwipeViewState extends State<SwipeView> {
  late UserProvider _userProvider;
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    _userProvider = Provider.of<UserProvider>(context, listen: false);
    if (_userProvider.user != null) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _userProvider.getSwipeLastTransaction(userId: _userProvider.user!.userID!);
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool result = await showDialog(
          context: context,
          builder: (_) => AAlertDialog(title: context.translation.signOut, content: context.translation.logoutAlert),
        );
        if (result) {
          bool isSuccess = await Provider.of<UserProvider>(context, listen: false).logout(context);
          if (isSuccess) {
            Provider.of<SettingProvider>(context, listen: false).resetSettings();
            Provider.of<UserProvider>(context, listen: false).reset();
            Navigator.of(context).pushNamedAndRemoveUntil(LoginPage.routeName, (routes) => true);
          }
        }
        return false;
      },
      child: Scaffold(
        key: _scaffoldKey,
        drawer: const AppDrawer(),
        appBar: AppBar(
          automaticallyImplyLeading: false,
          backgroundColor: Theme.of(context).scaffoldBackgroundColor,
          titleSpacing: 0,
          title: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Consumer<UserProvider>(builder: (context, snapshot, _) {
                return CircleAvatar(
                  radius: 24,
                  backgroundColor: context.isDark ? AppColor.neutral50 : AppColor.neutral40,
                  child: Padding(
                    padding: const EdgeInsets.all(1), // Border radius
                    child: ClipOval(
                      child: snapshot.profileImage != null
                          ? Image.file(snapshot.profileImage!)
                          : (snapshot.user?.profilePhotoName?.isNotEmpty ?? false)
                              ? Image.network(snapshot.user!.profilePhotoName!)
                              : const Icon(Icons.person, size: 24, color: Colors.white),
                    ),
                  ),
                ).onPress(() {
                  _scaffoldKey.currentState!.isDrawerOpen ? _scaffoldKey.currentState!.closeDrawer() : _scaffoldKey.currentState!.openDrawer();
                });
              }),
            ],
          ).paddingOnly(start: 16, end: 16),
        ),
        body: Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: [
                Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      context.translation.welcome,
                      style: AppTextStyles.heading6.copyWith(color: context.isDark ? AppColor.neutral10 : AppColor.neutral20),
                    ),
                    Text(
                      _userProvider.user?.username ?? "",
                      style: AppTextStyles.heading2.copyWith(color: context.isDark ? AppColor.neutral30 : AppColor.neutral50, fontWeight: FontWeight.w600),
                    ),
                  ],
                ).paddingOnly(start: 16, end: 16, top: 8, bottom: 4),
                SwipeHistoryView().expanded,
              ],
            ),
            Positioned(
              right: 20.toScreenWidth,
              bottom: 60.toScreenHeight,
              child: GestureDetector(
                onTap: () async {
                  bool isNfcSupported = false;
                  try {
                    isNfcSupported = await NfcManager.instance.isAvailable();
                  } catch (e) {
                    isNfcSupported = false;
                  }
                  SwipeGeneralUtils.instance.showSwipeTypeBottomSheetSheet(isNfcSupported: isNfcSupported);
                },
                child: CircularAnimatedContainer(
                  child: Container(
                    width: 100.toScreenWidth,
                    height: 100.toScreenHeight,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColor.white10,
                      border: Border.all(color: AppColor.primary80.withOpacity(0.5), width: 2),
                    ),
                    child: Consumer<UserProvider>(builder: (context, userProvider, child) {
                      return Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          'swipe'.toSvgAsset(width: 32, height: 32),
                          8.height,
                          Text(
                            ("${context.translation.checkIn}\n${userProvider.swipeTransactionModel != null && userProvider.swipeTransactionModel.swipeTime != null ? SwipeGeneralUtils.instance.formatTimeOnly(userProvider.swipeTransactionModel.swipeTime!) : '--:--'}"),
                            style: AppTextStyles.bodyText2.copyWith(color: AppColor.neutral80, fontWeight: FontWeight.w500, fontFamily: "Poppins"),
                          ),
                        ],
                      );
                    }),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
