import 'package:flutter/material.dart';

import 'package:flutter_timezone/flutter_timezone.dart';

import 'package:go_router/go_router.dart';

import 'package:provider/provider.dart';

import 'package:pshared/api/requests/login_data.dart';
import 'package:pshared/models/describable.dart';
import 'package:pshared/provider/locale.dart';
import 'package:pshared/provider/account.dart';

import 'package:pweb/app/router/pages.dart';
import 'package:pweb/pages/signup/form/content.dart';
import 'package:pweb/pages/signup/form/controllers.dart';
import 'package:pweb/pages/signup/form/form.dart';
import 'package:pweb/pages/signup/confirmation/args.dart';
import 'package:pweb/utils/error/snackbar.dart';

import 'package:pweb/generated/i18n/app_localizations.dart';


class SignUpFormState extends State<SignUpForm> {
  late final SignUpFormControllers controllers;
  final _formKey = GlobalKey<FormState>();
  bool _autoValidateMode = false;

  @override
  void initState() {
    super.initState();
    controllers = SignUpFormControllers();
  }

  Future<String?> signUp(
    BuildContext context,
    VoidCallback onSignUp,
    void Function(Object e) onError,
  ) async {
    final provider = Provider.of<AccountProvider>(context, listen: false);

    setState(() {
      _autoValidateMode = true;
    });

    if (!(_formKey.currentState?.validate() ?? false)) {
      return null;
    }

    try {
      final orgDescription = controllers.description.text.trim();
      final locs = AppLocalizations.of(context)!;
      final locale = context.read<LocaleProvider>().locale;
      final timezone = await FlutterTimezone.getLocalTimezone(locale.toString());
      await provider.signup(
        account: AccountData.build(
          login: LoginData.build(
            login: controllers.email.text.trim(), 
            password: controllers.password.text, 
            locale: locale.toLanguageTag(),
          ),
          name: controllers.firstName.text.trim(),
          lastName: controllers.lastName.text.trim(),
        ),
        organization: newDescribable(
          name: controllers.companyName.text.trim(),
          description: orgDescription.isEmpty ? null : orgDescription,
        ),
        timezone: timezone.identifier,
        ownerRole: newDescribable(
          name: locs.ownerRole,
          description: locs.ownerRoleDescription,
        ),
        cryptoWallet: newDescribable(
          name: locs.cryptoWallet,
          description: locs.cryptoWalletDesc,
        ),
        ledgerWallet: newDescribable(
          name: locs.ledgerWallet,
          description: locs.ledgerWalletDesc,
        ),
      );
      onSignUp();
      return 'ok';
    } catch (e) {
      onError(provider.error ?? e);
    }
    return null;
  }

  void handleSignUp() => signUp(
        context,
        () {
          context.goNamed(
            Pages.signupConfirm.name,
            extra: SignupConfirmationArgs(
              email: controllers.email.text.trim(),
              password: controllers.password.text,
            ),
          );
        },
        (e) => postNotifyUserOfErrorX(
          context: context,
          errorSituation: AppLocalizations.of(context)!.errorSignUp,
          exception: e,
        ),
      );

  void handleLogin() => navigateAndReplace(context, Pages.login);

  @override
  void dispose() {
    controllers.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) => SignUpFormContent(
        formKey: _formKey,
        controllers: controllers,
        autoValidateMode: _autoValidateMode,
        onSignUp: handleSignUp,
        onLogin: handleLogin,
      );
}
