import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hamlemuhcrm/core/constants/color_constants.dart';
import 'package:hamlemuhcrm/core/extensions/responsive_extension.dart';
import 'package:hamlemuhcrm/core/utility/toast_manager.dart';
import 'package:hamlemuhcrm/features/auth/login/cubit/login_cubit.dart';
import 'package:hamlemuhcrm/features/profile/cubit/profile_cubit.dart';
import 'package:hamlemuhcrm/features/profile/model/profile_detail.dart';

import '../model/profile_constant_detail.dart';

final class ProfileUpdateBottomSheet extends StatefulWidget {
  final ProfileDetail currentData;
  final ProfileConstantDetail constantData;

  const ProfileUpdateBottomSheet({
    Key? key,
    required this.currentData,
    required this.constantData,
  }) : super(key: key);

  @override
  State<ProfileUpdateBottomSheet> createState() =>
      _ProfileUpdateBottomSheetState();
}

class _ProfileUpdateBottomSheetState extends State<ProfileUpdateBottomSheet> {
  ProfileDetail? updateData;

  bool isLoading = true;

  final TextEditingController passwordController = TextEditingController();
  final TextEditingController telNumberController = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      updateData = widget.currentData;
      setInitialValue();
      _changeLoading();
    });
    super.initState();
  }

  @override
  void dispose() {
    passwordController.dispose();
    telNumberController.dispose();
    super.dispose();
  }

  void _changeLoading() {
    setState(() {
      isLoading = !isLoading;
    });
  }

  void setInitialValue() {
    if (updateData == null) return;
    passwordController.text = updateData!.password;
    telNumberController.text = updateData!.telNumber;
  }

  Future<bool> profileChange(ProfileDetail model) async {
    final response =
        await context.read<ProfileCubit>().changeProfileUpdate(model);
    switch (response) {
      case true:
        return true;
      case false:
        return false;
    }
  }

  Future<bool> checkValidateTextField() async {
    if (telNumberController.text.isEmpty) {
      ToastManager.instance
          .toastMessageService('Telefon Numarası Boş Geçilemez!');
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    final textTheme = Theme.of(context).textTheme;
    return isLoading
        ? const Center(
            child: CircularProgressIndicator.adaptive(),
          )
        : _body(context, textTheme);
  }

  Widget _body(BuildContext context, TextTheme textTheme) => Scrollbar(
        radius: const Radius.circular(5),
        child: SingleChildScrollView(
            padding: const EdgeInsets.symmetric(horizontal: 20.00),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _description,
                _emptySpaceHeight,
                headLine(textTheme, "Ad Soyad"),
                customContainer(widget.constantData.fullName),
                _emptySpaceHeight,
                headLine(textTheme, "Giriş Yapılan Mail Adresi"),
                customContainer(widget.constantData.email),
                _emptySpaceHeight,
                headLine(textTheme, "Bildirimleri Alacağı Mail Adresi"),
                customContainer(widget.constantData.secondMail),
                _emptySpaceHeight,
                headLine(textTheme, "Şifre"),
                mainTextFieldContainer(passwordController, isPassword: true),
                _emptySpaceHeight,
                headLine(textTheme, "Telefon Numarası"),
                mainTextFieldContainer(telNumberController, isDone: true),
                _emptySpaceHeight,
                _saveButton,
              ],
            )),
      );

  Widget get _emptySpaceHeight => SizedBox(
        height: context.dynamicHeight(0.02),
      );

  Widget get _description => Text("Profil Düzenleme",
      style: Theme.of(context)
          .textTheme
          .titleMedium
          ?.copyWith(color: ColorsConstants.instance.baseTheme));

  Widget headLine(
    TextTheme textTheme,
    String txt,
  ) =>
      Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Text(
            txt,
            style: textTheme.titleSmall?.copyWith(
                color: Colors.grey.shade600, fontWeight: FontWeight.bold),
          )
        ],
      );

  Widget customContainer(String value) => Container(
        height: context.dynamicHeight(0.047),
        width: context.dynamicWidth(1),
        alignment: Alignment.centerLeft,
        margin: const EdgeInsets.only(top: 4.00),
        padding: const EdgeInsets.only(left: 5.00),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          color: Colors.grey.shade400,
        ),
        child: Text(
          value,
          style: Theme.of(context)
              .textTheme
              .titleSmall
              ?.copyWith(color: Colors.black54),
        ),
      );

  Widget mainTextFieldContainer(TextEditingController controller,
          {bool isPassword = false, bool isDone = false}) =>
      Padding(
        padding: const EdgeInsets.only(top: 4.00),
        child: TextFormField(
          cursorColor: ColorsConstants.instance.baseTheme,
          controller: controller,
          obscureText: isPassword,
          textInputAction:
              !isDone ? TextInputAction.next : TextInputAction.done,
          decoration: InputDecoration(
            constraints: BoxConstraints(
              maxHeight: context.dynamicHeight(0.047),
            ),
            filled: true,
            fillColor: Colors.grey.shade300,
            border: const OutlineInputBorder(borderSide: BorderSide.none),
            focusedBorder: const OutlineInputBorder(
              borderSide: BorderSide(color: Colors.grey),
            ),
            contentPadding:
                const EdgeInsets.symmetric(horizontal: kToolbarHeight / 5),
          ),
        ),
      );

  Widget get _saveButton => ElevatedButton(
        onPressed: () async {
          final updateData = ProfileDetail(
              password: passwordController.text,
              telNumber: telNumberController.text);
          await checkValidateTextField().then((value) async {
            if (!value) return;
            await profileChange(ProfileDetail(
                    telNumber: updateData.telNumber,
                    password: updateData.password,
                    loginId: context.read<LoginCubit>().id,
                    token: context.read<LoginCubit>().token,
                    userfirmId: context.read<LoginCubit>().userfirmId))
                .then((value) {
              if (!value) return;
              Navigator.pop(context, value);
            });
          });
        },
        style: ElevatedButton.styleFrom(
            backgroundColor: ColorsConstants.instance.baseTheme),
        child: Center(
          child: Text(
            "Güncelle",
            style: Theme.of(context)
                .textTheme
                .titleMedium
                ?.copyWith(color: ColorsConstants.instance.appWhite),
          ),
        ),
      );
}
