import 'dart:async';
import 'dart:convert';

import 'package:animated_text_kit/animated_text_kit.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_pos_printer_platform_image_3/flutter_pos_printer_platform_image_3.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ticket_booth/app/constant.dart';
import 'package:ticket_booth/app/route.dart';
import 'package:ticket_booth/model/printer_device.dart';

import '../widgets/error_dialog.dart';

class SplashScreen extends HookConsumerWidget {
  const SplashScreen({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final PrinterManager pm = PrinterManager.instance;

    _connectDevice(PrinterDev selectedPrinter, PrinterType type,
        {bool reconnect = true, String? ipAddress = null}) async {
      try {
        await pm.connect(
            type: type,
            model: UsbPrinterInput(
                name: selectedPrinter.deviceName,
                productId: selectedPrinter.productId,
                vendorId: selectedPrinter.vendorId));
      } catch (e) {
        print(e);
      }
    }

    Future getData() async {
      try {
        final prefs = await SharedPreferences.getInstance();
        var raw_data = prefs.getString('tb-westerindo') ?? 'a';

        if (raw_data != 'a') {
          var data = json.decode(raw_data);
          PrinterDev selectedPrinter =
              PrinterDev.fromJson(data['selectedPrinter']);
          _connectDevice(selectedPrinter, PrinterType.usb);
        }
      } catch (e) {
        print(e);
        ErrorDialog(context, e.toString(), 'ERROR');
      }
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        await getData();
        Timer(const Duration(seconds: 3), () {
          Navigator.of(context).pushNamed(displayRoute);
        });
      });
      return () {};
    }, []);
    return Material(
        child: Container(
      height: Constant.getActualY(context: context, y: 982),
      width: Constant.getActualX(context: context, x: 1512),
      decoration: const BoxDecoration(
          image: DecorationImage(
              fit: BoxFit.cover,
              image: AssetImage("assets/images/new-bg-icon.png"))),
      child: Column(
        children: [
          SizedBox(
            height: Constant.getActualY(context: context, y: 600),
            width: Constant.getActualX(context: context, x: 1512),
          ),
          const SpinKitFadingCube(
            color: Colors.redAccent,
            size: 50.0,
          ),
          SizedBox(
            height: Constant.getActualY(context: context, y: 50),
          ),
          DefaultTextStyle(
              style: Constant.title(context: context)
                  .copyWith(fontStyle: FontStyle.italic, color: Colors.black),
              child: AnimatedTextKit(animatedTexts: [
                TyperAnimatedText('Loading ...',
                    speed: Duration(milliseconds: 300))
              ])),
          SizedBox(
            height: Constant.getActualY(context: context, y: 50),
          ),
          Text(
            Constant.versi,
            style: Constant.subTitle(context: context)
                .copyWith(fontStyle: FontStyle.italic, color: Colors.grey),
          )
        ],
      ),
    ));
  }
}
