import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../product/constant/app/app_constants.dart';
import 'profile/profile_screen.dart';
import '../../product/constant/icon/icon_constants.dart';
import '../../product/extention/context_extention.dart';
import '../../product/services/api_services.dart';
import 'profile/profile_model.dart';
import 'settings_bloc.dart';
import '../../product/base/bloc/base_bloc.dart';
import '../../product/services/language_services.dart';

class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  late SettingsBloc settingsBloc;
  User user = User();
  APIServices apiServices = APIServices();
  @override
  void initState() {
    super.initState();
    settingsBloc = BlocProvider.of(context);
    getUserProfile();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(appLocalization(context).profile_page_title),
        centerTitle: true,
      ),
      body: StreamBuilder<User>(
          stream: settingsBloc.streamUserProfile,
          initialData: user,
          builder: (context, userSnapshot) {
            return userSnapshot.data?.id == "" || user.id == ""
                ? Center(
                    child: CircularProgressIndicator(
                      value: context.highValue,
                    ),
                  )
                : Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      CircleAvatar(
                        radius: 70,
                        child: CircleAvatar(
                          radius: 60,
                          child: CircleAvatar(
                            radius: 50,
                            child: Text(
                              getAvatarContent(
                                  userSnapshot.data?.username ?? ""),
                              style: const TextStyle(
                                  fontSize: 35, fontWeight: FontWeight.bold),
                            ),
                          ),
                        ),
                      ),
                      SizedBox(height: context.lowValue),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Text(
                            userSnapshot.data?.name ?? "User Name",
                            style: const TextStyle(
                                fontWeight: FontWeight.w900, fontSize: 26),
                          )
                        ],
                      ),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [Text(userSnapshot.data?.email ?? "Email")],
                      ),
                      SizedBox(height: context.mediumValue),
                      cardContent(
                        Icons.account_circle_rounded,
                        appLocalization(context).profile_change_info,
                      ),
                      SizedBox(height: context.lowValue),
                      cardContent(
                        Icons.lock_outline,
                        appLocalization(context).profile_change_pass,
                      ),
                      SizedBox(height: context.lowValue),
                      cardContent(
                        Icons.settings_outlined,
                        appLocalization(context).profile_setting,
                      ),
                      SizedBox(height: context.lowValue),
                      cardContent(
                        Icons.logout_outlined,
                        appLocalization(context).log_out,
                      ),
                    ],
                  );
          }),
    );
  }

  cardContent(IconData icon, String content) {
    return GestureDetector(
      onTap: () async {
        if (icon == Icons.account_circle_rounded) {
          changeUserInfomation(context, user, settingsBloc);
        } else if (icon == Icons.lock_outline) {
          changeUserPassword(context, settingsBloc);
        } else if (icon == Icons.settings_outlined) {
          context.push(ApplicationConstants.DEVICE_NOTIFICATIONS_SETTINGS);
        } else {
          await apiServices.logOut(context);
        }
      },
      child: Card(
        margin: const EdgeInsets.only(left: 35, right: 35, bottom: 10),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(30)),
        child: ListTile(
          leading: IconConstants.instance.getMaterialIcon(icon),
          title: Text(
            content,
            style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          trailing: const Icon(
            Icons.arrow_forward_ios_outlined,
          ),
        ),
      ),
    );
  }

  void getUserProfile() async {
    String data = await apiServices.getUserDetail();
    user = User.fromJson(jsonDecode(data));
    settingsBloc.sinkUserProfile.add(user);
  }

  String getAvatarContent(String username) {
    String name = "";
    if (username.isNotEmpty) {
      name = username[0].toUpperCase();
    }
    return name;
  }
}
