import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/providers/user_provider.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/home/settings/profile/widgets/profile_photo.dart';
import 'package:didvan/views/home/widgets/menu_item.dart';
import 'package:didvan/views/widgets/animated_visibility.dart';
import 'package:didvan/views/widgets/didvan/button.dart';
import 'package:didvan/views/widgets/didvan/card.dart';
import 'package:didvan/views/widgets/didvan/divider.dart';
import 'package:didvan/views/widgets/didvan/scaffold.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 Profile extends StatefulWidget {
  const Profile({Key? key}) : super(key: key);

  @override
  State<Profile> createState() => _ProfileState();
}

class _ProfileState extends State<Profile> {
  Timer? _timer;

  late String fullName;
  String? username;
  String? email;
  bool _usernameIsAvailible = true;

  final _formKey = GlobalKey<FormState>();

  @override
  void initState() {
    final user = context.read<UserProvider>().user;
    fullName = user.fullName;
    username = user.username;
    email = user.email;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<UserProvider>(
      builder: (context, state, child) => Material(
        child: Stack(
          children: [
            Form(
              key: _formKey,
              child: DidvanScaffold(
                padding: const EdgeInsets.only(left: 16, right: 16, bottom: 92),
                appBarData: AppBarData(title: 'ویرایش پروفایل'),
                children: [
                  const ProfilePhoto(),
                  const SizedBox(height: 16),
                  DidvanCard(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        DidvanTextField(
                          title: 'نام و نام‌ خانوادگی',
                          hintText: 'نام و نام خانوادگی',
                          initialValue: state.user.fullName,
                          onChanged: (value) {
                            _setButtonState();
                            fullName = value;
                          },
                        ),
                        const SizedBox(height: 16),
                        DidvanTextField(
                          title: 'موبایل',
                          enabled: false,
                          hintText: state.user.phoneNumber,
                        ),
                        const SizedBox(height: 16),
                        DidvanTextField(
                          title: 'نام کاربری',
                          hintText: 'انتخاب نام کاربری (اختیاری)',
                          onChanged: _onUsernameChanged,
                          initialValue: state.user.username,
                        ),
                        AnimatedVisibility(
                          duration: DesignConfig.lowAnimationDuration,
                          isVisible: !_usernameIsAvailible,
                          child: DidvanText(
                            'نام کاربری در دسترس نمی‌باشد',
                            style: Theme.of(context).textTheme.caption,
                            color: Theme.of(context).colorScheme.error,
                          ),
                        ),
                        const SizedBox(height: 16),
                        DidvanTextField(
                          title: 'ایمیل',
                          hintText: 'مثال: example@email.com',
                          onChanged: (value) {
                            _setButtonState();
                            email = value;
                          },
                          initialValue: state.user.email,
                          validator: (value) {
                            if (value.isEmpty) return null;
                            bool emailValid = RegExp(
                                    r"^[a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+")
                                .hasMatch(value);
                            if (!emailValid) {
                              return 'ایمیل وارد شده معتبر نمی‌باشد';
                            }
                            return null;
                          },
                        ),
                        // const SizedBox(height: 16),
                        // DidvanSwitch(
                        //   value: true,
                        //   title: 'ورود با اثر انگشت',
                        //   onChanged: (value) => {},
                        // ),
                        const DidvanDivider(),
                        MenuItem(
                          title: 'تغییر رمز عبور',
                          onTap: () => Navigator.of(context).pushNamed(
                            Routes.authenticaion,
                            arguments: true,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Positioned(
              left: 20,
              right: 20,
              bottom: 20,
              child: DidvanButton(
                key: UniqueKey(),
                title: 'ذخیره تغییرات',
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    state.editProfile(fullName, username, email);
                  }
                },
                enabled: _buttonEnabled,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _setButtonState() {
    if (!_buttonEnabled) {
      setState(() {});
    }
  }

  bool get _buttonEnabled {
    final user = context.read<UserProvider>().user;
    return !(user.email == email &&
        user.fullName == fullName &&
        user.username == username);
  }

  void _onUsernameChanged(String value) {
    _usernameIsAvailible = true;
    _setButtonState();
    username = value;
    _timer?.cancel();
    if (value.length < 5) {
      return;
    }
    _timer = Timer(const Duration(seconds: 1), () {
      context.read<UserProvider>().checkUsername(value).then((value) {
        if (value == false) {
          setState(() {
            _usernameIsAvailible = false;
          });
        }
      });
    });
  }
}
