import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/utils/extension/build_context_x.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_managment_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/shared/device_control_dialog.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/widgets/device_search_filters.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>(
      builder: (context, state) {
        List<AllDevicesModel> devicesToShow = [];
        int selectedIndex = 0;
        int onlineCount = 0;
        int offlineCount = 0;
        int lowBatteryCount = 0;
        bool isControlButtonEnabled = false;

        if (state is DeviceManagementLoaded) {
          devicesToShow = state.devices;
          selectedIndex = state.selectedIndex;
          onlineCount = state.onlineCount;
          offlineCount = state.offlineCount;
          lowBatteryCount = state.lowBatteryCount;
          isControlButtonEnabled = state.selectedDevice != null;
        } else if (state is DeviceManagementFiltered) {
          devicesToShow = state.filteredDevices;
          selectedIndex = state.selectedIndex;
          onlineCount = state.onlineCount;
          offlineCount = state.offlineCount;
          lowBatteryCount = state.lowBatteryCount;
          isControlButtonEnabled = state.selectedDevice != null;
        } else if (state is DeviceManagementInitial) {
          devicesToShow = [];
          selectedIndex = 0;
          isControlButtonEnabled = false;
        }

        final tabs = [
          'All',
          'Online ($onlineCount)',
          'Offline ($offlineCount)',
          'Low Battery ($lowBatteryCount)',
        ];

        return Column(
           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: 100,
                    decoration: containerDecoration,
                    child: Center(
                      child: DefaultButton(
                        onPressed: isControlButtonEnabled
                            ? () {
                                final selectedDevice = context
                                    .read<DeviceManagementBloc>()
                                    .selectedDevices.first;
                                showDialog(
                                  context: context,
                                  builder: (context) => DeviceControlDialog(
                                      device: selectedDevice),
                                );
                              }
                            : null,
                        borderRadius: 9,
                        child: Text(
                          'Control',
                          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: context.screenSize,
                  uuidIndex: 2,
                  headers: const [
                    'Device Name',
                    'Product Name',
                    'Device ID',
                    'Unit Name',
                    'Room',
                    'Battery Level',
                    'Installation Date and Time',
                    'Status',
                    'Last Offline Date and Time',
                  ],
                  data: devicesToShow.map((device) {
                    return [
                      device.categoryName ?? '',
                      device.name ?? '',
                      device.uuid ?? '',
                      device.unit?.name ?? '',
                      device.room?.name ?? '',
                      device.batteryLevel != null
                          ? '${device.batteryLevel}%'
                          : '-',
                      formatDateTime(DateTime.fromMillisecondsSinceEpoch(
                          (device.createTime ?? 0) * 1000)),
                      device.online == true ? 'Online' : 'Offline',
                      formatDateTime(DateTime.fromMillisecondsSinceEpoch(
                          (device.updateTime ?? 0) * 1000)),
                    ];
                  }).toList(),
                  initialSelectedIds: context
                      .read<DeviceManagementBloc>()
                      .selectedDevices
                      .map((device) => device.uuid!)
                      .toList(),
                  isEmpty: devicesToShow.isEmpty,
                ),
              ),
            )
          ],
        );
      },
    );
  }
}
