import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:syncrow_web/pages/analytics/models/analytics_device.dart';
import 'package:syncrow_web/pages/analytics/modules/analytics/blocs/analytics_devices/analytics_devices_bloc.dart';
import 'package:syncrow_web/utils/color_manager.dart';
import 'package:syncrow_web/utils/extension/build_context_x.dart';

class AnalyticsDeviceDropdown extends StatelessWidget {
  const AnalyticsDeviceDropdown({
    required this.onChanged,
    this.showSpaceUuid = false,
    super.key,
  });

  final ValueChanged<AnalyticsDevice> onChanged;
  final bool showSpaceUuid;

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<AnalyticsDevicesBloc, AnalyticsDevicesState>(
      builder: (context, state) {
        return Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(16),
            border: Border.all(
              color: ColorsManager.greyColor,
              width: 1,
            ),
          ),
          child: Visibility(
            visible: state.status != AnalyticsDevicesStatus.loading,
            replacement: _buildLoadingIndicator(),
            child: Visibility(
              visible: state.devices.isNotEmpty,
              replacement: _buildNoDevicesFound(context),
              child: _buildDevicesDropdown(context, state),
            ),
          ),
        );
      },
    );
  }

  Widget _buildLoadingIndicator() {
    return const Center(
      child: SizedBox(
        width: 24,
        height: 24,
        child: CircularProgressIndicator(strokeWidth: 3),
      ),
    );
  }

  static const _defaultPadding = EdgeInsetsDirectional.symmetric(
    horizontal: 20,
    vertical: 2,
  );

  Widget _buildNoDevicesFound(BuildContext context) {
    return Padding(
      padding: _defaultPadding,
      child: Text(
        'no devices found',
        style: _getTextStyle(context),
      ),
    );
  }

  Widget _buildDevicesDropdown(BuildContext context, AnalyticsDevicesState state) {
    final spaceUuid = state.selectedDevice?.spaceUuid;
    return DropdownButton<AnalyticsDevice?>(
      value: state.selectedDevice,
      isDense: true,
      borderRadius: BorderRadius.circular(16),
      dropdownColor: ColorsManager.whiteColors,
      underline: const SizedBox.shrink(),
      icon: const RotatedBox(
        quarterTurns: 1,
        child: Icon(Icons.chevron_right, size: 16),
      ),
      style: _getTextStyle(context),
      padding: _defaultPadding,
      selectedItemBuilder: (context) {
        return state.devices.map((e) => Text(e.name)).toList();
      },
      items: state.devices.map((e) {
        return DropdownMenuItem(
          value: e,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(e.name),
              if (showSpaceUuid)
                if (spaceUuid != null)
                  FittedBox(
                    fit: BoxFit.scaleDown,
                    alignment: AlignmentDirectional.centerStart,
                    child: Text(
                      spaceUuid,
                      style: _getTextStyle(context)?.copyWith(
                        fontSize: 10,
                      ),
                    ),
                  ),
            ],
          ),
        );
      }).toList(),
      onChanged: (value) {
        if (value case final AnalyticsDevice device) {
          context.read<AnalyticsDevicesBloc>().add(
                SelectAnalyticsDeviceEvent(device),
              );
          onChanged.call(device);
        }
      },
    );
  }

  TextStyle? _getTextStyle(BuildContext context) {
    return context.textTheme.labelSmall?.copyWith(
      color: ColorsManager.textPrimaryColor,
      fontWeight: FontWeight.w700,
      fontSize: 14,
    );
  }
}
