import 'package:auto_route/auto_route.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:gap/gap.dart';
import 'package:krow/core/application/routing/routes.gr.dart';
import 'package:krow/core/presentation/gen/assets.gen.dart';
import 'package:krow/core/presentation/styles/kw_text_styles.dart';
import 'package:krow/core/presentation/styles/theme.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_app_bar.dart';
import 'package:krow/core/presentation/widgets/ui_kit/kw_button.dart';
import 'package:krow/features/profile/domain/bloc/personal_info_bloc.dart';

@RoutePage()
class ProfilePreviewScreen extends StatelessWidget {
  const ProfilePreviewScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          color: AppColors.primaryBlue,
          child: Assets.images.bgPattern.svg(
            fit: BoxFit.cover,
            width: double.infinity,
            height: double.infinity,
          ),
        ),
        Scaffold(
          backgroundColor: Colors.transparent,
          appBar: KwAppBar(
            contentColor: AppColors.grayWhite,
            titleText: 'Profile',
            centerTitle: false,
            backgroundColor: Colors.transparent,
          ),
          body: SingleChildScrollView(
            child: Container(
              padding: const EdgeInsets.all(12),
              margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 24),
              decoration: BoxDecoration(
                color: AppColors.bgProfileCard,
                borderRadius: BorderRadius.circular(12),
              ),
              child: BlocBuilder<PersonalInfoBloc, PersonalInfoState>(
                builder: (context, state) {
                  return Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      _buildUserPhoto(state.profileImageUrl, '${state.firstName} ${state.lastName}'),
                      const Gap(16),
                      _buildUserInfo(context, state),
                      const Gap(24),
                      KwButton.accent(
                          label: 'Edit Profile',
                          onPressed: () {
                            context.router.push(const PersonalInfoRoute());
                          }),
                      const Gap(12),
                      KwButton.outlinedPrimary(
                          label: 'Log Out',
                          onPressed: ()async  {
                            await FirebaseAuth.instance.signOut();
                            context.router.replace(const SplashRoute());
                          }).copyWith(color: AppColors.tintDarkRed),
                      const Gap(12),
                    ],
                  );
                },
              ),
            ),
          ),
        ),
      ],
    );
  }

  Container _buildUserPhoto(String? imageUrl, String? userName) {
    return Container(
      width: 174,
      height: 174,
      decoration: const BoxDecoration(
        shape: BoxShape.circle,
        color: AppColors.darkBgActiveButtonState,
      ),
      child: imageUrl == null || imageUrl.isEmpty
          ? Center(
              child: Text(
                getInitials(userName),
                style: AppTextStyles.headingH1.copyWith(
                  color: Colors.white,
                ),
              ),
            )
          : ClipOval(
              child: Image.network(
                imageUrl,
                fit: BoxFit.cover,
                width: 174,
                height: 174,
              ),
            ),
    );
  }

  Column _buildUserInfo(BuildContext context, PersonalInfoState state) {
    return Column(
      children: [
        Text(
          '${state.firstName} ${state.lastName}',
          style: AppTextStyles.headingH3.copyWith(color: Colors.white),
          textAlign: TextAlign.center,
        ),
        if (state.email.isNotEmpty) ...[
          const Gap(8),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Assets.images.icons.userProfile.sms.svg(
                colorFilter: const ColorFilter.mode(
                  AppColors.tintDropDownButton,
                  BlendMode.srcIn,
                ),
              ),
              const Gap(4),
              Text(
                state.email,
                style: AppTextStyles.bodyMediumReg
                    .copyWith(color: AppColors.tintDropDownButton),
              )
            ],
          ),
        ],
        if (state.phoneNumber.isNotEmpty) ...[
          const Gap(8),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Assets.images.icons.userProfile.call.svg(
                colorFilter: const ColorFilter.mode(
                  AppColors.tintDropDownButton,
                  BlendMode.srcIn,
                ),
              ),
              const Gap(4),
              Text(
                state.phoneNumber,
                style: AppTextStyles.bodyMediumReg
                    .copyWith(color: AppColors.tintDropDownButton),
              )
            ],
          ),
        ]
      ],
    );
  }

  String getInitials(String? name) {
  if (name == null || name.isEmpty) return '';
  if(name.trim().isEmpty) {
    return '';
  }
  List<String> nameParts = name.split(' ');
  if(nameParts.first.isEmpty) {
    return '';
  }
  if (nameParts.length == 1) {
    return nameParts[0].substring(0, 1).toUpperCase();
  }

  return (nameParts[0][0] + nameParts[1][0]).toUpperCase();
}
}


