import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/all_devices/models/devices_model.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_bloc.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_event.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/bloc/main_door_sensor_state.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/models/main_door_status_model.dart';
import 'package:syncrow_web/pages/device_managment/main_door_sensor/widgets/notification_dialog.dart';
import 'package:syncrow_web/pages/device_managment/shared/icon_name_status_container.dart';
import 'package:syncrow_web/pages/device_managment/shared/table/report_table.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

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

  final AllDevicesModel device;

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
        create: (context) => MainDoorSensorBloc()..add(MainDoorSensorFetchDeviceEvent(device.uuid!)),
        child: BlocBuilder<MainDoorSensorBloc, MainDoorSensorState>(
          builder: (context, state) {
            if (state is MainDoorSensorLoadingState || state is MainDoorSensorReportsLoadingState) {
              return const Center(child: CircularProgressIndicator());
            } else if (state is MainDoorSensorDeviceStatusLoaded) {
              return _buildStatusControls(context, state.status);
            } else if (state is MainDoorSensorReportLoaded) {
              return ReportsTable(
                report: state.deviceReport,
                onRowTap: (index) {},
                onClose: () {
                  context.read<MainDoorSensorBloc>().add(MainDoorSensorFetchDeviceEvent(device.uuid!));
                },
                hideValueShowDescription: true,
                mainDoorSensor: true,
              );
            } else if (state is MainDoorSensorFailedState || state is MainDoorSensorBatchFailedState) {
              return const Center(child: Text('Error fetching status'));
            } else {
              return const Center(child: CircularProgressIndicator());
            }
          },
        ));
  }

  Widget _buildStatusControls(BuildContext context, MainDoorSensorStatusModel status) {
    final isExtraLarge = isExtraLargeScreenSize(context);
    final isLarge = isLargeScreenSize(context);
    final isMedium = isMediumScreenSize(context);
    return GridView(
      padding: const EdgeInsets.symmetric(horizontal: 50),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: isLarge || isExtraLarge
            ? 3
            : isMedium
                ? 2
                : 1,
        mainAxisExtent: 140,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
      ),
      children: [
        IconNameStatusContainer(
          isFullIcon: true,
          name: status.doorContactState ? 'Open' : 'Close',
          icon: Assets.openCloseDoor,
          onTap: () {},
          status: status.doorContactState,
          textColor: status.doorContactState ? ColorsManager.red : ColorsManager.blackColor,
          paddingAmount: 8,
        ),
        IconNameStatusContainer(
          isFullIcon: true,
          name: 'Open/Close\nRecord',
          icon: Assets.openCloseRecords,
          onTap: () {
            final from = DateTime.now().subtract(const Duration(days: 30)).millisecondsSinceEpoch;
            final to = DateTime.now().millisecondsSinceEpoch;
            context.read<MainDoorSensorBloc>().add(
                  MainDoorSensorReportsEvent(
                    deviceId: device.uuid!,
                    code: 'doorcontact_state',
                    from: from.toString(),
                    to: to.toString(),
                  ),
                );
          },
          status: false,
          textColor: ColorsManager.blackColor,
        ),
        IconNameStatusContainer(
          isFullIcon: false,
          name: 'Notifications\nSettings',
          icon: Assets.mainDoorNotifi,
          onTap: () {
            showDialog(
              context: context,
              builder: (context) => const NotificationDialog(),
            );
          },
          status: false,
          textColor: ColorsManager.blackColor,
          paddingAmount: 14,
        ),
      ],
    );
  }
}
