import 'dart:async';

import 'package:didvan/config/design_config.dart';
import 'package:didvan/models/view/app_bar_data.dart';
import 'package:didvan/providers/user.dart';
import 'package:didvan/routes/routes.dart';
import 'package:didvan/views/profile/edit_profile/widgets/profile_photo.dart';
import 'package:didvan/views/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 EditProfile extends StatefulWidget {
  const EditProfile({Key? key}) : super(key: key);

  @override
  State<EditProfile> createState() => _EditProfileState();
}

class _EditProfileState extends State<EditProfile> {
  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: [
            Container(
              padding: const EdgeInsets.only(bottom: 80),
              child: Form(
                key: _formKey,
                child: DidvanScaffold(
                  padding: const EdgeInsets.only(
                    top: 16,
                    left: 16,
                    right: 16,
                  ),
                  appBarData:
                      AppBarData(title: 'ویرایش پروفایل', hasBack: true),
                  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,
                            acceptSpace: false,
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            child: DidvanText(
                              'نام کاربری می‌تواند شامل کاراکترهای انگلیسی و اعداد باشد.',
                              style: Theme.of(context).textTheme.labelSmall,
                            ),
                          ),
                          AnimatedVisibility(
                            duration: DesignConfig.lowAnimationDuration,
                            isVisible: !_usernameIsAvailible,
                            child: DidvanText(
                              'نام کاربری در دسترس نمی‌باشد',
                              style: Theme.of(context).textTheme.bodySmall,
                              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(),
                          MenuOption(
                            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() &&
                      _usernameIsAvailible) {
                    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;
          });
        }
      });
    });
  }
}
