import 'package:didvan/providers/server_data.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/authentication/authentication_state.dart';
import 'package:didvan/views/authentication/widgets/authentication_layout.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/didvan/text.dart';
import 'package:didvan/views/widgets/didvan/text_field.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

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

  @override
  State<PasswordInput> createState() => _PasswordInputState();
}

class _PasswordInputState extends State<PasswordInput> {
  final _formKey = GlobalKey<FormState>();

  @override
  Widget build(BuildContext context) {
    final AuthenticationState state = context.read<AuthenticationState>();
    return AuthenticationLayout(
      appBarTitle:
          'ورود با ${state.username.contains('09') ? 'شماره موبایل' : 'نام کاربری'} ${state.username}',
      children: [
        Form(
          key: _formKey,
          child: DidvanTextField(
            onChanged: (value) => state.password = value,
            onSubmitted: (value) => _onLogin(context),
            autoFocus: true,
            title: 'کلمه عبور',
            hintText: 'کلمه عبور',
            obsecureText: true,
            validator: (value) => value.length < 8
                ? 'کلمه عبور نمی‌تواند از 8 کاراکتر کمتر باشد'
                : null,
          ),
        ),
        const SizedBox(
          height: 32,
        ),
        GestureDetector(
          onTap: () => state.currentPageIndex++,
          child: DidvanText(
            'فراموشی رمز عبور',
            style: Theme.of(context).textTheme.titleSmall,
            color: Theme.of(context).colorScheme.primary,
          ),
        ),
        const Spacer(),
        DidvanButton(
          onPressed: () => _onLogin(context),
          title: 'ورود',
        ),
        const SizedBox(
          height: 48,
        ),
      ],
    );
  }

  Future<void> _onLogin(BuildContext context) async {
    if (!_formKey.currentState!.validate()) {
      return;
    }
    final state = context.read<AuthenticationState>();
    final userProvider = context.read<UserProvider>();
    final token = await state.login(userProvider);
    if (token != null) {
      await ServerDataProvider.getData();

      if (mounted) {
        await Future.delayed(
            Duration.zero,
            () => Navigator.of(context)
                .pushReplacementNamed(Routes.home, arguments: true));
      }
    }
  }
}
