import 'dart:convert';

import 'package:app_petty_cash/screen/home/info_account_balance_provider.dart';
import 'package:app_petty_cash/screen/home/list_transaksi_home_provider.dart';
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 '../../app/constant.dart';
import '../../app/route.dart';
import '../../model/info_account_balance.dart';
import '../../model/list_transaksi_model.dart';
import '../../provider/current_info_account_balance_provider.dart';
import '../../provider/current_user_provider.dart';
import '../../widget/custom_drawer.dart';
import '../../widget/history_row_atas_widget.dart';
import '../../widget/sankbar_widget.dart';

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

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final M_CompanyID = useState<String>("0");
    final searchTransaksiHomeLoading = useState<bool>(false);
    final infoAccountBalanceHomeLoading = useState<bool>(false);
    final listTransaksiHome = useState<List<ListTransaksiHomeModel>>(
      List.empty(growable: true),
    );
    final M_CompanyName = useState("-");

    // company name
    Future<String> getCompanyName() async {
      final shared = await SharedPreferences.getInstance();
      String M_CompanyName = "-";

      if (shared != null) {
        final bearerString = shared.get(Constant.bearerName).toString();
        final xmodel = jsonDecode(bearerString);
        if (xmodel != null) {
          M_CompanyName = xmodel["model"]["M_CompanyName"];
        }
      }

      if (M_CompanyName == "0") {
        // throw BaseRepositoryException(message: 'Invalid Company ID');
      }

      return M_CompanyName;
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final userID = ref.read(currentUserProvider)?.model.M_UserID ?? "0";
        if (userID == "0") {
          //not login
          Navigator.of(context)
              .pushNamedAndRemoveUntil(loginRoute, (route) => true);

          //  Navigator.popAndPushNamed(context, loginRoute);
          return;
        }
        M_CompanyName.value = await getCompanyName();
      });
      return () {};
    }, []);

    Future<String> getCompanyID() async {
      final shared = await SharedPreferences.getInstance();
      String M_CompanyID = "0";

      if (shared != null) {
        final bearerString = shared.get(Constant.bearerName).toString();
        final xmodel = jsonDecode(bearerString);
        if (xmodel != null) {
          M_CompanyID = xmodel["model"]["M_CompanyID"];
        }
      }

      if (M_CompanyID == "0") {
        // throw BaseRepositoryException(message: 'Invalid Company ID');
      }

      return M_CompanyID;
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        M_CompanyID.value = await getCompanyID();
        // info account balance
        ref
            .read(infoAccountBalanceHomeProvider.notifier)
            .infoAccountBalanceHome(M_CompanyID.value);
      });
      return () {};
    }, []);

    // read provider home
    ref.listen(
      listTransaksiHomeProvider,
      (previous, next) {
        if (next is ListTransaksiHomeStateLoading) {
          searchTransaksiHomeLoading.value = true;
        } else if (next is ListTransaksiHomeStateError) {
          // print(next.message);
          searchTransaksiHomeLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is ListTransaksiHomeStateDone) {
          // print(jsonEncode(next.model));
          // print(next.model.length);
          listTransaksiHome.value = next.model;
          searchTransaksiHomeLoading.value = false;
        }
      },
    );

    // read provider info account balance
    ref.listen(
      infoAccountBalanceHomeProvider,
      (previous, next) {
        if (next is InfoAccountBalanceHomeStateLoading) {
          infoAccountBalanceHomeLoading.value = true;
        } else if (next is InfoAccountBalanceHomeStateError) {
          // print(next.message);
          infoAccountBalanceHomeLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
        } else if (next is InfoAccountBalanceHomeStateDone) {
          // print(jsonEncode(next.model));
          // print(next.model.length);
          // infoAccountBalanceObject.value = next.model;
          ref.read(currentInfoAccountBalanceProvider.notifier).state =
              InfoAccountBalanceModel(
            kredit: next.model.kredit,
            debit: next.model.debit,
            totalAll: next.model.totalAll,
          );
          infoAccountBalanceHomeLoading.value = false;
        }
      },
    );

    return Padding(
      padding: EdgeInsets.only(
        top: Constant.getActualYPhone(context: context, y: 30),
      ),
      child: Scaffold(
        appBar: AppBar(
          title: Text(
            // 'Home Screen',
            M_CompanyName.value,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: Constant.textWhite,
            ),
          ),
          backgroundColor: Constant.pcBtnBackgroundColor,
          iconTheme: IconThemeData(
            color: Constant.textWhite,
          ),
        ),
        drawer: CustomDrawer(),
        body: SafeArea(
          child: Padding(
            padding: EdgeInsets.only(
              top: Constant.getActualYPhone(context: context, y: 36),
              left: Constant.getActualXPhone(context: context, x: 34),
              right: Constant.getActualXPhone(context: context, x: 34),
            ),
            child: RefreshIndicator(
              onRefresh: () async {
                ref
                    .read(infoAccountBalanceHomeProvider.notifier)
                    .infoAccountBalanceHome(M_CompanyID.value);
              },
              child: Container(
                width: Constant.getActualXPhone(context: context, x: 390),
                height: Constant.getActualYPhone(context: context, y: 844),
                child: Column(
                  children: [
                    Container(
                      width: Constant.getActualXPhone(context: context, x: 332),
                      height:
                          Constant.getActualYPhone(context: context, y: 173),
                      decoration: BoxDecoration(
                        // color: Colors.black12,
                        borderRadius: BorderRadius.circular(20),
                        image: DecorationImage(
                          image: AssetImage('images/background_card.png'),
                          fit: BoxFit.cover,
                        ),
                        boxShadow: [
                          BoxShadow(
                            color: Color.fromRGBO(145, 158, 171, 0.16),
                            offset: Offset(0, 24),
                            blurRadius: 48,
                          ),
                        ],
                      ),
                      //Isi Card
                      child: (infoAccountBalanceHomeLoading.value)
                          ? Center(
                              child: CircularProgressIndicator(),
                            )
                          : Container(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: [
                                  // Text1 & Text2
                                  Padding(
                                    padding: EdgeInsets.only(
                                      top: Constant.getActualYPhone(
                                          context: context, y: 17),
                                      left: Constant.getActualXPhone(
                                          context: context, x: 81),
                                      right: Constant.getActualXPhone(
                                          context: context, x: 81),
                                    ),
                                    child: Column(
                                      children: [
                                        Text(
                                          'Account Balance',
                                          style: Constant.body1(
                                                  context: context)
                                              .copyWith(
                                                  fontWeight: FontWeight.w400,
                                                  color: Constant.textWhite),
                                        ),
                                        Text(
                                          ref
                                              .watch(
                                                  currentInfoAccountBalanceProvider)
                                              .totalAll
                                              .toString(),
                                          style: Constant.H4_700V3(
                                                  context: context)
                                              .copyWith(
                                            color: Constant.textWhite,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),

                                  SizedBox(
                                    height: Constant.getActualYPhone(
                                        context: context, y: 27),
                                  ),

                                  //Debit dan Kredit
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      // Spasi di sebelah kiri "Check In"
                                      Expanded(
                                        child: Padding(
                                          padding: EdgeInsets.only(
                                            left: Constant.getActualXPhone(
                                                context: context, x: 20),
                                          ),
                                          child: Column(
                                            children: [
                                              Text(
                                                'Debit',
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w400,
                                                        color:
                                                            Constant.textWhite),
                                              ),
                                              Text(
                                                ref
                                                    .watch(
                                                        currentInfoAccountBalanceProvider)
                                                    .debit
                                                    .toString(),
                                                style: Constant.H4_700V3(
                                                        context: context)
                                                    .copyWith(
                                                        color:
                                                            Constant.textWhite),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),

                                      // SizedBox(
                                      //   width: Constant.getActualXPhone(
                                      //       context: context, x: 51),
                                      // ),

                                      Expanded(
                                        child: Padding(
                                          padding: EdgeInsets.only(
                                            right: Constant.getActualXPhone(
                                                context: context, x: 28),
                                          ),
                                          child: Column(
                                            children: [
                                              Text(
                                                'Credit',
                                                style: Constant.body1(
                                                        context: context)
                                                    .copyWith(
                                                        fontWeight:
                                                            FontWeight.w400,
                                                        color:
                                                            Constant.textWhite),
                                              ),
                                              Text(
                                                ref
                                                    .watch(
                                                        currentInfoAccountBalanceProvider)
                                                    .kredit
                                                    .toString(),
                                                style: Constant.H4_700V3(
                                                        context: context)
                                                    .copyWith(
                                                        color:
                                                            Constant.textWhite),
                                              ),
                                            ],
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                  SizedBox(
                                    height: Constant.getActualYPhone(
                                        context: context, y: 17),
                                  ),
                                ],
                              ),
                            ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 44),
                    ),

                    Align(
                      alignment: Alignment.centerLeft,
                      child: Text(
                        'Transaksi Terkini',
                        style: Constant.titleH5_600(context: context)
                            .copyWith(color: Constant.textBlack),
                      ),
                    ),

                    SizedBox(
                      height: Constant.getActualYPhone(context: context, y: 24),
                    ),

                    // list transaksi
                    (searchTransaksiHomeLoading.value)
                        ? Center(
                            child: CircularProgressIndicator(),
                          )
                        : Container(
                            child: Expanded(
                              child: ListView.builder(
                                itemCount: listTransaksiHome.value.length,
                                itemBuilder: (context, idx) {
                                  return Padding(
                                    padding: EdgeInsets.only(
                                      bottom: Constant.getActualYPhone(
                                        context: context,
                                        y: 10,
                                      ),
                                    ),
                                    child: Card(
                                      elevation: 2.0,
                                      child: Padding(
                                        padding: EdgeInsets.all(10),
                                        child: Column(
                                          // crossAxisAlignment: CrossAxisAlignment.start,
                                          // mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                            // atas
                                            HistoryRowAtasWidget(
                                              icon_category_id:
                                                  listTransaksiHome
                                                      .value[idx].kategoriid
                                                      .toString(),
                                              icon_category_name:
                                                  listTransaksiHome
                                                      .value[idx].kategoriname
                                                      .toString(),
                                              amount: listTransaksiHome
                                                  .value[idx].amount
                                                  .toString(),
                                              tglTransaksi: listTransaksiHome
                                                  .value[idx].tanggaltransaksi
                                                  .toString(),
                                              tipe: listTransaksiHome
                                                  .value[idx].tipe
                                                  .toString(),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                          ),
                  ],
                ),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
