import 'package:farm_tpf/data/repository/repository.dart';
import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
import 'package:farm_tpf/presentation/custom_widgets/widget_search.dart';
import 'package:farm_tpf/presentation/screens/control_device/widget_device_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'bloc/device_bloc.dart';

class ControlDeviceScreen extends StatefulWidget {
  @override
  _ControlDeviceScreenState createState() => _ControlDeviceScreenState();
}

class _ControlDeviceScreenState extends State<ControlDeviceScreen> {
  late BuildContext _blocContext;
  DeviceBloc _deviceBloc = DeviceBloc(repository: Repository());
  @override
  void initState() {
    super.initState();
    _deviceBloc.add(OpenScreen());
  }

  @override
  Widget build(BuildContext context) {
    _blocContext = context;
    return Scaffold(
        backgroundColor: Colors.white,
        body: BlocProvider<DeviceBloc>(create: (context) => DeviceBloc(repository: Repository())..add(OpenScreen()), child: _buildContent()));
  }

  Widget _buildContent() {
    return SafeArea(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const SizedBox(
            height: 8,
          ),
          const Padding(
            padding: EdgeInsets.all(8.0),
            child: Text(
              'Thiết bị',
              style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
            ),
          ),
          const Padding(
            padding: EdgeInsets.all(8.0),
            child: Text('Điều khiển thiết bị từ xa', style: TextStyle(fontSize: 15, fontWeight: FontWeight.w200, color: Colors.black54)),
          ),
          SearchWidget(searchPressed: (value) {
            FocusScope.of(context).requestFocus(FocusNode());
            _deviceBloc.add(OnSearch(query: value));
          }),
          Expanded(
              child: BlocBuilder<DeviceBloc, DeviceState>(
            bloc: _deviceBloc,
            builder: (context, state) {
              if (state is DisplayDevice) {
                if (state.loading) {
                  return Container(
                    child: const Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                }

                if (state.devices != null) {
                  return Container(
                    child: WidgetDeviceList(
                      devices: state.devices,
                      deviceBloc: _deviceBloc,
                    ),
                  );
                }
                return Container();
              } else {
                return Container();
              }
            },
          ))
        ],
      ),
    );
  }
}
