import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/common/buttons/default_button.dart';
import 'package:syncrow_web/pages/common/custom_table.dart';
import 'package:syncrow_web/pages/common/filter/filter_widget.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/all_devices/widgets/device_search_filters.dart';
import 'package:syncrow_web/pages/device_managment/device_setting/device_settings_panel.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_batch_control_dialog.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_control_dialog.dart';
import 'package:syncrow_web/pages/space_tree/view/space_tree_view.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/format_date_time.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';
import 'package:syncrow_web/utils/style.dart';

class DeviceManagementBody extends StatelessWidget with HelperResponsiveLayout {
  const DeviceManagementBody({super.key, required this.devices});

  final List<AllDevicesModel> devices;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<DeviceManagementBloc, DeviceManagementState>(
      buildWhen: (previous, current) => previous != current,
      builder: (context, state) {
        List<AllDevicesModel> devicesToShow = [];
        int selectedIndex = 0;
        int onlineCount = 0;
        int offlineCount = 0;
        int lowBatteryCount = 0;
        bool isControlButtonEnabled = false;
        List<AllDevicesModel> selectedDevices = [];
        if (state is DeviceManagementLoaded) {
          devicesToShow = state.devices;
          selectedIndex = state.selectedIndex;
          onlineCount = state.onlineCount;
          offlineCount = state.offlineCount;
          lowBatteryCount = state.lowBatteryCount;
          isControlButtonEnabled = state.isControlButtonEnabled;
          selectedDevices = state.selectedDevice ?? [];
        } else if (state is DeviceManagementFiltered) {
          devicesToShow = state.filteredDevices;
          selectedIndex = state.selectedIndex;
          onlineCount = state.onlineCount;
          offlineCount = state.offlineCount;
          lowBatteryCount = state.lowBatteryCount;
          isControlButtonEnabled = state.isControlButtonEnabled;
          selectedDevices = state.selectedDevice ?? [];
        } else if (state is DeviceManagementInitial) {
          devicesToShow = [];
          selectedIndex = 0;
          isControlButtonEnabled = false;
        }
        final tabs = [
          'All',
          'Online ($onlineCount)',
          'Offline ($offlineCount)',
          'Low Battery ($lowBatteryCount)',
        ];

        final buttonLabel =
            (selectedDevices.length > 1) ? 'Batch Control' : 'Control';
        final isAnyDeviceOffline =
            selectedDevices.any((element) => !(element.online ?? false));
        return Row(
          children: [
            Expanded(child: SpaceTreeView(
              onSelect: () {
                context.read<DeviceManagementBloc>().add(ResetFilters());
                context.read<DeviceManagementBloc>().add(FetchDevices(context));
              },
            )),
            Expanded(
              flex: 4,
              child: state is DeviceManagementLoading
                  ? const Center(child: CircularProgressIndicator())
                  : Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                          padding: isLargeScreenSize(context)
                              ? const EdgeInsets.all(30)
                              : const EdgeInsets.all(15),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              FilterWidget(
                                size: MediaQuery.of(context).size,
                                tabs: tabs,
                                selectedIndex: selectedIndex,
                                onTabChanged: (index) {
                                  context
                                      .read<DeviceManagementBloc>()
                                      .add(SelectedFilterChanged(index));
                                },
                              ),
                              const SizedBox(height: 20),
                              const DeviceSearchFilters(),
                              const SizedBox(height: 12),
                              Container(
                                // height: 45,
                                width: 125,
                                decoration: containerDecoration,
                                child: Center(
                                  child: DefaultButton(
                                    backgroundColor: isAnyDeviceOffline
                                        ? ColorsManager.primaryColor
                                            .withValues(alpha: 0.1)
                                        : null,
                                    onPressed: isControlButtonEnabled
                                        ? () {
                                            if (isAnyDeviceOffline) {
                                              ScaffoldMessenger.of(context)
                                                  .clearSnackBars();
                                              ScaffoldMessenger.of(context)
                                                  .showSnackBar(
                                                const SnackBar(
                                                  content: Text(
                                                    'This Device is Offline',
                                                  ),
                                                  duration:
                                                      Duration(seconds: 2),
                                                ),
                                              );
                                              return;
                                            }

                                            if (selectedDevices.length == 1) {
                                              showDialog(
                                                context: context,
                                                builder: (context) =>
                                                    DeviceControlDialog(
                                                  device: selectedDevices.first,
                                                ),
                                              );
                                            } else if (selectedDevices.length >
                                                1) {
                                              final productTypes =
                                                  selectedDevices
                                                      .map((device) =>
                                                          device.productType)
                                                      .toSet();
                                              if (productTypes.length == 1) {
                                                showDialog(
                                                  context: context,
                                                  builder: (context) =>
                                                      DeviceBatchControlDialog(
                                                    devices: selectedDevices,
                                                  ),
                                                );
                                              }
                                            }
                                          }
                                        : null,
                                    borderRadius: 9,
                                    child: Text(
                                      buttonLabel,
                                      textAlign: TextAlign.center,
                                      style: TextStyle(
                                        fontSize: 12,
                                        color: isControlButtonEnabled
                                            ? Colors.white
                                            : Colors.grey,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: Padding(
                            padding: isLargeScreenSize(context)
                                ? const EdgeInsets.all(30)
                                : const EdgeInsets.all(15),
                            child: DynamicTable(
                              withSelectAll: true,
                              cellDecoration: containerDecoration,
                              onRowSelected: (index, isSelected, row) {
                                final selectedDevice = devicesToShow[index];
                                context
                                    .read<DeviceManagementBloc>()
                                    .add(SelectDevice(selectedDevice));
                              },
                              withCheckBox: true,
                              size: MediaQuery.of(context).size,
                              uuidIndex: 2,
                              headers: const [
                                'Device Name',
                                'Product Name',
                                'Device ID',
                                'Space Name',
                                'Location',
                                'Battery Level',
                                'Installation Date and Time',
                                'Status',
                                'Last Offline Date and Time',
                                'Settings'
                              ],
                              data: devicesToShow.map((device) {
                                final combinedSpaceNames = device.spaces != null
                                    ? device.spaces!
                                            .map((space) => space.spaceName)
                                            .join(' > ') +
                                        (device.community != null
                                            ? ' > ${device.community!.name}'
                                            : '')
                                    : (device.community != null
                                        ? device.community!.name
                                        : '');

                                return [
                                  device.name ?? '',
                                  device.productName ?? '',
                                  device.uuid ?? '',
                                  (device.spaces != null &&
                                          device.spaces!.isNotEmpty)
                                      ? device.spaces![0].spaceName
                                      : '',
                                  combinedSpaceNames,
                                  device.batteryLevel != null
                                      ? '${device.batteryLevel}%'
                                      : '-',
                                  formatDateTime(
                                      DateTime.fromMillisecondsSinceEpoch(
                                          (device.createTime ?? 0) * 1000)),
                                  device.online == true ? 'Online' : 'Offline',
                                  formatDateTime(
                                      DateTime.fromMillisecondsSinceEpoch(
                                          (device.updateTime ?? 0) * 1000)),
                                  'Settings',
                                ];
                              }).toList(),
                              onSelectionChanged: (selectedRows) {
                                context
                                    .read<DeviceManagementBloc>()
                                    .add(UpdateSelection(selectedRows));
                              },
                              initialSelectedIds: context
                                  .read<DeviceManagementBloc>()
                                  .selectedDevices
                                  .map((device) => device.uuid!)
                                  .toList(),
                              isEmpty: devicesToShow.isEmpty,
                              onSettingsPressed: (rowIndex) async {
                                final device = devicesToShow[rowIndex];
                                showDeviceSettingsSidebar(context, device);
                              },
                            ),
                          ),
                        )
                      ],
                    ),
            ),
          ],
        );
      },
    );
  }

  void showDeviceSettingsSidebar(BuildContext context, AllDevicesModel device) {
    showGeneralDialog(
      context: context,
      barrierDismissible: true,
      barrierLabel: "Device Settings",
      transitionDuration: const Duration(milliseconds: 300),
      pageBuilder: (_, anim1, anim2) {
        return Align(
          alignment: Alignment.centerRight,
          child: Material(
            child: Container(
              width: MediaQuery.of(context).size.width * 0.3,
              color: ColorsManager.whiteColors,
              child: DeviceSettingsPanel(
                device: device,
                onClose: () => Navigator.of(context).pop(),
                deviceManagementBloc: context.read<DeviceManagementBloc>(),
              ),
            ),
          ),
        );
      },
      transitionBuilder: (context, anim1, anim2, child) {
        return SlideTransition(
          position: Tween<Offset>(
            begin: const Offset(1, 0),
            end: Offset.zero,
          ).animate(anim1),
          child: child,
        );
      },
    );
  }
}
