import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:go_router/go_router.dart';
import 'package:pharmacy_mobile/auth/auth_service.dart';
import 'package:pharmacy_mobile/blocs/guest/functions/bloc_getgueststatus.dart';
import 'package:pharmacy_mobile/functions/getlanguage_function.dart';
import 'package:pharmacy_mobile/tables/settings.dart';
import 'package:pharmacy_mobile/widgets/button_widget.dart';
import 'package:pharmacy_mobile/widgets/customer_pagebackground_widget.dart';
import 'package:pharmacy_mobile/widgets/customer_title_widget.dart';
import 'package:pharmacy_mobile/widgets/setting_widget.dart';
import 'package:pharmacy_mobile/widgets/snackbar_widget.dart';
import 'package:pharmacy_mobile/widgets/text_widget.dart';

class CustomerSettingsPage extends StatefulWidget {
  const CustomerSettingsPage({super.key});

  @override
  State<CustomerSettingsPage> createState() => _CustomerSettingsPageState();
}

class _CustomerSettingsPageState extends State<CustomerSettingsPage> {
  static const List<String> languageList = ['English', 'Tagalog', 'Hilogaynon (Ilonggo)', 'Cebuano (Bisaya)'];
  final _authService = AuthService();
  final _settings = Settings();

  late String currentName = '';
  late bool _isGuest = false;
  late String currentLanguage = '';

  void _signOut() async {
    // ignore: use_build_context_synchronously
    await _authService.signOut().then((_) => {context.go('/'), showNotification(context, 'Logged Out', true)});
  }

  Future<bool> _checkGuest() async {
    final guest = await blocGetGuestStatus(context);
    return guest;
  }

  Future<String> _getUsername() async {
    final username = _authService.getCurrentUser();
    return username ?? '';
  }

  void gotoSettings() async {
    await context.push('/languagesetting');
    // ignore: use_build_context_synchronously
    currentLanguage = await getLanguage(context);
    setState(() {});

    await Future.delayed(Duration(seconds: 1));
    final user = _authService.getCurrentUserId()!;
    final language = currentLanguage;
    final name = '';

    final exist = await _settings.checkExist(user);

    if (exist) {
      final updateSetting = await _settings.updateLanguage(user, currentLanguage);
      if (!updateSetting) {
        // ignore: use_build_context_synchronously
        showNotification(context, 'Settings not updated online', false);
      }
    } else {
      final settingsSaved = await _settings.postSettings(user, language, name);
      if (!settingsSaved) {
        // ignore: use_build_context_synchronously
        showNotification(context, 'Settings not saved online', false);
      }
    }
  }

  void autoRun() async {
    final guest = await _checkGuest();
    if (guest) {
      _isGuest = guest;
    } else {
      currentName = await _getUsername();
    }
    // ignore: use_build_context_synchronously
    currentLanguage = await getLanguage(context);
    setState(() {});
  }

  @override
  void initState() {
    autoRun();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: CustomerPagebackgroundWidget(
            child: Column(
      children: [
        if (currentLanguage == languageList[0])
          Column(
            children: [
              const Gap(68),
              const CustomerTitleWidget(),
              const Gap(32),
              const TextWidget(text: 'Settings'),
              const Gap(16),
              SettingWidget(
                  icon: Icons.language, title: 'Language', value: currentLanguage, onPressed: () => gotoSettings()),
              const Gap(8),
              SettingWidget(
                icon: Icons.person,
                title: 'Name',
                value: _isGuest ? 'Guest' : currentName,
              ),
              const Gap(32),
              ButtonWidget(text: 'Log Out', onPressed: _signOut)
            ],
          )
        else if (currentLanguage == languageList[1])
          Column(
            children: [
              const Gap(68),
              const CustomerTitleWidget(),
              const Gap(32),
              const TextWidget(text: 'Mga Setting'),
              const Gap(16),
              SettingWidget(
                  icon: Icons.language, title: 'Wika', value: currentLanguage, onPressed: () => gotoSettings()),
              const Gap(8),
              SettingWidget(
                icon: Icons.person,
                title: 'Pangalan',
                value: _isGuest ? 'Guest' : currentName,
              ),
              const Gap(32),
              ButtonWidget(text: 'Log Out', onPressed: _signOut)
            ],
          )
        else if (currentLanguage == languageList[2])
          Column(
            children: [
              const Gap(68),
              const CustomerTitleWidget(),
              const Gap(32),
              const TextWidget(text: 'Mga Setting'),
              const Gap(16),
              SettingWidget(
                  icon: Icons.language, title: 'Lenggwahe', value: currentLanguage, onPressed: () => gotoSettings()),
              const Gap(8),
              SettingWidget(
                icon: Icons.person,
                title: 'Ngalan',
                value: _isGuest ? 'Guest' : currentName,
              ),
              const Gap(32),
              ButtonWidget(text: 'Log Out', onPressed: _signOut)
            ],
          )
        else
          Column(children: [
            const Gap(68),
            const CustomerTitleWidget(),
            const Gap(32),
            const TextWidget(text: 'Mga Setting'),
            const Gap(16),
            SettingWidget(
                icon: Icons.language, title: 'Pinulongan', value: currentLanguage, onPressed: () => gotoSettings()),
            const Gap(8),
            SettingWidget(
              icon: Icons.person,
              title: 'Ngalan',
              value: _isGuest ? 'Guest' : currentName,
            ),
            const Gap(32),
            ButtonWidget(text: 'Log Outss', onPressed: _signOut),
          ])
      ],
    )));
  }
}
