import 'package:didvan/config/design_config.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/utils/action_sheet.dart';
import 'package:didvan/views/profile/general_settings/settings_state.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/radial_button.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/flutter_svg.dart';
import 'package:provider/provider.dart';

import '../../../routes/routes.dart';

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

  @override
  State<GeneralSettings> createState() => _GeneralSettingsState();
}

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

  @override
  void initState() {
    super.initState();
    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: () {},
        state: context.read<GeneralSettingsState>(),
        builder: (context, state) => DidvanScaffold(
          padding: const EdgeInsets.all(16),
          appBarData: AppBarData(hasBack: true, title: 'تنظیمات'),
          children: [
            DidvanCard(
              child:
               MenuOption(
                title: 'زمان دریافت اعلان',
                onTap: () => Navigator.of(context).pushNamed(
                  Routes.notificationTime,
                  arguments: {
                    "fromFav": false,
                    'onTimeChanged': () => Future.delayed(
                          Duration.zero,
                          () => state.getTime(),
                        )
                  },
                ),
                icon: DidvanIcons.notification_solid,
                suffix: state.time,
                // suffix: 'از${DateTimeUtils.normalizeTimeDuration(
                //   Duration(minutes: state.notificationTimeRange[0]),
                // )} تا ${DateTimeUtils.normalizeTimeDuration(
                //   Duration(minutes: state.notificationTimeRange[1]),
                // )}',
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            DidvanCard(
              child: MenuOption(
                title: 'شخصی سازی محتوا',
                onTap: () => Navigator.of(context).pushNamed(
                    Routes.favouritesStep,
                    arguments: {"toTimer": false}),
                icon: DidvanIcons.note_solid,
                // suffix: 'از${DateTimeUtils.normalizeTimeDuration(
                //   Duration(minutes: state.notificationTimeRange[0]),
                // )} تا ${DateTimeUtils.normalizeTimeDuration(
                //   Duration(minutes: state.notificationTimeRange[1]),
                // )}',
              ),
            ),
            const ItemTitle(
              title: 'انتخاب قلم',
              icon: DidvanIcons.font_solid,
            ),
            DidvanCard(
              child: Column(
                children: [
                  MenuOption(
                    suffix: state.fontFamily == 'Dana-FA' 
                        ? 'دانا' 
                        : state.fontFamily == 'Iransans-FA'
                        ? 'ایران سنس'
                        : 'ایران یکان',
                    title: 'فونت برنامه',
                    onTap: _showFontFamilyBottomSheet,
                  ),
                  const DidvanDivider(),
                  MenuOption(
                    suffix: fontScaleSuffix(state.fontSizeScale),
                    title: 'اندازه متن',
                    onTap: _showFontScaleBottomSheet,
                  ),
                ],
              ),
            ),
            const ItemTitle(
              title: 'ظاهر برنامه',
              icon: DidvanIcons.theme_solid,
            ),
            DidvanCard(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _themeItem(context, state, 'light'),
                  _themeItem(context, state, 'dark'),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  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',
              ),
              const SizedBox(height: 24),
              DidvanRadialButton(
                title: 'ایران یکان',
                fontFamily: 'IranYekan',
                onSelected: () {
                  state.fontFamily = 'IranYekan';
                  setState(() {});
                },
                value: state.fontFamily == 'IranYekan',
              ),
            ],
          ),
        ),
        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 ? 'تیره' : 'روشن',
          ),
        ],
      ),
    );
  }
}
