import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/bloc/device_mgmt_bloc/device_managment_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_bloc.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/bloc/setting_bloc_state.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/device_icon_type_helper.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/device_management_content.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/remove_device_widget.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/device_info_model.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/settings_model/sub_space_model.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:syncrow_web/web_layout/default_container.dart';

class DeviceSettingsPanel extends StatelessWidget {
  final VoidCallback? onClose;
  final AllDevicesModel device;
  final DeviceManagementBloc deviceManagementBloc;
  const DeviceSettingsPanel({
    super.key,
    this.onClose,
    required this.device,
    required this.deviceManagementBloc,
  });

  @override
  Widget build(BuildContext context) {
    final sectionTitle = context.theme.textTheme.titleMedium!.copyWith(
      fontWeight: FontWeight.bold,
      color: ColorsManager.grayColor,
    );
    return BlocProvider(
      create: (context) => SettingDeviceBloc(
        deviceId: device.uuid ?? '',
      )
        ..add(DeviceSettingInitialInfo())
        ..add(SettingBlocFetchRooms(
          communityUuid: device.community!.uuid!,
          spaceUuid: device.spaces!.first.uuid!,
        )),
      child: Builder(
        builder: (context) {
          return BlocBuilder<SettingDeviceBloc, DeviceSettingsState>(
            builder: (context, state) {
              final _bloc = context.read<SettingDeviceBloc>();
              final iconPath = DeviceIconTypeHelper.getDeviceIconByTypeCode(
                  device.productType);
              final deviceInfo = state is DeviceSettingsUpdate
                  ? state.deviceInfo ?? DeviceInfoModel.empty()
                  : DeviceInfoModel.empty();
              final subSpaces =
                  state is DeviceSettingsUpdate ? state.roomsList ?? [] : [];
              return Stack(
                children: [
                  Container(
                    width: MediaQuery.of(context).size.width * 0.3,
                    color: ColorsManager.grey25,
                    padding: const EdgeInsets.all(10),
                    child: ListView(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            IconButton(
                              icon: SvgPicture.asset(Assets.closeSettingsIcon),
                              onPressed:
                                  onClose ?? () => Navigator.of(context).pop(),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              'Device Settings',
                              style: context.theme.textTheme.titleLarge!
                                  .copyWith(
                                  fontWeight: FontWeight.w700,
                                      color: ColorsManager.vividBlue
                                          .withOpacity(0.7),
                                  fontSize: 24),
                            ),
                          ],
                        ),
                        const SizedBox(height: 24),
                        DefaultContainer(
                          borderRadius: BorderRadius.circular(15),
                          child: Row(
                            children: [
                              Padding(
                                padding: const EdgeInsets.only(left: 15),
                                child: CircleAvatar(
                                  radius: 38,
                                  backgroundColor:
                                      ColorsManager.grayBorder.withOpacity(0.5),
                                  child: CircleAvatar(
                                    backgroundColor: ColorsManager.whiteColors,
                                    radius: 36,
                                    child: SvgPicture.asset(
                                      iconPath,
                                      fit: BoxFit.cover,
                                    ),
                                  ),
                                ),
                              ),
                              const SizedBox(width: 25),
                              Expanded(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.start,
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    const SizedBox(height: 15),
                                    Text(
                                      'Device Name:',
                                      style: context.textTheme.bodyMedium!
                                          .copyWith(
                                        color: ColorsManager.grayColor,
                                      ),
                                    ),
                                    SizedBox(
                                      height: 35,
                                      child: Row(
                                        children: [
                                          SizedBox(
                                            height: 50,
                                            width: 190,
                                            child: TextFormField(
                                              scrollPadding: EdgeInsets.zero,
                                              maxLength: 30,
                                              style: const TextStyle(
                                                color: ColorsManager.blackColor,
                                                fontSize: 16,
                                              ),
                                              textAlign: TextAlign.start,
                                              focusNode: _bloc.focusNode,
                                              controller: _bloc.nameController,
                                              enabled: _bloc.editName,
                                              onFieldSubmitted: (value) {
                                                _bloc.add(const ChangeNameEvent(
                                                    value: false));
                                                deviceManagementBloc
                                                    ..add(UpdateDeviceName(
                                                        deviceId: device.uuid!,
                                                        newName: _bloc
                                                            .nameController
                                                            .text))..add(ResetSelectedDevices());
                                              },
                                              decoration:const InputDecoration(
                                                isDense: true,
                                                contentPadding: EdgeInsets.zero,
                                                border: InputBorder.none,
                                                fillColor: Colors.white10,
                                                counterText: '',
                                              ),
                                            ),
                                          ),
                                          Column(
                                            children: [
                                              SizedBox(
                                                width: 15,
                                                height: 25,
                                                child: Visibility(
                                                  visible:
                                                      _bloc.editName != true,
                                                  replacement: const SizedBox(),
                                                  child: InkWell(
                                                    onTap: () {
                                                      _bloc.add(
                                                          const ChangeNameEvent(
                                                          value: true));
                                                    },
                                                    child: SvgPicture.asset(
                                                      Assets
                                                          .editNameIconSettings,
                                                      color: ColorsManager
                                                          .lightGrayBorderColor,
                                                      height: 15,
                                                      width: 15,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 32),
                        Padding(
                          padding: const EdgeInsets.only(left: 10),
                          child: Text('Device Management', style: sectionTitle),
                        ),
                        DeviceManagementContent(
                          device: device,
                          subSpaces: subSpaces.cast<SubSpaceModel>(),
                          deviceInfo: deviceInfo,
                          deviceManagementBloc: deviceManagementBloc,
                        ),
                        const SizedBox(height: 32),
                        RemoveDeviceWidget(bloc: _bloc),
                      ],
                    ),
                  ),
                  if (state is DeviceSettingsLoading)
                    Positioned.fill(
                      child: Container(
                        color: Colors.black.withOpacity(0.1),
                        child: const Center(
                          child: CircularProgressIndicator(
                            color: ColorsManager.primaryColor,
                          ),
                        ),
                      ),
                    ),
                ],
              );
            },
          );
        },
      ),
    );
  }
}
