// ignore_for_file: sized_box_for_whitespace

import 'package:byod/bloc/branch_list.dart';
import 'package:byod/bloc/filter_menu.dart';
import 'package:byod/helper/helper.dart';
import 'package:byod/helper/prefs.dart';
import 'package:byod/models/branchs.dart';
import 'package:byod/ui/home/new_home2.dart';
import 'package:byod/ui/screen_responsive.dart';
import 'package:byod/ui/webview/webview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../bloc/search_branch.dart';
import '../helper/widget/button_dialog.dart';
import '../helper/widget/style.dart';
import 'app_bar_select_branch.dart';

class SelectBranch extends StatelessWidget {
  const SelectBranch({
    super.key,
    this.isFormBill = false,
  });

  final bool isFormBill;
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: backgroundColor,
        body: ScreenResponsive(
          widget: CoreBranch(
            isFormBill: isFormBill,
          ),
          widthScreen: MediaQuery.of(context).size.width,
          isCoreLayout: true,
        ),
      ),
    );
  }
}

class CoreBranch extends StatelessWidget {
  const CoreBranch({
    super.key,
    required this.isFormBill,
  });

  final bool isFormBill;
  @override
  Widget build(BuildContext context) {
    double widthScreen = responsiveWidthScreen(context);
    return Container(
      width: widthScreen,
      // padding: const EdgeInsets.symmetric(horizontal: paddingLeftRight),
      child: Column(
        children: [
          CustomAppBar(
              // allBranch: listB,
              ),
          const SizedBox(
            height: 16,
          ),
          BlocBuilder<BranchList, List<Branch>>(
            builder: (context, listB) {
              return BlocBuilder<SearchBranch, List<Branch>>(
                builder: (contextSearch, listSearch) {
                  List<Branch> listBranch;
                  if (listSearch.isNotEmpty) {
                    if (listSearch[0].id == '0') {
                      listBranch = listB;
                    } else {
                      listBranch = listSearch;
                    }
                  } else {
                    listBranch = listSearch;
                  }
                  return Expanded(
                    child: ListView.builder(
                        itemCount: listBranch.length,
                        itemBuilder: (context, i) {
                          return GestureDetector(
                            onTap: () {
                              void ontapOkeChange() {
                                Navigator.pushReplacement(
                                  context,
                                  MaterialPageRoute(
                                    builder: (_) => WebViewMap(
                                      titleAppBar: 'Pilih Alamat',
                                      url:
                                          '${getBaseUrl()}rdm/address/add/?session_id=${getSessionId()}',
                                      isFromSelectBranch: true,
                                    ),
                                  ),
                                );
                              }

                              String textOnOk = 'OK';
                              String textOnCancel = 'Batal';
                              String title = 'Alamat Terlalu Jauh';
                              String description = '''
Lokasi anda saat ini terlalu jauh dari outlet kami, silakan ganti alamat.

Apakah ingin ganti alamat ?''';

                              void onTapCancelChange() {
                                Navigator.pop(context);
                              }

                              if (listBranch[i].isDelivery == false &&
                                  listBranch[i].isPickup == false) {
                                EasyLoading.showToast(
                                    'Outlet tidak menerima delivery dan pickup');
                              } else if (listBranch[i].distance >
                                  getServiceRadius().toDouble()) {
                                buttonDialogGlobal(
                                  context,
                                  title,
                                  description,
                                  textOnOk,
                                  textOnCancel,
                                  ontapOkeChange,
                                  onTapCancelChange,
                                  okButtonColor: buttonColor,
                                );
                              } else {
                                if (isFormBill) {
                                  changeBranch(listBranch[i].branchCode)
                                      .then((value) {
                                    if (value['status']
                                            .toString()
                                            .toLowerCase() ==
                                        'ok') {
                                      context.read<FilterMenuBloc>().catAndMenu(
                                            listBranch[i].branchCode,
                                            getBrand(),
                                            getRole(),
                                            getCashierName(),
                                            getOrderId(),
                                          );
                                      setIsDelivery(listBranch[i].isDelivery);
                                      setIsPickup(listBranch[i].isPickup);
                                      setBranch(listBranch[i].branchCode);
                                      if (listBranch[i].isDelivery) {
                                        setIsCustomerDelivery(true);
                                      } else {
                                        setIsCustomerDelivery(false);
                                      }
                                      setDistance(listBranch[i].distance);
                                      Navigator.pushReplacement(
                                        context,
                                        MaterialPageRoute(
                                            builder: (_) => const NewHome2()),
                                      );
                                    } else {
                                      if (value['status'] == 'error' &&
                                          value['code'] ==
                                              'SERVICE_OUT_RANGE') {
                                        buttonDialogGlobal(
                                          context,
                                          title,
                                          description,
                                          textOnOk,
                                          textOnCancel,
                                          ontapOkeChange,
                                          onTapCancelChange,
                                          okButtonColor: buttonColor,
                                        );
                                      } else {
                                        EasyLoading.showToast(value['msg']);
                                      }
                                    }
                                  });
                                } else {
                                  setIsDelivery(listBranch[i].isDelivery);
                                  setIsPickup(listBranch[i].isPickup);
                                  setBranch(listBranch[i].branchCode);
                                  context.read<FilterMenuBloc>().catAndMenu(
                                        listBranch[i].branchCode,
                                        getBrand(),
                                        getRole(),
                                        getCashierName(),
                                        getOrderId(),
                                      );

                                  if (listBranch[i].isDelivery) {
                                    setIsCustomerDelivery(true);
                                  } else {
                                    setIsCustomerDelivery(false);
                                  }
                                  Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(
                                        builder: (_) => const NewHome2()),
                                  );
                                }
                              }
                            },
                            child: Container(
                              margin: const EdgeInsets.only(
                                bottom: 8,
                                left: paddingLeftRight,
                                right: paddingLeftRight,
                              ),
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(6),
                                color: backgroundWhite,
                              ),
                              // height: 72,
                              child: Container(
                                padding: const EdgeInsets.only(
                                  left: 16,
                                  right: 12,
                                  bottom: 16,
                                  top: 5,
                                ),
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        mainAxisAlignment:
                                            MainAxisAlignment.center,
                                        children: [
                                          defaultText(
                                            context,
                                            listBranch[i].name,
                                            // maxLines: 1,
                                            // overFlow: TextOverflow.ellipsis,
                                            style: historyOrderStyle(),
                                          ),
                                          const SizedBox(
                                            height: 4,
                                          ),
                                          defaultText(
                                            context,
                                            "${listBranch[i].distance} KM",
                                            style: historyOrderStyle(),
                                          )
                                        ],
                                      ),
                                    ),
                                    Container(
                                      width: 145,
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.end,
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          defaultText(
                                            context,
                                            (listBranch[i].isDelivery)
                                                ? 'Delivery Tersedia'
                                                : 'Delivery Tidak Tersedia',
                                            style: historyOrderStyle(
                                              color: (listBranch[i].isDelivery)
                                                  ? successColor
                                                  : textGreyDeskripsi,
                                            ),
                                          ),
                                          const SizedBox(
                                            height: 15,
                                          ),
                                          defaultText(
                                            context,
                                            (listBranch[i].isPickup)
                                                ? 'Pickup Tersedia'
                                                : 'Pickup Tidak Tersedia',
                                            style: historyOrderStyle(
                                              color: (listBranch[i].isPickup)
                                                  ? successColor
                                                  : textGreyDeskripsi,
                                            ),
                                          ),
                                        ],
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          );
                        }),
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }
}
