import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:syncrow_web/pages/routines/bloc/routine_bloc/routine_bloc.dart';
import 'package:syncrow_web/pages/routines/models/device_functions.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';

class DraggableCard extends StatelessWidget {
  final String imagePath;
  final String title;
  final Map<String, dynamic> deviceData;
  final EdgeInsetsGeometry? padding;
  final void Function()? onRemove;
  final bool? isFromThen;
  final bool? isFromIf;

  const DraggableCard({
    super.key,
    required this.imagePath,
    required this.title,
    required this.deviceData,
    this.padding,
    this.onRemove,
    this.isFromThen,
    this.isFromIf,
  });

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<RoutineBloc, RoutineState>(
      builder: (context, state) {
        final deviceFunctions = state.selectedFunctions[deviceData['uniqueCustomId']] ?? [];

        int index = state.thenItems
            .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']);

        if (index != -1) {
          return _buildCardContent(context, deviceFunctions, padding: padding);
        }

        int ifIndex = state.ifItems
            .indexWhere((item) => item['uniqueCustomId'] == deviceData['uniqueCustomId']);

        if (ifIndex != -1) {
          return _buildCardContent(context, deviceFunctions, padding: padding);
        }

        return Draggable<Map<String, dynamic>>(
          data: deviceData,
          feedback: Transform.rotate(
            angle: -0.1,
            child: _buildCardContent(context, deviceFunctions, padding: padding),
          ),
          childWhenDragging: _buildGreyContainer(),
          child: _buildCardContent(context, deviceFunctions, padding: padding),
        );
      },
    );
  }

  Widget _buildCardContent(BuildContext context, List<DeviceFunctionData> deviceFunctions,
      {EdgeInsetsGeometry? padding}) {
    return Stack(
      children: [
        Card(
          color: ColorsManager.whiteColors,
          child: Container(
            padding: const EdgeInsets.all(16),
            width: 110,
            height: deviceFunctions.isEmpty ? 160 : 180,
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container(
                      height: 50,
                      width: 50,
                      decoration: BoxDecoration(
                        color: ColorsManager.circleImageBackground,
                        borderRadius: BorderRadius.circular(90),
                        border: Border.all(
                          color: ColorsManager.graysColor,
                        ),
                      ),
                      padding: const EdgeInsets.all(8),
                      child: deviceData['type'] == 'tap_to_run' || deviceData['type'] == 'scene'
                          ? Image.memory(
                              base64Decode(deviceData['icon']),
                            )
                          : SvgPicture.asset(
                              imagePath,
                            ),
                    ),
                    const SizedBox(height: 8),
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 3),
                      child: Text(
                        deviceData['title'] ?? deviceData['name'] ?? title,
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis,
                        maxLines: 2,
                        style: context.textTheme.bodySmall?.copyWith(
                          color: ColorsManager.blackColor,
                          fontSize: 12,
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 4,
                    ),
                    Visibility(
                      visible: deviceData['tag'] != null && deviceData['tag'] != '',
                      child: Row(
                        spacing: 2,
                        children: [
                          SizedBox(
                              width: 8, height: 8, child: SvgPicture.asset(Assets.deviceTagIcon)),
                          Flexible(
                            child: Text(
                              deviceData['tag'] ?? '',
                              textAlign: TextAlign.center,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: context.textTheme.bodySmall?.copyWith(
                                color: ColorsManager.lightGreyColor,
                                fontSize: 9,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Visibility(
                      visible: deviceData['subSpace'] != null && deviceData['subSpace'] != '',
                      child: const SizedBox(
                        height: 4,
                      ),
                    ),
                    Visibility(
                      visible: deviceData['subSpace'] != null && deviceData['subSpace'] != '',
                      child: Row(
                        spacing: 2,
                        children: [
                          SizedBox(
                              width: 8,
                              height: 8,
                              child: SvgPicture.asset(Assets.spaceLocationIcon)),
                          Flexible(
                            child: Text(
                              deviceData['subSpace'] ?? '',
                              textAlign: TextAlign.center,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: context.textTheme.bodySmall?.copyWith(
                                color: ColorsManager.lightGreyColor,
                                fontSize: 9,
                                fontWeight: FontWeight.w400,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                if (deviceFunctions.isNotEmpty)
                  const SizedBox(
                    height: 4,
                  ),
                if (deviceFunctions.isNotEmpty)
                  ...deviceFunctions.map((function) => Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Expanded(
                            child: Text(
                              '${function.operationName}: ${_formatFunctionValue(function)}',
                              style: context.textTheme.bodySmall?.copyWith(
                                fontSize: 9,
                                color: ColorsManager.lightGreyColor,
                                height: 1.2,
                              ),
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      )),
              ],
            ),
          ),
        ),
        Positioned(
          top: -4,
          right: -6,
          child: Visibility(
            visible: (isFromIf ?? false) || (isFromThen ?? false),
            child: IconButton(
              onPressed: onRemove == null
                  ? null
                  : () {
                      onRemove!();
                    },
              icon: const Icon(
                Icons.close,
                color: ColorsManager.boxColor,
              ),
            ),
          ),
        ),
      ],
    );
  }

  String _formatFunctionValue(DeviceFunctionData function) {
    if (function.functionCode == 'temp_set' || function.functionCode == 'temp_current') {
      return '${(function.value / 10).toStringAsFixed(0)}°C';
    } else if (function.functionCode.contains('countdown')) {
      final seconds = function.value?.toInt() ?? 0;
      if (seconds >= 3600) {
        final hours = (seconds / 3600).floor();
        final remainingMinutes = ((seconds % 3600) / 60).floor();
        final remainingSeconds = seconds % 60;
        return '$hours h ${remainingMinutes}m ${remainingSeconds}s';
      } else if (seconds >= 60) {
        final minutes = (seconds / 60).floor();
        final remainingSeconds = seconds % 60;
        return '$minutes m ${remainingSeconds}s';
      }
      return '${seconds}s';
    }
    return function.value.toString();
  }

  Widget _buildGreyContainer() {
    return Container(
      height: 123,
      width: 90,
      decoration: BoxDecoration(
        color: Colors.grey[100],
        borderRadius: BorderRadius.circular(20),
      ),
    );
  }
}
