import 'dart:io';

import 'package:example/pages/visual/visual_debug_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:get/get.dart';
import 'package:guru_widgets/appbar/guru_app_bar.dart';
import 'package:guru_widgets/button/guru_button.dart';
import 'package:guru_widgets/theme/guru_theme.dart';
import 'package:guru_popup/guru_popup.dart';
import 'package:guru_widgets/animation/lottie/lottie_widget.dart';
import 'package:guru_widgets/guru_widgets.dart';

class VisualDebugBinding extends Bindings {
  @override
  void dependencies() {
    Get.lazyPut(() => VisualDebugController());
  }
}

class VisualItemWidget extends StatefulWidget {
  final VisualInfo info;

  const VisualItemWidget({super.key, required this.info});

  @override
  State<StatefulWidget> createState() => _VisualItemState();
}

class _VisualItemState extends State<VisualItemWidget> with SingleTickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: LottieWidget(
          uri: widget.info.uri, duration: widget.info.duration, action: LottieAction.repeat),
    );
  }
}

class VisualDebugPage extends GetWidget<VisualDebugController> {
  const VisualDebugPage({super.key});

  Widget buildRootWidget({
    required BuildContext context,
    Color? backgroundColor,
    String? title,
    Color? appbarColor,
    required Widget body,
  }) {
    final guruTheme = GuruTheme.of(context);
    final colorScheme = guruTheme.colorScheme;
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: Scaffold(
        backgroundColor: backgroundColor ?? colorScheme.backgroundColor,
        appBar: _buildAppBar(context),
        body: body,
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(BuildContext context) {
    return GuruAppBar(backgroundColor: Colors.transparent, actions: [
      GuruButton(
        size: const Size(128, 48),
        action: "Open Lottie",
        style: GuruButtonStyle.positive,
        onPressed: () async {
          await controller.loadVisual();
        },
      )
    ]);
  }

  @override
  Widget build(BuildContext context) {
    final guruTheme = GuruTheme.of(context);
    return buildRootWidget(
        context: context,
        backgroundColor: guruTheme.colorScheme.backgroundColor,
        body: StreamBuilder<VisualInfo>(
            stream: controller.observableVisualInfo,
            builder: (context, snapshot) {
              final visualInfo = snapshot.data;
              if (visualInfo == null || visualInfo == VisualInfo.invalid) {
                return const EmptySpacer();
              }
              return VisualItemWidget(info: visualInfo);
            }));
  }
}
