import 'package:eva_icons_flutter/eva_icons_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:mitra_corporate/provider/menu_provider.dart';
import 'package:mitra_corporate/screen/result/search_result_provider.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';

import '../../app/constant.dart';
import '../../model/surat_jalan_model.dart';
import '../../provider/auth_provider.dart';
import '../../provider/surat_jalan_provider.dart';
import '../../widgets/custom_snackbar_widget.dart';
import '../../widgets/custom_text_field.dart';
import '../../widgets/header.dart';
import '../registrasi/table_pasien.dart';

class ResultScreen extends HookConsumerWidget {
  const ResultScreen({super.key});
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final keyword = useState("");
    final keywordCtr = useTextEditingController(text: "");
    final auth = ref.watch(authProvider);
    final suratJalanTab = ref.watch(suratJalanProvider);
    final rowsPerPage = useState(10);
    final searchLoading = useState(false);
    final dataStart = useState(1);
    final dataEnd = useState(1);
    final currPage = useState(1);
    final sjList = useState<SearchSuratJalanModel>(
        SearchSuratJalanModel(suratJalan: [], total: "0", totalPage: 0));

    onRefresh() {
      ref.read(SearchResultProvider.notifier).getData(
          ed: "",
          sd: "",
          token: auth?.token ?? "",
          page: currPage.value.toString(),
          keyword: keyword.value,
          rpp: rowsPerPage.value.toString(),
          company_id: auth?.mUserMCompanyID ?? "");
    }

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        debouncer.run(() {
          onRefresh();
        });
      });
      return () {};
    }, [currPage.value, suratJalanTab]);

    useEffect(() {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
        final debouncer = Debouncer(milliseconds: 100);
        currPage.value = 1;
        debouncer.run(() {
          ref.read(SearchResultProvider.notifier).getData(
              ed: "",
              sd: "",
              token: auth?.token ?? "",
              page: "1",
              keyword: keyword.value,
              rpp: rowsPerPage.value.toString(),
              company_id: auth?.mUserMCompanyID ?? "");
        });
      });
      return () {};
    }, [
      keyword.value,
      rowsPerPage.value,
    ]);

    ref.listen(
      SearchResultProvider,
      (pref, next) {
        if (next is SearchResultStateInit) {
          searchLoading.value = true;
        } else if (next is SearchResultStateLoading) {
          searchLoading.value = true;
        } else if (next is SearchResultStateError) {
          searchLoading.value = false;
          SanckbarWidget(context, next.message, snackbarType.error);
          Constant.autoLogout(context: context, msg: next.message);
        } else if (next is SearchResultStateDone) {
          sjList.value = next.model;
          // print(jsonEncode(next.model));

          dataStart.value =
              (currPage.value * rowsPerPage.value) - rowsPerPage.value + 1;
          dataEnd.value = currPage.value == next.model.totalPage
              ? int.parse(next.model.total ?? "0")
              : dataStart.value + rowsPerPage.value - 1;

          searchLoading.value = false;
        }
      },
    );
    return Material(
        child: Column(children: [
      Header(),
      Padding(
          padding: const EdgeInsets.all(32.0),
          child:
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
            Container(
              alignment: Alignment.centerLeft,
              // width: Constant.getActualX(context: context, x: 1079),
              height: Constant.getActualY(context: context, y: 40),
              child: Text('Hasil',
                  style: Constant.h3_400(context: context)
                      .copyWith(color: Constant.textBlack)),
            ),
            SizedBox(height: Constant.getActualY(context: context, y: 42)),
            Container(
              alignment: Alignment.centerLeft,
              width: Constant.getActualX(context: context, x: 409),
              child: CustomTextField(
                onChange: (value) {
                  keyword.value = value;
                },
                // controller: searchCtr,
                isPassword: false,
                hintText: "Cari Nomor Surat Jalan",
                labelText: "Cari",
                suffixIcon: Icon(EvaIcons.search),
              ),
            ),
            SizedBox(height: Constant.getActualY(context: context, y: 24)),
            Material(
                elevation: 5,
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8)),
                child: Column(children: [
                  Row(
                    children: [
                      Expanded(
                          flex: 2,
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(
                              alignment: Alignment.centerLeft,
                              // width: Constant.getActualX(context: context, x: 171),
                              height:
                                  Constant.getActualY(context: context, y: 64),
                              // color: Constant.grey_200,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 12, bottom: 12, left: 24, right: 24),
                                child: Text('Tanggal',
                                    overflow: TextOverflow.ellipsis,
                                    style: Constant.body3_600(context: context)
                                        .copyWith(color: Constant.textGrey)),
                              ),
                            ),
                          )),
                      Expanded(
                        flex: 2,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          // width: Constant.getActualX(context: context, x: 171),
                          height: Constant.getActualY(context: context, y: 64),
                          // color: Constant.grey_200,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 12, bottom: 12, left: 24, right: 24),
                            child: Text('Nomor Surat Jalan',
                                overflow: TextOverflow.ellipsis,
                                style: Constant.body3_600(context: context)
                                    .copyWith(color: Constant.textGrey)),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          // width: Constant.getActualX(context: context, x: 171),
                          height: Constant.getActualY(context: context, y: 64),
                          // color: Constant.grey_200,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 12, bottom: 12, left: 24, right: 24),
                            child: Text('Staff PIC',
                                overflow: TextOverflow.ellipsis,
                                style: Constant.body3_600(context: context)
                                    .copyWith(color: Constant.textGrey)),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          // width: Constant.getActualX(context: context, x: 171),
                          height: Constant.getActualY(context: context, y: 64),
                          // color: Constant.grey_200,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 12, bottom: 12, left: 24, right: 24),
                            child: Text('New',
                                overflow: TextOverflow.ellipsis,
                                style: Constant.body3_600(context: context)
                                    .copyWith(color: Constant.textGrey)),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          // width: Constant.getActualX(context: context, x: 171),
                          height: Constant.getActualY(context: context, y: 64),
                          // color: Constant.grey_200,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 12, bottom: 12, left: 24, right: 24),
                            child: Text('Send',
                                overflow: TextOverflow.ellipsis,
                                style: Constant.body3_600(context: context)
                                    .copyWith(color: Constant.textGrey)),
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          alignment: Alignment.centerLeft,
                          // width: Constant.getActualX(context: context, x: 171),
                          height: Constant.getActualY(context: context, y: 64),
                          // color: Constant.grey_200,
                          child: Padding(
                            padding: const EdgeInsets.only(
                                top: 12, bottom: 12, left: 24, right: 24),
                            child: Text('Receive',
                                overflow: TextOverflow.ellipsis,
                                style: Constant.body3_600(context: context)
                                    .copyWith(color: Constant.textGrey)),
                          ),
                        ),
                      ),
                    ],
                  ),
                  Container(
                    color: Colors.white,
                    height: Constant.getActualY(context: context, y: 500),
                    child: searchLoading.value
                        ? Center(
                            child: LoadingAnimationWidget.discreteCircle(
                                color: Constant.primaryBlue, size: 40))
                        : ListView(
                            children: sjList.value.suratJalan!
                                .map(
                                  (e) => TextButton(
                                    onPressed: () {
                                      ref.read(suratJalanID.notifier).state =
                                          e.id ?? "";

                                      ref
                                          .read(suratJalanNumber.notifier)
                                          .state = e.orderNumber ?? "";
                                      ref
                                          .read(currentMenuProvider.notifier)
                                          .state = 7;
                                    },
                                    style: TextButton.styleFrom(
                                        foregroundColor: Constant.primaryBlue),
                                    child: Row(
                                      children: [
                                        Expanded(
                                            flex: 2,
                                            child: Padding(
                                              padding:
                                                  const EdgeInsets.all(8.0),
                                              child: Container(
                                                alignment: Alignment.centerLeft,
                                                // width: Constant.getActualX(context: context, x: 171),
                                                // height: Constant.getActualY(
                                                //     context: context, y: 64),
                                                // color: Constant.grey_200,
                                                child: Padding(
                                                  padding:
                                                      const EdgeInsets.only(
                                                          top: 12,
                                                          bottom: 12,
                                                          left: 24,
                                                          right: 24),
                                                  child: Text(e.date ?? "",
                                                      overflow:
                                                          TextOverflow.ellipsis,
                                                      style: Constant.body3_600(
                                                              context: context)
                                                          .copyWith(
                                                              color: Colors
                                                                  .black)),
                                                ),
                                              ),
                                            )),
                                        Expanded(
                                          flex: 2,
                                          child: Container(
                                            alignment: Alignment.centerLeft,
                                            // width: Constant.getActualX(context: context, x: 171),
                                            // height: Constant.getActualY(
                                            //     context: context, y: 64),
                                            // color: Constant.grey_200,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 12,
                                                  bottom: 12,
                                                  left: 24,
                                                  right: 24),
                                              child: Text(e.orderNumber ?? "",
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: Constant.body3_600(
                                                          context: context)
                                                      .copyWith(
                                                          color: Colors.black)),
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 3,
                                          child: Container(
                                            alignment: Alignment.centerLeft,
                                            // width: Constant.getActualX(context: context, x: 171),
                                            // height: Constant.getActualY(
                                            //     context: context, y: 64),
                                            // color: Constant.grey_200,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 12,
                                                  bottom: 12,
                                                  left: 24,
                                                  right: 24),
                                              child: Text(e.pic ?? "",
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: Constant.body3_600(
                                                          context: context)
                                                      .copyWith(
                                                          color: Colors.black)),
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 1,
                                          child: Container(
                                            alignment: Alignment.centerLeft,
                                            // width: Constant.getActualX(context: context, x: 171),
                                            // height: Constant.getActualY(
                                            //     context: context, y: 64),
                                            // color: Constant.grey_200,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 12,
                                                  bottom: 12,
                                                  left: 24,
                                                  right: 24),
                                              child: e.status == "N" ||
                                                      e.status == "S" ||
                                                      e.status == "D"
                                                  ? Icon(
                                                      EvaIcons.checkmarkCircle2,
                                                      size: 24,
                                                      color: Constant.green,
                                                    )
                                                  : null,
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 1,
                                          child: Container(
                                            alignment: Alignment.centerLeft,
                                            // width: Constant.getActualX(context: context, x: 171),
                                            // height: Constant.getActualY(
                                            //     context: context, y: 64),
                                            // color: Constant.grey_200,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 12,
                                                  bottom: 12,
                                                  left: 24,
                                                  right: 24),
                                              child: Row(
                                                children: [
                                                  if (e.status == "S" ||
                                                      e.status == "D")
                                                    Icon(
                                                      EvaIcons.checkmarkCircle2,
                                                      size: 24,
                                                      color: Constant.green,
                                                    ),
                                                  if (e.status == "X")
                                                    Icon(
                                                      EvaIcons.closeCircle,
                                                      size: 24,
                                                      color: Colors.red,
                                                    ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 1,
                                          child: Container(
                                            alignment: Alignment.centerLeft,
                                            // width: Constant.getActualX(context: context, x: 171),
                                            // height: Constant.getActualY(
                                            //     context: context, y: 64),
                                            // color: Constant.grey_200,
                                            child: Padding(
                                              padding: const EdgeInsets.only(
                                                  top: 12,
                                                  bottom: 12,
                                                  left: 24,
                                                  right: 24),
                                              child: e.status == "D"
                                                  ? Icon(
                                                      EvaIcons.checkmarkCircle2,
                                                      size: 24,
                                                      color: Constant.green,
                                                    )
                                                  : null,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                )
                                .toList(),
                          ),
                  ),
                  Divider(),
                  SizedBox(
                    // color: Colors.white,
                    height: Constant.getActualY(context: context, y: 60),
                    child: Row(
                      children: [
                        Spacer(),
                        Text(
                          "Rows per page :",
                          style: Constant.body3_400(context: context),
                        ),
                        SizedBox(
                          width: Constant.getActualX(context: context, x: 24),
                        ),
                        DropdownButton<int>(
                            value: rowsPerPage.value,
                            dropdownColor: Colors.white,
                            elevation: 0,
                            style: Constant.body3_400(context: context)
                                .copyWith(color: Colors.black),
                            underline: Container(),
                            icon: Icon(Icons.keyboard_arrow_down_rounded),
                            focusColor: Colors.white,
                            items: [
                              DropdownMenuItem(
                                value: 10,
                                child: Text("10"),
                              ),
                              DropdownMenuItem(
                                value: 15,
                                child: Text("15"),
                              ),
                              DropdownMenuItem(
                                value: 20,
                                child: Text("20"),
                              ),
                              DropdownMenuItem(
                                value: 30,
                                child: Text("30"),
                              ),
                              DropdownMenuItem(
                                value: 40,
                                child: Text("40"),
                              ),
                              DropdownMenuItem(
                                value: 50,
                                child: Text("50"),
                              ),
                            ],
                            onChanged: (value) {
                              rowsPerPage.value = value!;
                            }),
                        SizedBox(
                          width: Constant.getActualX(context: context, x: 24),
                        ),
                        Text(
                          "${dataStart.value} - ${dataEnd.value} of ${sjList.value.total}",
                          style: Constant.body3_400(context: context),
                        ),
                        SizedBox(
                          width: Constant.getActualX(context: context, x: 24),
                        ),
                        IconButton(
                            iconSize: 20,
                            onPressed: currPage.value > 1
                                ? () {
                                    currPage.value = currPage.value - 1;
                                  }
                                : null,
                            icon: Icon(Icons.arrow_back_ios_new_rounded)),
                        SizedBox(
                          width: Constant.getActualX(context: context, x: 10),
                        ),
                        IconButton(
                            iconSize: 20,
                            onPressed:
                                currPage.value < sjList.value.totalPage!.toInt()
                                    ? () {
                                        currPage.value = currPage.value + 1;
                                      }
                                    : null,
                            icon: Icon(Icons.arrow_forward_ios_outlined)),
                        SizedBox(
                          width: Constant.getActualX(context: context, x: 24),
                        )
                      ],
                    ),
                  )
                ]))
          ]))
    ]));
  }
}
