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/utils/color_manager.dart';
import 'package:syncrow_web/utils/constants/assets.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';
import 'package:uuid/uuid.dart';

class IfContainer extends StatelessWidget {
  const IfContainer({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(
                width: double.infinity,
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text('IF',
                            style: TextStyle(
                                fontSize: 18, fontWeight: FontWeight.bold)),
                        if (state.isAutomation && state.ifItems.isNotEmpty)
                          AutomationOperatorSelector(
                              selectedOperator:
                                  state.selectedAutomationOperator),
                      ],
                    ),
                    const SizedBox(height: 16),
                    if (state.isTabToRun)
                      const Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          DraggableCard(
                            imagePath: Assets.tabToRun,
                            title: 'Tap to run',
                            deviceData: {},
                          ),
                        ],
                      ),
                    if (!state.isTabToRun)
                      Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children: List.generate(
                            state.ifItems.length,
                            (index) => GestureDetector(
                                  onTap: () async {
                                    if (!state.isTabToRun) {
                                      final result = await DeviceDialogHelper
                                          .showDeviceDialog(
                                              context: context,
                                              data: state.ifItems[index],
                                              removeComparetors: false,
                                              dialogType: "IF");

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

            if (state.isAutomation && mutableData['deviceId'] == 'tab_to_run') {
              return;
            }

            if (!state.isTabToRun) {
              if (mutableData['deviceId'] == 'tab_to_run') {
                context
                    .read<RoutineBloc>()
                    .add(AddToIfContainer(mutableData, true));
              } else {
                final result = await DeviceDialogHelper.showDeviceDialog(
                    dialogType: 'IF',
                    context: context,
                    data: mutableData,
                    removeComparetors: false);

                if (result != null) {
                  context
                      .read<RoutineBloc>()
                      .add(AddToIfContainer(mutableData, false));
                } else if (![
                  'AC',
                  '1G',
                  '2G',
                  '3G',
                  'WPS',
                  'GW',
                  'CPS',
                  'NCPS',
                  'WH',
                  'PC',
                  'CUR',
                ].contains(mutableData['productType'])) {
                  context
                      .read<RoutineBloc>()
                      .add(AddToIfContainer(mutableData, false));
                }
              }
            }
          },
        );
      },
    );
  }
}

class AutomationOperatorSelector extends StatelessWidget {
  const AutomationOperatorSelector({
    super.key,
    required this.selectedOperator,
  });

  final String selectedOperator;

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(color: ColorsManager.dividerColor),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          TextButton(
            style: TextButton.styleFrom(
              backgroundColor: selectedOperator.toLowerCase() == 'or'
                  ? ColorsManager.dialogBlueTitle
                  : ColorsManager.whiteColors,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(0),
              ),
            ),
            child: Text(
              'Any condition is met',
              style: context.textTheme.bodyMedium?.copyWith(
                color: selectedOperator.toLowerCase() == 'or'
                    ? ColorsManager.whiteColors
                    : ColorsManager.blackColor,
              ),
            ),
            onPressed: () {
              context
                  .read<RoutineBloc>()
                  .add(const ChangeAutomationOperator(operator: 'or'));
            },
          ),
          Container(
            width: 3,
            height: 24,
            color: ColorsManager.dividerColor,
          ),
          TextButton(
            style: TextButton.styleFrom(
              backgroundColor: selectedOperator.toLowerCase() == 'and'
                  ? ColorsManager.dialogBlueTitle
                  : ColorsManager.whiteColors,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(0),
              ),
            ),
            child: Text(
              'All condition is met',
              style: context.textTheme.bodyMedium?.copyWith(
                color: selectedOperator.toLowerCase() == 'and'
                    ? ColorsManager.whiteColors
                    : ColorsManager.blackColor,
              ),
            ),
            onPressed: () {
              context
                  .read<RoutineBloc>()
                  .add(const ChangeAutomationOperator(operator: 'and'));
            },
          ),
        ],
      ),
    );
  }
}
