import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:nut_player_example/src/common/repository/settings_repository.dart';
import 'package:nut_player_example/src/features/main_screen/domain/main_bloc/main_bloc.dart';
import 'package:nut_player_example/src/features/main_screen/domain/json_bloc/json_bloc.dart';
import 'package:nut_player_example/src/features/main_screen/domain/url_bloc/url_bloc.dart';
import 'package:nut_player_example/src/features/main_screen/presentation/buttons.dart';
import 'package:nut_player_example/src/features/main_screen/presentation/json_view.dart';
import 'package:nut_player_example/src/features/main_screen/presentation/url_view.dart';
import 'package:nut_player_example/src/features/player_screen/presentation/player_view.dart';
import 'package:nut_player_example/src/features/settings_screen/domain/settings_bloc.dart';
import '../../player_screen/domain/bloc/playerview_bloc.dart';
import '../../settings_screen/presentation/settings_view.dart';

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

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp
    ]);
    return CupertinoPageScaffold(
      backgroundColor: CupertinoColors.extraLightBackgroundGray,
      navigationBar: CupertinoNavigationBar(
        key: const Key('AppBarID'),
        leading: Image.asset('assets/images/nut_logo.png', width: 154),
        border: null,
        backgroundColor: CupertinoColors.white,
      ),
      child: MultiBlocProvider(
        providers: [
          BlocProvider(create: (_) => MainBloc()),
          BlocProvider(create: (_) => JsonBloc()),
          BlocProvider(create: (_) => UrlBloc())
        ],
        child: BlocListener<MainBloc, MainState>(
          listener: (context, state) { _navigate(state, context); },
          child: SafeArea(
            child: CustomScrollView(
              slivers: <Widget>[
                SliverToBoxAdapter(
                    child: BlocBuilder<MainBloc, MainState>(
                      builder: (context, state) {
                        return Column(
                            children: [
                              Container(
                                key: const Key('MainSegmentedButtonID'),
                                width: double.infinity,
                                padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 16),
                                color: CupertinoColors.white,
                                child: _buildSegmentedButtonWidget(context, state.inputType, (newInputType) {
                                  if (newInputType != null) {
                                    context.read<MainBloc>().add(newInputType == InputType.json
                                        ? ChooseJsonEvent()
                                        : ChooseUrlEvent());
                                    newInputType == InputType.url
                                        ? context.read<JsonBloc>().add(JsonResetEvent())
                                        : context.read<UrlBloc>().add(UrlResetEvent());
                                  }
                                })
                              ),

                              if (state.inputType == InputType.url)
                                const URLView()
                              else if (state.inputType == InputType.json)
                                const JSONView()
                              else
                                const Text('unknown')
                            ]
                        );
                      },
                    )
                ),

                SliverFillRemaining(
                    hasScrollBody: false,
                    child: Align(
                      alignment: Alignment.bottomCenter,
                      child: Builder(
                        builder: (context) {
                          return const Buttons();
                        }
                      ),
                    )
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  _navigate(MainState state, BuildContext context) {
    final repository = context.read<SettingsRepository>();
    if (state is PlayerState) {
      Navigator.push(context, CupertinoPageRoute(builder: (_) {
        return BlocProvider(
            create: (BuildContext context) => PlayerViewBloc(provider: state.provider, repository: repository),
            child: BlocListener<PlayerViewBloc, PlayerViewState>(
              listener: (context, state) {
                if (state is PlayerViewDismiss) {
                  Navigator.of(context).pop();
                }
              },
              child: const PlayerView(),
            ),
        );
      }));
    } else if (state is SettingState) {
      Navigator.push(context, CupertinoPageRoute(builder: (_) {
        return BlocProvider(
            create: (context) => SettingsBloc(repository),
            child: BlocListener<SettingsBloc, SettingsState>(
              listener: (context, state) {
                if (state is SettingsDismiss) {
                  Navigator.of(context).pop();
                }
              },
              child: const SettingsView(),
            )
        );
      }));
    }
  }

  _buildSegmentedButtonWidget(BuildContext context, InputType currentInputType, Function(InputType?) onValueChanged) {
    return CupertinoSlidingSegmentedControl<InputType>(
      groupValue: currentInputType,
      onValueChanged: onValueChanged,
      children: const <InputType, Widget>{
        InputType.json: Padding(
          key: Key('JSONSegmentElementID'),
          padding: EdgeInsets.symmetric(vertical: 6),
          child: Text('JSON-конфиг',
              style: TextStyle(
                  decoration: TextDecoration.none,
                  fontSize: 16,
                  color: CupertinoColors.black,
                  fontWeight: FontWeight.normal)),
        ),

        InputType.url: Padding(
          key: Key('URLSegmentElementID'),
          padding: EdgeInsets.symmetric(vertical: 6),
          child: Text('Видео URL',
              style: TextStyle(
                  decoration: TextDecoration.none,
                  fontSize: 16,
                  color: CupertinoColors.black,
                  fontWeight: FontWeight.normal)),
        )
      },
    );
  }
}
