import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'package:intl/intl.dart';
import 'package:mitra_corporate/app/constant.dart';
import 'package:mitra_corporate/model/create_surat_jalan_model.dart';
import 'package:mitra_corporate/provider/auth_provider.dart';
import 'package:mitra_corporate/provider/surat_jalan_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/create_surat_jalan_provider.dart';
import 'package:mitra_corporate/screen/surat_jalan/dialog_send_qr.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../widgets/custom_snackbar_widget.dart';

class SuratJalanConfirmation extends HookConsumerWidget {
  const SuratJalanConfirmation({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final tempSuratjalan = ref.watch(createSuratJalanProvider);
    final auth = ref.watch(authProvider);
    final date = useState("");
    final loading = useState(false);
    final number = useState("");

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        DateTime now = DateTime.parse(tempSuratjalan.order!.date!);
        // DateTime now = DateTime.now();
        initializeDateFormatting('id', '').then((_) {
          date.value = DateFormat('EEEE, d MMMM yyyy', "id").format(now);
          print(DateFormat('EEEE, d MMMM yyyy', "id").format(now));
        });
      });
      return () {};
    }, []);

    addOrder() {
      // print(jsonEncode(tempSuratjalan));
      // return;

      ref.read(CreateSuratJalanProvider.notifier).addOrder(prm: tempSuratjalan);
    }

    ref.listen(
      CreateSuratJalanProvider,
      (previous, next) {
        if (next is CreateSuratJalanStateInit) {
          loading.value = true;
        } else if (next is CreateSuratJalanStateLoading) {
          loading.value = true;
        } else if (next is CreateSuratJalanStateError) {
          SanckbarWidget(context, next.message, snackbarType.error);
          loading.value = false;
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is CreateSuratJalanStateDone) {
          // print(jsonEncode(next.model));
          number.value = next.number;
          SanckbarWidget(
              context,
              "Pengiriman order berhasil di buat ${next.number}",
              snackbarType.success);
          List<String> arrOrderID = List.empty(growable: true);
          for (var element in tempSuratjalan.orderDetail!) {
            arrOrderID.add(element.orderId!);
          }
          Navigator.pop(context);
          ref.read(createSuratJalanProvider.notifier).state =
              CreateSuratJalanModel();
          ref.read(suratJalanProvider.state).update((state) => 1);

          showDialog<String>(
            context: context,
            barrierDismissible: false,
            builder: (BuildContext context) => DialogSendQr(
              arrOrderID: arrOrderID,
              orderNumber: next.number,
            ),
          );

          loading.value = false;
        }
      },
    );

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          "Anda yakin dengan pengiriman order berikut ?",
          style: Constant.h4_600(context: context),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Regional",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  tempSuratjalan.order?.regionalName ?? "",
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 20),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Cabang",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  tempSuratjalan.order?.destinationName ?? "",
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 20),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Staff PIC",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  auth?.mUserUsername ?? "",
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 20),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Nomor Referensi",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  tempSuratjalan.order?.noRef ?? "",
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 20),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Tanggal Kirim Order",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  date.value,
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 20),
        ),
        Row(
          children: [
            Expanded(
                flex: 3,
                child: Container(
                  margin: EdgeInsets.only(
                      left: Constant.getActualX(context: context, x: 24)),
                  child: Text(
                    "Catatan",
                    style: Constant.body1_600(context: context)
                        .copyWith(color: Constant.textGrey),
                  ),
                )),
            Expanded(
                flex: 9,
                child: Text(
                  tempSuratjalan.order?.note ?? "",
                  style: Constant.body1_600(context: context),
                ))
          ],
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 28),
        ),
        SizedBox(
          height: Constant.getActualY(context: context, y: 64),
          child: Text(
            "List Pasien Terpilih",
            style: Constant.h4_600(context: context),
          ),
        ),
        Container(
          height: Constant.getActualY(context: context, y: 64),
          decoration: BoxDecoration(
              color: Constant.grey_200, borderRadius: BorderRadius.circular(8)),
          child: Row(
            children: [
              Expanded(
                  flex: 3,
                  child: Container(
                    margin: EdgeInsets.only(
                        left: Constant.getActualX(context: context, x: 24)),
                    child: Text(
                      "Nomor Registrasi",
                      style: Constant.body3_600(context: context)
                          .copyWith(color: Constant.textGrey),
                    ),
                  )),
              Expanded(
                  flex: 3,
                  child: Container(
                    margin: EdgeInsets.only(
                        left: Constant.getActualX(context: context, x: 24)),
                    child: Text(
                      "Nama Pasien",
                      style: Constant.body3_600(context: context)
                          .copyWith(color: Constant.textGrey),
                    ),
                  )),
              Expanded(
                  flex: 6,
                  child: Container(
                    margin: EdgeInsets.only(
                        left: Constant.getActualX(context: context, x: 24)),
                    child: Text(
                      "Pemeriksaan",
                      style: Constant.body3_600(context: context)
                          .copyWith(color: Constant.textGrey),
                    ),
                  )),
            ],
          ),
        ),
        ...tempSuratjalan.orderDetail!.map((e) => Container(
              constraints: BoxConstraints(
                  minHeight: Constant.getActualX(context: context, x: 64)),
              margin: EdgeInsets.only(
                  bottom: Constant.getActualX(context: context, x: 10)),
              child: Row(
                children: [
                  Expanded(
                      flex: 3,
                      child: Container(
                        margin: EdgeInsets.only(
                            left: Constant.getActualX(context: context, x: 24)),
                        child: Text(
                          e.orderNumber ?? "",
                          style: Constant.body3_600(context: context),
                        ),
                      )),
                  Expanded(
                      flex: 3,
                      child: Container(
                        margin: EdgeInsets.only(
                            left: Constant.getActualX(context: context, x: 24)),
                        child: Text(
                          e.patientName ?? "",
                          style: Constant.body3_600(context: context),
                        ),
                      )),
                  Expanded(
                      flex: 6,
                      child: Container(
                        margin: EdgeInsets.only(
                            left: Constant.getActualX(context: context, x: 24)),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Wrap(
                              children: [
                                ...e.tests!.map((i) => Container(
                                      margin: EdgeInsets.only(
                                          top: Constant.getActualX(
                                              context: context, x: 10),
                                          right: Constant.getActualX(
                                              context: context, x: 10),
                                          bottom: Constant.getActualX(
                                              context: context, x: 10)),
                                      child: Chip(
                                        shape: RoundedRectangleBorder(
                                          borderRadius: BorderRadius.all(
                                              Radius.circular(6)),
                                        ),
                                        // backgroundColor:
                                        //     Constant.grey_200,
                                        label: Text(
                                            '$i '.replaceAll(' ', '\u00A0'),
                                            overflow: TextOverflow.ellipsis,
                                            style: Constant.caption1_600(
                                                    context: context)
                                                .copyWith(
                                                    color: Constant.textBlack)),
                                      ),
                                    )),
                              ],
                            ),
                          ],
                        ),
                      )),
                ],
              ),
            )),
        SizedBox(
          height: Constant.getActualY(context: context, y: 12),
        ),
        Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            SizedBox(
              height: Constant.getActualY(context: context, y: 45),
              child: OutlinedButton(
                  style: OutlinedButton.styleFrom(
                      backgroundColor: Colors.white,
                      side: BorderSide(color: Colors.grey, width: 2),
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8))),
                  onPressed: !loading.value
                      ? () {
                          // ref.read(createSuratJalanProvider.notifier).state =
                          //     CreateSuratJalanModel();
                          ref
                              .read(suratJalanProvider.state)
                              .update((state) => 1);

                          // Navigator.pop(context);
                        }
                      : null,
                  child: loading.value
                      ? LoadingAnimationWidget.staggeredDotsWave(
                          color: Constant.green, size: 20)
                      : Text('Batal',
                          style: Constant.body3_600(context: context)
                              .copyWith(color: Constant.textBlack))),
            ),
            SizedBox(width: Constant.getActualX(context: context, x: 24)),
            Container(
              height: Constant.getActualY(context: context, y: 45),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(8),
                  color: Constant.green),
              child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Constant.green,
                    side: BorderSide(color: Constant.green, width: 2),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  onPressed: !loading.value
                      ? () {
                          addOrder();
                        }
                      : null,
                  child: loading.value
                      ? LoadingAnimationWidget.staggeredDotsWave(
                          color: Colors.white, size: 20)
                      : Text('Simpan',
                          style: Constant.body3_600(context: context)
                              .copyWith(color: Constant.textWhite))),
            ),
          ],
        )
      ],
    );
  }
}
