import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart';

class RoutineDevices extends StatefulWidget {
  const RoutineDevices({super.key});

  @override
  State<RoutineDevices> createState() => _RoutineDevicesState();
}

class _RoutineDevicesState extends State<RoutineDevices> {
  @override
  void initState() {
    super.initState();
    context.read<RoutineBloc>().add(FetchDevicesInRoutine());
  }

  static const _allowedProductTypes = {
    'AC',
    '1G',
    '2G',
    '3G',
    'WPS',
    'GW',
    'CPS',
    'NCPS',
    'WH',
    'PC',
    'CUR',
  };

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        if (state.isLoading) {
          return const Center(child: CircularProgressIndicator());
        }

        Future.delayed(const Duration(seconds: 1), () {
          if (state.devices.isEmpty) {
            return const Center(child: Text('No devices found'));
          }
        });

        final deviceList = state.devices
            .where(
                (device) => _allowedProductTypes.contains(device.productType))
            .toList();

        return Wrap(
          spacing: 10,
          runSpacing: 10,
          children: deviceList.asMap().entries.map((entry) {
            final device = entry.value;

            final deviceData = {
              'device': device,
              'imagePath': device.getDefaultIcon(device.productType),
              'title': device.name ?? '',
              'deviceId': device.uuid,
              'productType': device.productType,
              'functions': device.functions,
              'uniqueCustomId': '',
              'tag': device.deviceTags!.isNotEmpty
                  ? device.deviceTags![0].name
                  : '',
              'subSpace': device.deviceSubSpace?.subspaceName ?? '',
            };

            if (state.searchText != null && state.searchText!.isNotEmpty) {
              return device.name!
                      .toLowerCase()
                      .contains(state.searchText!.toLowerCase())
                  ? DraggableCard(
                      imagePath: deviceData['imagePath'] as String,
                      title: deviceData['title'] as String,
                      deviceData: deviceData,
                    )
                  : const SizedBox.shrink();
            } else {
              return DraggableCard(
                imagePath: deviceData['imagePath'] as String,
                title: deviceData['title'] as String,
                deviceData: deviceData,
              );
            }
          }).toList(),
        );
      },
    );
  }
}
