import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:nut_player_example/src/features/main_screen/domain/json_bloc/json_bloc.dart';
import 'options_list.dart';
import 'url_input.dart';

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

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<JsonBloc, JsonState>(
      builder: (context, state) {
        return Column(
          children: _buildAllWidgets(context, state, null)
        );
      },
    );
  }

  List<Widget> _buildAllWidgets(BuildContext context, JsonState state, int? index) {
    List<Widget> widgets = [];

    final parent = state.parent;
    if (parent != null) {
      widgets.addAll(_buildAllWidgets(context, parent, state.initialIndex));
    }

    var widget = _buildWidget(state, context, index);

    if (widget != null) {
      widgets.removeWhere((element) => element.key == widget.key);
      widgets.add(widget);
    }

    return widgets;
  }

  Widget? _buildWidget(JsonState state, BuildContext context, int? index) {
    if (state.uiType == UIType.input) {
      return URLInput(
          state.title,
          state.urlPath!,
          (value) {
            final createString = state.createStringEvent;
            if (createString != null) {
              context.read<JsonBloc>().add(createString(value));
            }
          },
          key: state.key,
      );
    } else if (state.uiType == UIType.list) {
      if (state.options.isEmpty) { return _buildLoader(); }
      var isListCheckmarked = state.options.length > 2;
        return OptionsList(
            state.options,
            isListCheckmarked ? state.currentIndex : index,
            state.title,
            isListCheckmarked ? ListType.checkmark : ListType.radio,
            (selectedIndex) {
              final createIndexed = state.createIndexedEvent;
              if (createIndexed != null) {
                context.read<JsonBloc>().add(createIndexed(selectedIndex));
              }
            },
            key: state.key
        );
    } else {
      return null;
    }
  }

  Widget _buildLoader() {
    return Container(
      margin: const EdgeInsets.all(10),
      width: double.infinity,
      height: 80,
      child: const CupertinoActivityIndicator(radius: 20),
    );
  }
}
