import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:provider/provider.dart';

import '../../../api/login_api_client.dart';
import '../../../controllers/localization/localization.dart';
import '../../../controllers/providers/settings/setting_provider.dart';
import '../../../controllers/providers/user_provider.dart';
import '../../../controllers/validator/validator.dart';
import '../../../models/subtitle.dart';
import '../../../models/user.dart';
import '../../app_style/colors.dart';
import '../../app_style/sizing.dart';
import '../../widgets/app_text_form_field.dart';
import '../../widgets/buttons/app_back_button.dart';
import '../../widgets/buttons/app_button.dart';
import '../../widgets/departments/department_button.dart';
import '../../widgets/hospitals/hospital_button.dart';
import '../../widgets/loaders/loading_manager.dart';

class ProfilePage extends StatefulWidget {
  static const String id = "/user/profile";

  const ProfilePage({super.key});

  @override
  ProfilePageState createState() => ProfilePageState();
}

class ProfilePageState extends State<ProfilePage> {
  late UserProvider _userProvider;
  late SettingProvider _settingProvider;
  late double _width;
  late double _height;
  User _user = User();
  bool _firstTime = true;
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    _userProvider = Provider.of<UserProvider>(context);
    _settingProvider = Provider.of<SettingProvider>(context);
    _width = MediaQuery.of(context).size.width;
    _height = MediaQuery.of(context).size.height;
    Subtitle subtitle = AppLocalization.of(context)!.subtitle!;
    if (_firstTime) {
      _user = User.fromJson(UserApiClient().user!.toJson());
      _firstTime = false;
    }
    return Scaffold(
      key: _scaffoldKey,
      body: LoadingManager(
        isLoading: _userProvider.loading,
        isFailedLoading: false,
        stateCode: 200,
        onRefresh: () async {},
        child: SafeArea(
          child: Stack(
            children: [
              Form(
                key: _formKey,
                child: ListView(
                  children: [
                    //AppNameBar(),
                    Hero(
                      tag: "logo",
                      child: Image(
                        height: _height / 4,
                        image: const AssetImage("assets/images/logo.png"),
                      ),
                    ),
                    Container(
                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      margin: const EdgeInsets.symmetric(horizontal: 16),
                      decoration: BoxDecoration(
                        color: AColors.primaryColor,
                        borderRadius: BorderRadius.circular(AppStyle.getBorderRadius(context)),
                        boxShadow: const [BoxShadow(color: AColors.grey, offset: Offset(0, -1))],
                      ),
                      child: Column(
                        children: [
                          ATextFormField(
                            initialValue: _user.userName,
                            hintText: subtitle.name,
                            enable: false,
                            prefixIconData: Icons.account_circle,
                            style: Theme.of(context).textTheme.titleLarge,
                            validator: (value) => Validator.hasValue(value!) ? '' : subtitle.nameValidateMessage,
                            onSaved: (value) {
                              _user.userName = value!;
                            },
                          ),
                          const SizedBox(height: 8),
                          ATextFormField(
                            initialValue: _user.email,
                            hintText: subtitle.email,
                            enable: false,
                            prefixIconData: Icons.email,
                            textInputType: TextInputType.emailAddress,
                            style: Theme.of(context).textTheme.titleLarge,
                            validator: (value) => Validator.isEmail(value!) ? '' : subtitle.emailValidateMessage,
                            onSaved: (value) {
                              _user.email = value!;
                            },
                          ),
                          const SizedBox(height: 8),
                          AbsorbPointer(
                            child: HospitalButton(
                              hospital: _user.hospital!,
                              onHospitalPick: (hospital) {
                                _user.hospital = hospital;
                                setState(() {});
                              },
                            ),
                          ),
                          const SizedBox(height: 8),
                          DepartmentButton(
                            department: _user.department,
                            onDepartmentPick: (department) {
                              _user.department = department;
                              setState(() {});
                            },
                          ),
                          const SizedBox(height: 8),
                          ATextFormField(
                            initialValue: _user.phoneNumber,
                            hintText: subtitle.phoneNumber,
                            style: Theme.of(context).textTheme.titleLarge,
                            prefixIconData: Icons.phone_android,
                            validator: (value) => Validator.isPhoneNumber(value!) ? '' : subtitle.phoneNumberValidateMessage,
                            textInputType: TextInputType.phone,
                            onSaved: (value) {
                              _user.phoneNumber = value;
                            },
                          ),
                          const SizedBox(height: 8),
                          ATextFormField(
                            initialValue: _user.whatsApp,
                            hintText: subtitle.whatsApp,
                            style: Theme.of(context).textTheme.titleLarge,
                            prefixIconData: FontAwesomeIcons.whatsapp,
                            prefixIconSize: 36,
                            validator: (value) => Validator.isPhoneNumber(value!) ? '' : subtitle.phoneNumberValidateMessage,
                            textInputType: TextInputType.phone,
                            onSaved: (value) {
                              _user.whatsApp = value;
                            },
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(height: 16),
                    Center(
                      child: SizedBox(
                        height: _width / 8,
                        width: _width / 1.2,
                        child: AButton(
                          text: subtitle.update,
                          onPressed: () async {
                            if (_formKey.currentState?.validate() ?? false) {
                              _formKey.currentState?.save();
                              await _userProvider.updateProfile(context, updatedUser: _user);
                            }
                          },
                        ),
                      ),
                    ),
                    const SizedBox(height: 32),
                  ],
                ),
              ),
              const ABackButton(),
            ],
          ),
        ),
      ),
    );
  }
}
