import 'dart:io';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:mnemo_cards/domain/router/app_router.dart';
import 'package:mnemo_cards/flags.dart';
import 'package:mnemo_cards/widgets/header.dart';
import 'package:mnemo_cards_common/mnemo_cards_common.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import '../admin/all_cards.dart';
import '../admin/all_users.dart';
import '../di/locator.dart';
import '../features/analytics/analytics.dart';
import '../theme/themes.dart';
import '../widgets/big_back_button.dart';
import '../widgets/shared_pref_button.dart';
import '../widgets/text_button.dart';

@RoutePage()
class ProfilePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Analytics.profilePageOpened(locator.userManager.userStateHolder.user);
    final theme = Theme.of(context).textTheme;
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            StreamBuilder(
                stream: locator.userManager.userStateHolder.asStream,
                builder: (context, snapshot) {
                  var title = snapshot.data?.name;
                  if (true || title == null || title.length > 10) {
                    title = 'Привет!';
                  }
                  return Header(
                    title,
                    popText: 'назад',
                    hasPopButton: true,
                    trail: GestureDetector(
                      onTap: () async {
                        await locator.userManager.logout();
                        final sp = await SharedPreferences.getInstance();
                        sp.clear();
                        AppRouter.openAuthOrProfile();
                      },
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          Image.asset(
                            'icons/exit.png',
                            width: 25.w,
                          ),
                        ],
                      ),
                    ),
                  );
                }),
            SizedBox(
              height: 40.h,
            ),
            if (ADMIN_BUILD)
              MaterialButton(
                onPressed: () {
                  showDialog(
                      context: context, builder: (c) => const AllCards());
                },
                child: Text('ALL CARDS'),
              ),
            if (ADMIN_BUILD)
              MaterialButton(
                onPressed: () {
                  showDialog(
                      context: context, builder: (c) => const AllUsers());
                },
                child: Text('ALL USERS'),
              ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0.w),
              child: Text(
                'Скоро тут будет прогресс, ачивки, настройки и другая важная информация',
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  fontSize: 16,
                  color: Colors.black,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0.w),
              child: Text(
                'А сейчас есть переключатель звука:',
                style: TextStyle(
                  fontWeight: FontWeight.w500,
                  fontSize: 16,
                  color: Colors.black,
                ),
                textAlign: TextAlign.center,
              ),
            ),
            Expanded(
              child: SharedPrefButton(
                enabledWidget: Image.asset(
                  'icons/sound_on.png',
                  width: 140.w,
                  height: 120.h,
                ),
                disabledWidget: Image.asset(
                  'icons/sound_off.png',
                  width: 140.w,
                  height: 120.h,
                ),
                spKey: 'sound_on',
              ),
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0.w),
              child: LinkButton(
                'Написать в тг',
                () => launchUrl(
                  Uri.parse('https://t.me/mnemo_cards_bot'),
                ),
              ),
            ),
            SizedBox(
              height: 30.0.h,
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Flexible(
                    child: LinkButton(
                      'Очистить кэш',
                      () async {
                        await locator.packManager.clearCache();
                        locator.testManager.clearStates();
                        await locator.packUpdater.updateAvailablePacks();
                      },
                    ),
                  ),
                  Flexible(
                    child: LinkButton(
                      'Страница в сторе',
                      () {},
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(
              height: 30.0.h,
            ),
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0.w),
              child: LinkButton(
                'Политика конфиденциальности',
                () {
                  launchUrl(
                    Uri.parse(
                        'https://www.freeprivacypolicy.com/live/1c2bce51-86c6-4a36-b226-b6c6f50ebf0f'),
                  );
                },
              ),
            ),
            // Padding(
            //   padding: EdgeInsets.symmetric(horizontal: 10.0.w),
            //   child: LinkButton(
            //     'Условия использования',
            //     () {
            //
            //     },
            //   ),
            // ),
            const BigBackButton(),
          ],
        ),
      ),
    );
  }

  Future<void> clearAndExit() async {
    final sp = await SharedPreferences.getInstance();
    sp.clear();
    exit(0);
  }

  const ProfilePage();
}
