import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/three_gang_switch/bloc/living_room_bloc.dart';
import 'package:syncrow_web/pages/device_managment/three_gang_switch/models/living_room_model.dart';
import 'package:syncrow_web/pages/device_managment/three_gang_switch/widgets/living_toggle_widget.dart';
import 'package:syncrow_web/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

class LivingRoomDeviceControl extends StatelessWidget with HelperResponsiveLayout {
  final String deviceId;

  const LivingRoomDeviceControl({super.key, required this.deviceId});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) =>
          LivingRoomBloc(deviceId: deviceId)..add(LivingRoomFetchDeviceStatus(deviceId)),
      child: BlocBuilder<LivingRoomBloc, LivingRoomState>(
        builder: (context, state) {
          if (state is LivingRoomDeviceStatusLoading) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is LivingRoomDeviceStatusLoaded) {
            return _buildStatusControls(context, state.status);
          } else if (state is LivingRoomDeviceManagementError || state is LivingRoomControlError) {
            return const Center(child: Text('Error fetching status'));
          } else {
            return const Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }

  Widget _buildStatusControls(BuildContext context, LivingRoomStatusModel status) {
    final isExtraLarge = isExtraLargeScreenSize(context);
    final isLarge = isLargeScreenSize(context);
    final isMedium = isMediumScreenSize(context);
    return Container(
      child: 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: [
          ToggleWidget(
            value: status.switch1,
            code: 'switch_1',
            deviceId: deviceId,
            label: 'Wall Light',
          ),
          ToggleWidget(
            value: status.switch2,
            code: 'switch_2',
            deviceId: deviceId,
            label: 'Ceiling Light',
          ),
          ToggleWidget(
            value: status.switch3,
            code: 'switch_3',
            deviceId: deviceId,
            label: 'Spotlight',
          ),
        ],
      ),
    );
  }
}
