// lib/pages/routiens/widgets/then_container.dart

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/helper/dialog_helper/device_dialog_helper.dart';
import 'package:syncrow_web/pages/routines/widgets/dragable_card.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/automation_dialog.dart';
import 'package:syncrow_web/pages/routines/widgets/routine_dialogs/delay_dialog.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:uuid/uuid.dart';

class ThenContainer extends StatelessWidget {
  const ThenContainer({super.key});

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        return DragTarget<Map<String, dynamic>>(
          builder: (context, candidateData, rejectedData) {
            return SingleChildScrollView(
              child: Container(
                padding: const EdgeInsets.all(16),
                width: double.infinity,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text('THEN',
                        style: TextStyle(
                            fontSize: 18, fontWeight: FontWeight.bold)),
                    const SizedBox(height: 16),
                    if (state.isLoading && state.isUpdate == true)
                      const Center(
                        child: CircularProgressIndicator(),
                      )
                    else
                      Wrap(
                          spacing: 8,
                          runSpacing: 8,
                          children: List.generate(
                              state.thenItems.length,
                              (index) => GestureDetector(
                                    onTap: () async {
                                      if (state.thenItems[index]['deviceId'] ==
                                          'delay') {
                                        final result = await DelayHelper
                                            .showDelayPickerDialog(context,
                                                state.thenItems[index]);

                                        if (result != null) {
                                          context
                                              .read<RoutineBloc>()
                                              .add(AddToThenContainer({
                                                ...state.thenItems[index],
                                                'imagePath': Assets.delay,
                                                'title': 'Delay',
                                              }));
                                        }
                                        return;
                                      }

                                      if (state.thenItems[index]['type'] ==
                                          'automation') {
                                        final result = await showDialog<bool>(
                                          context: context,
                                          builder: (BuildContext context) =>
                                              AutomationDialog(
                                            automationName:
                                                state.thenItems[index]['name']
                                                        as String? ??
                                                    'Automation',
                                            automationId: state.thenItems[index]
                                                    ['deviceId'] as String? ??
                                                '',
                                            uniqueCustomId: state
                                                    .thenItems[index]
                                                ['uniqueCustomId'] as String,
                                          ),
                                        );

                                        if (result != null) {
                                          context
                                              .read<RoutineBloc>()
                                              .add(AddToThenContainer({
                                                ...state.thenItems[index],
                                                'imagePath': Assets.automation,
                                                'title': state.thenItems[index]
                                                        ['name'] ??
                                                    state.thenItems[index]
                                                        ['title'],
                                              }));
                                        }
                                        return;
                                      }

                                      final result = await DeviceDialogHelper
                                          .showDeviceDialog(
                                              context: context,
                                              data: state.thenItems[index],
                                              removeComparetors: true,
                                              dialogType: 'THEN');
                                      if (result != null) {
                                        context.read<RoutineBloc>().add(
                                            AddToThenContainer(
                                                state.thenItems[index]));
                                      } else if (![
                                        'AC',
                                        '1G',
                                        '2G',
                                        '3G',
                                        'WPS',
                                        'CPS',
                                        'GW',
                                        'NCPS',
                                        'WH',
                                        'CUR',
                                      ].contains(state.thenItems[index]
                                          ['productType'])) {
                                        context.read<RoutineBloc>().add(
                                            AddToThenContainer(
                                                state.thenItems[index]));
                                      }
                                    },
                                    child: DraggableCard(
                                      imagePath: state.thenItems[index]
                                              ['imagePath'] as String? ??
                                          '',
                                      title: state.thenItems[index]['title']
                                              as String? ??
                                          '',
                                      deviceData: state.thenItems[index],
                                      padding: const EdgeInsets.symmetric(
                                          horizontal: 4, vertical: 8),
                                      isFromThen: true,
                                      isFromIf: false,
                                      onRemove: () {
                                        context.read<RoutineBloc>().add(
                                            RemoveDragCard(
                                                index: index,
                                                isFromThen: true,
                                                key: state.thenItems[index]
                                                        ['uniqueCustomId']
                                                    as String));
                                      },
                                    ),
                                  ))),
                  ],
                ),
              ),
            );
          },
          onAcceptWithDetails: (data) async {
            final uniqueCustomId = const Uuid().v4();
            final mutableData = Map<String, dynamic>.from(data.data);
            mutableData['uniqueCustomId'] = uniqueCustomId;

            if (mutableData['type'] == 'scene') {
              context.read<RoutineBloc>().add(AddToThenContainer(mutableData));
              return;
            }

            if (state.automationId == mutableData['deviceId'] ||
                state.sceneId == mutableData['deviceId']) {
              return;
            }

            if (mutableData['type'] == 'automation') {
              int index = state.thenItems.indexWhere(
                  (item) => item['deviceId'] == mutableData['deviceId']);
              if (index != -1) {
                return;
              }

              final result = await showDialog<bool>(
                context: context,
                builder: (BuildContext context) => AutomationDialog(
                  automationName: mutableData['name'] ?? 'Automation',
                  automationId: mutableData['deviceId'] ?? '',
                  uniqueCustomId: uniqueCustomId,
                ),
              );

              if (result != null) {
                context.read<RoutineBloc>().add(AddToThenContainer({
                      ...mutableData,
                      'imagePath': Assets.automation,
                      'title': mutableData['name'],
                    }));
              }
              return;
            }

            if (mutableData['type'] == 'tap_to_run' && state.isAutomation) {
              int index = state.thenItems.indexWhere(
                  (item) => item['deviceId'] == mutableData['deviceId']);
              if (index != -1) {
                return;
              }
              context.read<RoutineBloc>().add(AddToThenContainer({
                    ...mutableData,
                    'imagePath': mutableData['imagePath'] ?? Assets.logo,
                    'title': mutableData['name'],
                  }));

              return;
            }

            if (mutableData['type'] == 'tap_to_run' && !state.isAutomation) {
              return;
            }

            if (mutableData['deviceId'] == 'delay') {
              final result =
                  await DelayHelper.showDelayPickerDialog(context, mutableData);

              if (result != null) {
                context.read<RoutineBloc>().add(AddToThenContainer({
                      ...mutableData,
                      'imagePath': Assets.delay,
                      'title': 'Delay',
                    }));
              }
              return;
            }

            final result = await DeviceDialogHelper.showDeviceDialog(
                context: context,
                data: mutableData,
                removeComparetors: true,
                dialogType: 'THEN');
            if (result != null) {
              context.read<RoutineBloc>().add(AddToThenContainer(mutableData));
            } else if (![
              'AC',
              '1G',
              '2G',
              '3G',
              'WPS',
              'GW',
              'CPS',
              'NCPS',
              'WH',
              'PC',
              'CUR',
            ].contains(mutableData['productType'])) {
              context.read<RoutineBloc>().add(AddToThenContainer(mutableData));
            }
          },
        );
      },
    );
  }
}
