import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_bloc.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_event.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/bloc/garage_door_state.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/helper/garage_door_helper.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/models/garage_door_model.dart';
import 'package:syncrow_web/pages/device_managment/garage_door/schedule_view/schedule_garage_view.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/pages/device_managment/shared/toggle_widget.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/utils/helpers/responsice_layout_helper/responsive_layout_helper.dart';

class GarageDoorControlView extends StatelessWidget
    with HelperResponsiveLayout {
  final String deviceId;

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

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => GarageDoorBloc(deviceId: deviceId)
        ..add(GarageDoorInitialEvent(deviceId)),
      child: BlocBuilder<GarageDoorBloc, GarageDoorState>(
        builder: (context, state) {
          if (state is GarageDoorLoadingState) {
            return const Center(child: CircularProgressIndicator());
          } else if (state is GarageDoorReportsState) {
            return ReportsTable(
              report: state.deviceReport,
              hideValueShowDescription: true,
              garageDoorSensor: true,
              onRowTap: (index) {},
              onClose: () {
                context
                    .read<GarageDoorBloc>()
                    .add(BackToGarageDoorGridViewEvent());
              },
            );
          } else if (state is GarageDoorLoadedState) {
            return _buildControlView(context, state.status);
          } else if (state is GarageDoorErrorState) {
            return Center(child: Text('Error: ${state.message}'));
          }
          return const Center(child: Text('Unknown state'));
        },
      ),
    );
  }

  Widget _buildControlView(BuildContext context, GarageDoorStatusModel status) {
    final isExtraLarge = isExtraLargeScreenSize(context);
    final isLarge = isLargeScreenSize(context);
    final isMedium = isMediumScreenSize(context);

    return GridView(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: const EdgeInsets.symmetric(horizontal: 50),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: isLarge || isExtraLarge
            ? 3
            : isMedium
                ? 2
                : 1,
        childAspectRatio: 1.5,
        mainAxisExtent: 140,
        crossAxisSpacing: 12,
        mainAxisSpacing: 12,
      ),
      children: [
        IconNameStatusContainer(
          isFullIcon: false,
          name: status.doorContactState ? 'Opened' : 'Closed',
          icon: status.doorContactState ? Assets.openedDoor : Assets.closedDoor,
          onTap: () {
            context.read<GarageDoorBloc>().add(
                  GarageDoorControlEvent(
                      deviceId: status.uuid,
                      value: !status.switch1,
                      code: 'doorcontact_state'),
                );
          },
          status: status.switch1,
          textColor: ColorsManager.blackColor,
        ),
        IconNameStatusContainer(
          onTap: () {
            context.read<GarageDoorBloc>().add(
                  FetchGarageDoorSchedulesEvent(
                      deviceId: deviceId, category: 'doorcontact_state'),
                );
            showDialog(
                context: context,
                builder: (ctx) => BlocProvider.value(
                      value: BlocProvider.of<GarageDoorBloc>(context),
                      child: BuildGarageDoorScheduleView(status: status),
                    ));
          },
          name: 'Scheduling',
          icon: Assets.acSchedule,
          status: false,
          textColor: ColorsManager.blackColor,
          isFullIcon: false,
        ),
        ToggleWidget(
          label: '',
          labelWidget: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              IconButton(
                onPressed: () {
                  context
                      .read<GarageDoorBloc>()
                      .add(DecreaseGarageDoorDelayEvent(deviceId: status.uuid));
                },
                icon: const Icon(
                  Icons.remove,
                  size: 28,
                  color: ColorsManager.greyColor,
                ),
                padding: EdgeInsets.zero,
              ),
              Text(
                status.delay.inHours.toString().padLeft(2, '0'),
                style: context.textTheme.titleLarge!.copyWith(
                  color: ColorsManager.dialogBlueTitle,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                'h',
                style: context.textTheme.bodySmall!
                    .copyWith(color: ColorsManager.blackColor),
              ),
              Text(
                (status.delay.inMinutes % 60).toString().padLeft(2, '0'),
                style: context.textTheme.titleLarge!.copyWith(
                  color: ColorsManager.dialogBlueTitle,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Text(
                'm',
                style: context.textTheme.bodySmall!
                    .copyWith(color: ColorsManager.blackColor),
              ),
              IconButton(
                onPressed: () {
                  context
                      .read<GarageDoorBloc>()
                      .add(IncreaseGarageDoorDelayEvent(deviceId: status.uuid));
                },
                icon: const Icon(
                  Icons.add,
                  size: 28,
                  color: ColorsManager.greyColor,
                ),
                padding: EdgeInsets.zero,
              ),
            ],
          ),
          value: status.countdown1 != 0 ? true : false,
          code: 'countdown_1',
          deviceId: status.uuid,
          icon: Assets.doorDelay,
          onChange: (value) {
            context.read<GarageDoorBloc>().add(
                  GarageDoorControlEvent(
                      deviceId: status.uuid,
                      value: value ? status.delay.inSeconds : 0,
                      code: 'countdown_1'),
                );
          },
        ),
        IconNameStatusContainer(
          isFullIcon: false,
          name: 'Records',
          icon: Assets.records,
          onTap: () {
            context.read<GarageDoorBloc>().add(FetchGarageDoorRecordsEvent(
                code: 'doorcontact_state', deviceId: status.uuid));
          },
          status: false,
          textColor: ColorsManager.blackColor,
        ),
        IconNameStatusContainer(
          isFullIcon: false,
          name: 'Preferences',
          icon: Assets.preferences,
          onTap: () {
            GarageDoorDialogHelper.showPreferencesDialog(context);
          },
          status: false,
          textColor: ColorsManager.blackColor,
        ),
      ],
    );
  }
}
