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/door_lock/bloc/door_lock_bloc.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/bloc/door_lock_event.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/bloc/door_lock_state.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/models/door_lock_status_model.dart';
import 'package:syncrow_web/pages/device_managment/door_lock/widget/door_button.dart';

class DoorLockControlsView extends StatelessWidget {
  final AllDevicesModel device;

  const DoorLockControlsView({super.key, required this.device});

  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => DoorLockBloc(deviceId: device.uuid!)
        ..add(DoorLockFetchStatus(device.uuid!)),
      child: BlocListener<DoorLockBloc, DoorLockState>(
        listener: (context, state) {
          if (state is DoorLockControlError) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text(state.message)),
            );
          }
        },
        child: BlocBuilder<DoorLockBloc, DoorLockState>(
          builder: (context, state) {
            if (state is DoorLockStatusLoading) {
              return const Center(child: CircularProgressIndicator());
            } else if (state is DoorLockStatusLoaded) {
              return _buildStatusControls(context, state.status);
            } else if (state is UpdateState) {
              return _buildStatusControls(context, state.smartDoorModel);
            } else if (state is DoorLockControlError) {
              return const SizedBox();
            } else {
              return const Center(child: Text('Error fetching status'));
            }
          },
        ),
      ),
    );
  }

  Widget _buildStatusControls(
      BuildContext context, DoorLockStatusModel status) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 40),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            DoorLockButton(
              smartDoorModel: status,
              doorLock: device,
            ),
          ],
        ),
      ),
    );
  }
}
