import 'package:didvan/config/design_config.dart';
import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/constants/assets.dart';
import 'package:didvan/models/view/action_sheet_data.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/providers/theme.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/services/storage/storage.dart';
import 'package:didvan/utils/action_sheet.dart';
import 'package:didvan/views/profile/general_settings/settings_state.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/radial_button.dart';
import 'package:didvan/views/widgets/menu_item.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/scaffold.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/item_title.dart';
import 'package:didvan/views/widgets/state_handlers/state_handler.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher_string.dart';

class ProfilePage extends StatefulWidget {
  const ProfilePage({Key? key}) : super(key: key);

  @override
  State<ProfilePage> createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  String fontScaleSuffix(double fontSizeScale) {
    final fontScale = fontSizeScale;
    if (fontScale == 1) return 'متوسط';
    if (fontScale == 1.15) return 'بزرگ';
    return 'کوچک';
  }

  @override
  void initState() {
    super.initState();
    context.read<GeneralSettingsState>().init();

    final state = context.read<GeneralSettingsState>();
    Future.delayed(
      Duration.zero,
      () => state.getTime(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<GeneralSettingsState>(
        builder: (context, state, child) => StateHandler<GeneralSettingsState>(
              onRetry: context.read<GeneralSettingsState>().init,
              state: context.read<GeneralSettingsState>(),
              builder: (context, state) => DidvanScaffold(
                padding: const EdgeInsets.all(16),
                appBarData: AppBarData(title: 'تنظیمات', hasBack: true),
                children: [
                  DidvanCard(
                    child: Column(
                      children: [
                        MenuOption(
                          title: 'ویرایش پروفایل',
                          icon: DidvanIcons.user_edit_regular,
                          suffix: context.watch<UserProvider>().user.fullName,
                          onTap: () => Navigator.of(context)
                              .pushNamed(Routes.editProfile),
                        ),
                        const DidvanDivider(),
                        MenuOption(
                            title: 'تنظیمات',
                            icon: DidvanIcons.setting_regular,
                            onTap: () {
                              state.showSettings = !state.showSettings;
                              state.update();
                            },
                            trailing: Icon(
                              state.showSettings
                                  ? DidvanIcons.angle_up_regular
                                  : DidvanIcons.angle_down_regular,
                              size: 18,
                              color: Theme.of(context).colorScheme.title,
                            )),
                        AnimatedVisibility(
                          duration: DesignConfig.lowAnimationDuration,
                          isVisible: state.showSettings,
                          child: Padding(
                            padding: const EdgeInsets.only(right: 8.0, top: 8),
                            child: Column(
                              children: [
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 12.0),
                                  child: MenuOption(
                                    title: 'زمان دریافت اعلان',
                                    onTap: () =>
                                        Navigator.of(context).pushNamed(
                                      Routes.notificationTime,
                                      arguments: {
                                        "fromFav": false,
                                        'onTimeChanged': () => Future.delayed(
                                              Duration.zero,
                                              () => state.getTime(),
                                            )
                                      },
                                    ),
                                    icon: DidvanIcons.notification_regular,
                                    suffix: state.time,
                                    // suffix: 'از${DateTimeUtils.normalizeTimeDuration(
                                    //   Duration(minutes: state.notificationTimeRange[0]),
                                    // )} تا ${DateTimeUtils.normalizeTimeDuration(
                                    //   Duration(minutes: state.notificationTimeRange[1]),
                                    // )}',
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 12.0),
                                  child: MenuOption(
                                    title: 'شخصی سازی محتوا',
                                    onTap: () => Navigator.of(context)
                                        .pushNamed(Routes.favouritesStep,
                                            arguments: {"toTimer": false}),
                                    icon: DidvanIcons.note_regular,
                                    // suffix: 'از${DateTimeUtils.normalizeTimeDuration(
                                    //   Duration(minutes: state.notificationTimeRange[0]),
                                    // )} تا ${DateTimeUtils.normalizeTimeDuration(
                                    //   Duration(minutes: state.notificationTimeRange[1]),
                                    // )}',
                                  ),
                                ),
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      vertical: 12.0),
                                  child: MenuOption(
                                    suffix: state.fontFamily == 'Dana-FA'
                                        ? 'دانا'
                                        : 'ایران سنس',
                                    title: 'فونت برنامه',
                                    onTap: _showFontFamilyBottomSheet,
                                    icon: DidvanIcons.font_regular,
                                  ),
                                ),
                                Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 12.0),
                                    child: MenuOption(
                                      suffix:
                                          fontScaleSuffix(state.fontSizeScale),
                                      title: 'اندازه متن',
                                      onTap: _showFontScaleBottomSheet,
                                      icon: DidvanIcons.font_size_solid,
                                    )),
                                Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 12.0),
                                    child: MenuOption(
                                        title: 'ظاهر برنامه',
                                        onTap: () {
                                          state.showThemes = !state.showThemes;
                                          state.update();
                                        },
                                        icon: DidvanIcons.theme_regular,
                                        trailing: Icon(
                                          state.showThemes
                                              ? DidvanIcons.angle_up_regular
                                              : DidvanIcons.angle_down_regular,
                                          size: 18,
                                          color: Theme.of(context)
                                              .colorScheme
                                              .title,
                                        ))),
                                AnimatedVisibility(
                                  duration: DesignConfig.lowAnimationDuration,
                                  isVisible: state.showThemes,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 12.0),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.spaceAround,
                                      children: [
                                        _themeItem(context, state, 'light'),
                                        _themeItem(context, state, 'dark'),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                        const DidvanDivider(),
                        MenuOption(
                          title: 'خروج از حساب کاربری',
                          icon: DidvanIcons.sign_out_regular,
                          color: Theme.of(context).colorScheme.secondary,
                          onTap: () async {
                            StorageService.delete(key: 'token');
                            Navigator.of(context).pushNamedAndRemoveUntil(
                              Routes.splash,
                              (_) => false,
                            );
                          },
                        ),
                      ],
                    ),
                  ),
                  const ItemTitle(
                    title: 'درباره ما',
                  ),
                  DidvanCard(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        MenuOption(
                          icon: DidvanIcons.info_circle_regular,
                          title: 'معرفی دیدوان',
                          onTap: () => launchUrlString(
                              'https://didvan.com/#info',
                              mode: LaunchMode.inAppWebView),
                        ),
                        const DidvanDivider(),
                        MenuOption(
                            icon: DidvanIcons.contact_us_solid,
                            title: 'تماس با ما',
                            onTap: () {
                              state.showContactUs = !state.showContactUs;
                              state.update();
                            },
                            trailing: Row(
                              children: [
                                if (state.unread > 0)
                                  Container(
                                    width: 12,
                                    height: 12,
                                    decoration: BoxDecoration(
                                      shape: BoxShape.circle,
                                      color: Theme.of(context)
                                          .colorScheme
                                          .secondary,
                                    ),
                                    alignment: Alignment.center,
                                  ),
                                const SizedBox(
                                  width: 12,
                                ),
                                Icon(
                                  state.showContactUs
                                      ? DidvanIcons.angle_up_regular
                                      : DidvanIcons.angle_down_regular,
                                  size: 18,
                                  color: Theme.of(context).colorScheme.title,
                                ),
                              ],
                            )),
                        AnimatedVisibility(
                            isVisible: state.showContactUs,
                            duration: DesignConfig.lowAnimationDuration,
                            fadeMode: FadeMode.vertical,
                            child: Padding(
                              padding:
                                  const EdgeInsets.only(right: 8.0, top: 8),
                              child: Column(
                                children: [
                                  Padding(
                                    padding: const EdgeInsets.symmetric(
                                        vertical: 12),
                                    child: MenuOption(
                                      icon: DidvanIcons.support_regular,
                                      title: 'پیام به پشتیبانی',
                                      onTap: () {
                                        Navigator.of(context).pushNamed(
                                          Routes.direct,
                                          arguments: {
                                            'type': 'پشتیبانی اپلیکیشن'
                                          },
                                        );
                                      },
                                    ),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(top: 12),
                                    child: MenuOption(
                                      icon: DidvanIcons.chats_regular,
                                      title: 'صندوق پیام',
                                      onTap: () {
                                        Navigator.of(context)
                                            .pushNamed(Routes.directList)
                                            .then(
                                              (value) => state.init(),
                                            );
                                      },
                                      trailing: Row(
                                        children: [
                                          if (state.unread > 0)
                                            Container(
                                              height: 18,
                                              padding:
                                                  const EdgeInsets.symmetric(
                                                      horizontal: 4),
                                              decoration: BoxDecoration(
                                                borderRadius: DesignConfig
                                                    .lowBorderRadius,
                                                color: Theme.of(context)
                                                    .colorScheme
                                                    .secondary,
                                              ),
                                              alignment: Alignment.center,
                                              child: DidvanText(
                                                state.unread.toString(),
                                                color: Colors.white,
                                                fontSize: 12,
                                              ),
                                            ),
                                          const SizedBox(
                                            width: 12,
                                          ),
                                          Icon(
                                            DidvanIcons.angle_left_regular,
                                            size: 18,
                                            color: Theme.of(context)
                                                .colorScheme
                                                .title,
                                          )
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            )),
                        const DidvanDivider(),
                        MenuOption(
                          icon: DidvanIcons.alert_regular,
                          title: 'حریم خصوصی',
                          onTap: () => launchUrlString(
                              'https://didvan.com/terms-of-use#privacy',
                              mode: LaunchMode.inAppWebView),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 16),
                  FutureBuilder<PackageInfo>(
                      future: PackageInfo.fromPlatform(),
                      builder: (context, snapshot) {
                        String version = '...';
                        if (snapshot.hasData && snapshot.data != null) {
                          version = snapshot.data!.version;
                        }
                        return DidvanText(
                          'نسخه نرم‌افزار: $version',
                          style: Theme.of(context).textTheme.bodySmall,
                        );
                      })
                ],
              ),
            ));
  }

  Future<void> _showFontFamilyBottomSheet() async {
    final themeProvider = context.read<ThemeProvider>();
    final state = context.read<GeneralSettingsState>();
    final family = state.fontFamily;

    await ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        content: StatefulBuilder(
          builder: (context, setState) => Column(
            children: [
              DidvanRadialButton(
                title: 'دانا',
                fontFamily: 'Dana-FA',
                onSelected: () {
                  state.fontFamily = 'Dana-FA';
                  setState(() {});
                },
                value: state.fontFamily == 'Dana-FA',
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'ایران سنس',
                fontFamily: 'Iransans-FA',
                onSelected: () {
                  state.fontFamily = 'Iransans-FA';
                  setState(() {});
                },
                value: state.fontFamily == 'Iransans-FA',
              ),
            ],
          ),
        ),
        title: 'انتخاب فونت برنامه',
        titleIcon: DidvanIcons.font_regular,
        onDismissed: () => state.fontFamily = family,
        onConfirmed: () => themeProvider.fontFamily = state.fontFamily,
      ),
    );
  }

  Future<void> _showFontScaleBottomSheet() async {
    final themeProvider = context.read<ThemeProvider>();
    final state = context.read<GeneralSettingsState>();
    final scale = state.fontSizeScale;

    await ActionSheetUtils(context).showBottomSheet(
      data: ActionSheetData(
        content: StatefulBuilder(
          builder: (context, setState) => Column(
            children: [
              DidvanRadialButton(
                title: 'بزرگ',
                fontSize: 15 * 1.15,
                onSelected: () {
                  state.fontSizeScale = 1.15;
                  setState(() {});
                },
                value: state.fontSizeScale == 1.15,
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'متوسط',
                onSelected: () {
                  state.fontSizeScale = 1;
                  setState(() {});
                },
                value: state.fontSizeScale == 1,
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'کوچک',
                fontSize: 15 * 0.85,
                onSelected: () {
                  state.fontSizeScale = 0.85;
                  setState(() {});
                },
                value: state.fontSizeScale == 0.85,
              ),
            ],
          ),
        ),
        title: 'انتخاب اندازه متن',
        titleIcon: DidvanIcons.font_regular,
        onDismissed: () => state.fontSizeScale = scale,
        onConfirmed: () => themeProvider.fontScale = state.fontSizeScale,
      ),
    );
  }

  Widget _themeItem(
      BuildContext context, GeneralSettingsState state, String brightness) {
    final bool isDarkTheme = brightness == 'dark';
    return GestureDetector(
      onTap: () {
        state.brightness = brightness;
        if (isDarkTheme && DesignConfig.isDark) {
          return;
        } else if (!isDarkTheme && !DesignConfig.isDark) {
          return;
        } else {
          if (isDarkTheme) {
            context.read<ThemeProvider>().themeMode = ThemeMode.dark;
          } else {
            context.read<ThemeProvider>().themeMode = ThemeMode.light;
          }
          DesignConfig.updateSystemUiOverlayStyle();
        }
      },
      child: Column(
        children: [
          SvgPicture.asset(isDarkTheme ? Assets.darkTheme : Assets.lightTheme),
          const SizedBox(height: 8),
          DidvanText(
            isDarkTheme ? 'تیره' : 'روشن',
          ),
        ],
      ),
    );
  }
}
