import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_app/features/app_layout/bloc/home_cubit.dart';
import 'package:syncrow_app/features/devices/bloc/device_settings_bloc/device_scene_bloc.dart';
import 'package:syncrow_app/features/devices/bloc/device_settings_bloc/device_scene_event.dart';
import 'package:syncrow_app/features/devices/bloc/device_settings_bloc/device_scene_state.dart';
import 'package:syncrow_app/features/devices/model/device_model.dart';
import 'package:syncrow_app/features/devices/view/device_settings/location_setting.dart';
import 'package:syncrow_app/features/shared_widgets/default_container.dart';
import 'package:syncrow_app/features/shared_widgets/default_scaffold.dart';
import 'package:syncrow_app/features/shared_widgets/text_widgets/body_medium.dart';
import 'package:syncrow_app/generated/assets.dart';
import 'package:syncrow_app/utils/resource_manager/color_manager.dart';

class SettingProfilePage extends StatelessWidget {
  final DeviceModel? device;

  const SettingProfilePage({super.key, this.device});

  @override
  Widget build(BuildContext context) {
    var spaces = HomeCubit.getInstance().spaces;

    return PopScope(
      canPop: false, 
      onPopInvoked: (didPop) {
        if (didPop) {
          return;
        }
        Navigator.of(context).pop(true);
      },
      child: DefaultScaffold(
        title: 'Device Settings',
        leading: IconButton(
            onPressed: () {
              Navigator.of(context).pop(true);
            },
            icon: const Icon(Icons.arrow_back_ios)),
        child: BlocProvider(
          create: (context) => DeviceSettingBloc(deviceId: device?.uuid ?? '')
            ..add(const DeviceSettingInitial())
            ..add(const DeviceSettingInitialInfo()),
          child: BlocBuilder<DeviceSettingBloc, DeviceSettingState>(
            builder: (context, state) {
              final _bloc = BlocProvider.of<DeviceSettingBloc>(context);
              return state is DeviceSettingLoadingState
                  ? const Center(
                      child: DefaultContainer(
                          width: 50,
                          height: 50,
                          child: CircularProgressIndicator()),
                    )
                  : RefreshIndicator(
                      onRefresh: () async {
                        _bloc.add(const DeviceSettingInitial());
                      },
                      child: ListView(
                        children: [
                          buildDeviceAvatar(context, device!),
                          const SizedBox(
                            height: 10,
                          ),
                          SizedBox(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                IntrinsicWidth(
                                  child: ConstrainedBox(
                                    constraints:
                                        const BoxConstraints(maxWidth: 200),
                                    child: TextFormField(
                                      maxLength: 30,
                                      style: const TextStyle(
                                        color: Colors.black,
                                      ),
                                      textAlign: TextAlign.center,
                                      focusNode: _bloc.focusNode,
                                      controller: _bloc.nameController,
                                      enabled: _bloc.editName,
                                      onEditingComplete: () {
                                        _bloc.add(const SaveNameEvent());
                                      },
                                      decoration: const InputDecoration(
                                        hintText: "Your Name",
                                        border: InputBorder.none,
                                        fillColor: Colors.white10,
                                        counterText: '',
                                      ),
                                    ),
                                  ),
                                ),
                                const SizedBox(width: 5),
                                InkWell(
                                  onTap: () {
                                    _bloc.add(
                                        const ChangeNameEvent(value: true));
                                  },
                                  child: Padding(
                                    padding:
                                        EdgeInsets.symmetric(horizontal: 10),
                                    child: SvgPicture.asset(
                                      Assets.sosEditProfile,
                                      color: Colors.grey,
                                      fit: BoxFit.contain,
                                      height:
                                          MediaQuery.of(context).size.height *
                                              0.02,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                          const SizedBox(height: 20),
                          const BodyMedium(
                            text: 'Smart Device Information',
                            fontWeight: FontWeight.w700,
                            fontSize: 12,
                            fontColor: ColorsManager.grayColor,
                          ),
                          const SizedBox(height: 7),
                          DefaultContainer(
                            padding: const EdgeInsets.all(20),
                            child: InkWell(
                              onTap: () async {
                                if (HomeCubit.visitorPasswordManagement) {
                                  bool? val = await Navigator.of(context).push(
                                    MaterialPageRoute(
                                        builder: (context) =>
                                            LocationSettingPage(
                                              space: spaces!.first,
                                              deviceId: device?.uuid ?? '',
                                            )),
                                  );
                                  if (val != null && val == true) {
                                    _bloc.add(const DeviceSettingInitialInfo());
                                  }
                                }
                              },
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  const SizedBox(
                                    child: Text('Location'),
                                  ),
                                  Row(
                                    children: [
                                      SizedBox(
                                        child: BodyMedium(
                                          text: _bloc
                                              .deviceInfo.subspace.subspaceName,
                                          fontColor: ColorsManager.textGray,
                                        ),
                                      ),
                                      const Icon(
                                        Icons.arrow_forward_ios,
                                        size: 15,
                                        color: ColorsManager.textGray,
                                      ),
                                    ],
                                  )
                                ],
                              ),
                            ),
                          )
                        ],
                      ),
                    );
            },
          ),
        ),
      ),
    );
  }

  Widget buildDeviceAvatar(BuildContext context, DeviceModel device) {
    final isSOSDevice = device.type == "SOS";

    final assetIcon = isSOSDevice
        ? Assets.sosHomeIcon
        : device.type == 'NCPS'
            ? Assets.flushIcon
            : device.type == '4S'
                ? Assets.fourSceneIcon
                : Assets.sixSceneIcon;

    final avatarRadius = isSOSDevice ? 52.0 : 60.0;
    final innerAvatarRadius = 55.0;
    final assetHeightFactor = isSOSDevice ? 0.13 : 0.08;

    return CircleAvatar(
      radius: avatarRadius,
      backgroundColor: Colors.white,
      child: ClipOval(
        child: isSOSDevice
            ? SvgPicture.asset(
                assetIcon,
                fit: BoxFit.fitHeight,
                height: MediaQuery.of(context).size.height * assetHeightFactor,
              )
            : CircleAvatar(
                radius: innerAvatarRadius,
                backgroundColor: ColorsManager.graysColor,
                child: Center(
                  child: SvgPicture.asset(
                    assetIcon,
                    fit: BoxFit.contain,
                    height:
                        MediaQuery.of(context).size.height * assetHeightFactor,
                  ),
                ),
              ),
      ),
    );
  }
}
