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

import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.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/print_ticket.dart';
import 'package:ticket_booth/app/route.dart';
import 'package:ticket_booth/provider/all_service_provider.dart';
import 'package:ticket_booth/screen/initial/service_list_provider.dart';

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

class InitialScreen extends HookConsumerWidget {
  const InitialScreen({super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final isLoading = useState(false);
    final errorMsg = useState('');
    final hostIp = useState('N');
    final testPrintDisabled = useState(true);
    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);
          hostIp.value = data['hostIp'];
          testPrintDisabled.value = false;
        }
      } catch (e) {
        print(e);
        ErrorDialog(context, e.toString(), 'ERROR');
      }
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        await getData();
        if (hostIp.value != 'N') {
          ref.read(ServiceListProvider.notifier).list(hostIp: hostIp.value);
        }
      });
      // Navigator.of(context).pushNamed(queueRoute);
      // final timer = Timer(const Duration(seconds: 10), () {
      // });
      return () {
        // timer.cancel();
      };
    }, []);
    ref.listen(ServiceListProvider, (previous, next) {
      if (next is ServiceListStateLoading) {
        isLoading.value = true;
      } else if (next is ServiceListStateError) {
        errorMsg.value = next.message;
        ErrorDialog(context, errorMsg.value, 'ERROR');
      } else if (next is ServiceListStateDone) {
        ref.read(allServiceProvider.notifier).state = next.model;
        // print(ref.read(allServiceProvider));
      }
    });
    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),
          ),
          Text(
            Constant.versi,
            style: Constant.subTitle(context: context)
                .copyWith(fontStyle: FontStyle.italic, color: Colors.grey),
          ),
          SizedBox(
            height: Constant.getActualY(context: context, y: 302),
            width: Constant.getActualX(context: context, x: 1512),
            child: Center(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        maximumSize: Size(
                            Constant.getActualX(context: context, x: 350),
                            Constant.getActualY(context: context, y: 100)),
                        elevation: 5,
                        side: const BorderSide(
                            width: 0.5,
                            color: Color.fromARGB(162, 204, 92, 146)),
                        backgroundColor: Colors.white,
                        foregroundColor: Colors.grey,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50))),
                    onPressed: () {
                      Navigator.of(context).popAndPushNamed(settingRoute);
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal:
                              Constant.getActualX(context: context, x: 51),
                          vertical:
                              Constant.getActualY(context: context, y: 21)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            'assets/images/setting.png',
                            height:
                                Constant.getActualY(context: context, y: 57),
                            width: Constant.getActualY(context: context, y: 57),
                          ),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 15),
                          ),
                          Text(
                            'Setting',
                            style: Constant.title(context: context)
                                .copyWith(color: Colors.black),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 166.5),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        elevation: 5,
                        maximumSize: Size(
                            Constant.getActualX(context: context, x: 350),
                            Constant.getActualY(context: context, y: 100)),
                        foregroundColor: Colors.grey,
                        side: const BorderSide(
                            width: 0.5,
                            color: Color.fromARGB(162, 204, 92, 146)),
                        backgroundColor: testPrintDisabled.value
                            ? Colors.grey
                            : Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50))),
                    onPressed: () {
                      if (testPrintDisabled.value) {
                      } else {
                        PrintTicket().printTest();
                      }
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal:
                              Constant.getActualX(context: context, x: 51),
                          vertical:
                              Constant.getActualY(context: context, y: 21)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            'assets/images/next.png',
                            height:
                                Constant.getActualY(context: context, y: 57),
                            width: Constant.getActualY(context: context, y: 57),
                          ),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 15),
                          ),
                          Text(
                            'Test Print',
                            style: Constant.title(context: context).copyWith(
                                color: testPrintDisabled.value
                                    ? Colors.white
                                    : Colors.black),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: Constant.getActualX(context: context, x: 166.5),
                  ),
                  ElevatedButton(
                    style: ElevatedButton.styleFrom(
                        elevation: 5,
                        maximumSize: Size(
                            Constant.getActualX(context: context, x: 350),
                            Constant.getActualY(context: context, y: 100)),
                        foregroundColor: Colors.grey,
                        side: const BorderSide(
                            width: 0.5,
                            color: Color.fromARGB(162, 204, 92, 146)),
                        backgroundColor: Colors.white,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(50))),
                    onPressed: () {
                      Navigator.of(context).pushNamed(queueRoute);
                    },
                    child: Padding(
                      padding: EdgeInsets.symmetric(
                          horizontal:
                              Constant.getActualX(context: context, x: 51),
                          vertical:
                              Constant.getActualY(context: context, y: 21)),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(
                            'assets/images/next.png',
                            height:
                                Constant.getActualY(context: context, y: 57),
                            width: Constant.getActualY(context: context, y: 57),
                          ),
                          SizedBox(
                            width: Constant.getActualX(context: context, x: 15),
                          ),
                          Text(
                            'Next',
                            style: Constant.title(context: context)
                                .copyWith(color: Colors.black),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          )
        ],
      ),
    ));
  }
}
