import 'package:baseproject/core/common/index.dart';
import 'package:baseproject/core/components/index.dart';
import 'package:baseproject/features/model/login_dto.dart';
import 'package:baseproject/features/usecases/user_use_cases.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

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

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final GlobalKey<FormBuilderState> _formKey = GlobalKey<FormBuilderState>();
  bool _isLoading = false;
  String? _error;
  bool _rememberMe = false;

  Future<void> _onSubmit() async {
    final formState = _formKey.currentState;
    if (formState == null) return;

    if (!formState.saveAndValidate()) {
      return;
    }

    final value = formState.value;

    final dto = LoginDto(
      userName: value['userName'] as String?,
      password: value['password'] as String?,
      rememberMe: _rememberMe,
    );

    setState(() {
      _isLoading = true;
      _error = null;
    });

    final userUseCases = getItSuper<UserUseCases>();
    final result = await userUseCases.loginAccount(dto);

    result.fold(
      (l) => setState(() {
        _error = l;
        _isLoading = false;
      }),
      (r) {
        setState(() {
          _isLoading = false;
        });
        // TODO: điều hướng sang màn hình chính sau khi login thành công
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Đăng nhập'),
      ),
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: FormBuilder(
            key: _formKey,
            autovalidateMode: AutovalidateMode.onUserInteraction,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                if (_error != null)
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: Text(
                      _error!,
                      style: const TextStyle(color: Colors.red),
                    ),
                  ),
                FormControl(
                  labelText: 'Tên đăng nhập',
                  isShowTextRequire: true,
                  child: TextFormField(
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: 'Nhập tên đăng nhập',
                    ),
                    validator: FormBuilderValidators.required<String>(
                      context,
                    ),
                    onSaved: (value) {
                      _formKey.currentState?.setInternalFieldValue(
                        'userName',
                        value,
                        isUpdateState: false,
                      );
                    },
                  ),
                ),
                const SizedBox(height: 16),
                FormControl(
                  labelText: 'Mật khẩu',
                  isShowTextRequire: true,
                  child: TextFormField(
                    obscureText: true,
                    decoration: const InputDecoration(
                      border: OutlineInputBorder(),
                      hintText: 'Nhập mật khẩu',
                    ),
                    validator: FormBuilderValidators.required<String>(
                      context,
                    ),
                    onSaved: (value) {
                      _formKey.currentState?.setInternalFieldValue(
                        'password',
                        value,
                        isUpdateState: false,
                      );
                    },
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: <Widget>[
                    Checkbox(
                      value: _rememberMe,
                      onChanged: (v) {
                        setState(() {
                          _rememberMe = v ?? false;
                        });
                      },
                    ),
                    const Text('Ghi nhớ đăng nhập'),
                  ],
                ),
                const SizedBox(height: 24),
                SizedBox(
                  height: 48,
                  child: ElevatedButton(
                    onPressed: _isLoading ? null : _onSubmit,
                    child: _isLoading
                        ? const CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                          )
                        : const Text('Đăng nhập'),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
