import 'package:comunic/enums/user_page_visibility.dart';
import 'package:comunic/helpers/database/users_database_helper.dart';
import 'package:comunic/helpers/settings_helper.dart';
import 'package:comunic/models/general_settings.dart';
import 'package:comunic/ui/dialogs/multi_choices_dialog.dart';
import 'package:comunic/ui/dialogs/virtual_directory_dialog.dart';
import 'package:comunic/ui/widgets/async_screen_widget.dart';
import 'package:comunic/ui/widgets/settings/multi_choices_settings_tile.dart';
import 'package:comunic/ui/widgets/settings/text_settings_edit_tile.dart';
import 'package:comunic/utils/account_utils.dart';
import 'package:comunic/utils/input_utils.dart';
import 'package:comunic/utils/intl_utils.dart';
import 'package:comunic/utils/ui_utils.dart';
import 'package:flutter/material.dart';
import 'package:settings_ui/settings_ui.dart';

/// General account settings
///
/// @author Pierre HUBERT

class GeneralAccountSettingsScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("General settings"),
      ),
      body: _GeneralAccountSettingsBody(),
    );
  }
}

class _GeneralAccountSettingsBody extends StatefulWidget {
  @override
  __GeneralAccountSettingsBodyState createState() =>
      __GeneralAccountSettingsBodyState();
}

class __GeneralAccountSettingsBodyState
    extends State<_GeneralAccountSettingsBody> {
  GeneralSettings _settings;

  final _key = GlobalKey<AsyncScreenWidgetState>();

  @override
  void dispose() {
    // Remove current user information to force refresh of account image
    UsersDatabaseHelper().delete(userID());

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AsyncScreenWidget(
      key: _key,
      onReload: () async =>
          _settings = await SettingsHelper.getGeneralSettings(),
      onBuild: _buildSettings,
      errorMessage: tr("Could not load general settings!"),
      showOldDataWhileUpdating: true,
    );
  }

  Widget _buildSettings() {
    return SettingsList(
      sections: [
        SettingsSection(
          title: tr("Main account information"),
          tiles: _mainInformationTiles(),
        ),
        SettingsSection(
          title: tr("Your page settings"),
          tiles: _pageSettingsTiles(),
        )
      ],
    );
  }

  List<SettingsTile> _mainInformationTiles() {
    return [
      SettingsTile(
        title: tr("User ID"),
        subtitle: "${userID()}",
      ),
      SettingsTile(
        title: tr("Email address"),
        subtitle: _settings.email,
      ),

      // First name
      TextEditSettingsTile(
        title: tr("First name"),
        currValue: _settings.firstName,
        onChanged: (s) {
          _settings.firstName = s;
          _updateSettings();
        },
        checkInput: (s) => s.length >= 3,
      ),

      // Last name
      TextEditSettingsTile(
        title: tr("Last name"),
        currValue: _settings.lastName,
        onChanged: (s) {
          _settings.lastName = s;
          _updateSettings();
        },
        checkInput: (s) => s.length >= 3,
      ),

      // Emails settings
      SettingsTile.switchTile(
        title: tr("Allow comunic to send emails"),
        onToggle: (s) {
          _settings.allowComunicEmails = s;
          _updateSettings();
        },
        switchValue: _settings.allowComunicEmails,
      ),
    ];
  }

  List<MultiChoiceEntry> get _visibilityChoices => [
        MultiChoiceEntry(
            id: UserPageVisibility.PRIVATE,
            title: tr("Private"),
            subtitle: tr("Private, accessible only to your friends")),
        MultiChoiceEntry(
            id: UserPageVisibility.PUBLIC,
            title: tr("Public"),
            subtitle: tr("Public, accessible to all Comunic members")),
        MultiChoiceEntry(
            id: UserPageVisibility.OPEN,
            title: tr("Open"),
            subtitle:
                tr("Accessible to everyone, including non-Comunic users")),
      ];

  /// Build page settings tile
  List<SettingsTile> _pageSettingsTiles() {
    return [
      // Page visibility
      MultiChoicesSettingsTile(
          title: tr("Page visibility"),
          choices: _visibilityChoices,
          currentValue: _settings.pageVisibility,
          onChanged: (v) {
            _settings.pageVisibility = v;
            _updateSettings();
          }),

      // Allow comments on user page ?
      SettingsTile.switchTile(
        title: tr("Allow comments on your page"),
        onToggle: (v) {
          _settings.allowComments = v;
          _updateSettings();
        },
        switchValue: _settings.allowComments,
      ),

      // Allow posts from friends
      SettingsTile.switchTile(
        title: tr("Allow posts from your friends on your page"),
        onToggle: (v) {
          _settings.allowPostsFromFriends = v;
          _updateSettings();
        },
        switchValue: _settings.allowPostsFromFriends,
      ),

      // Make friends list public
      SettingsTile.switchTile(
        title: tr("Make your friends list public"),
        onToggle: (v) {
          _settings.publicFriendsList = v;
          _updateSettings();
        },
        switchValue: _settings.publicFriendsList,
      ),

      // Personal website
      TextEditSettingsTile(
        title: tr("Personal website URL (optional)"),
        currValue: _settings.personalWebsite,
        onChanged: (v) {
          _settings.personalWebsite = v;
          _updateSettings();
        },
        checkInput: (s) => validateUrl(s),
        allowEmptyValues: true,
      ),

      // Public notes
      TextEditSettingsTile(
        title: tr("Public note (optional)"),
        currValue: _settings.publicNote,
        onChanged: (v) {
          _settings.publicNote = v;
          _updateSettings();
        },
        allowEmptyValues: true,
        maxLength: 255,
        maxLines: 3,
      ),

      // Virtual directory
      SettingsTile(
        title: tr("Virtual directory (optional)"),
        subtitle: _settings.virtualDirectory,
        onTap: () async {
          final dir = await showVirtualDirectoryDialog(
              context: context,
              initialDirectory: _settings.virtualDirectory,
              type: VirtualDirectoryTargetType.USER,
              id: userID());

          if (dir == null) return;

          _settings.virtualDirectory = dir;
          _updateSettings();
        },
      ),
    ];
  }

  /// Apply new settings
  Future<void> _updateSettings() async {
    try {
      await SettingsHelper.updateGeneralSettings(_settings);
    } catch (e, stack) {
      print("Error while updating settings! $e/n$stack");
      showSimpleSnack(context, tr("Could not update general settings!"));
    }
    _key.currentState.refresh();
  }
}