import 'dart:developer';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/config/dependency_injection.dart';
import 'package:mc_common_app/config/routes.dart';
import 'package:mc_common_app/extensions/int_extensions.dart';
import 'package:mc_common_app/extensions/string_extensions.dart';
import 'package:mc_common_app/generated/locale_keys.g.dart';
import 'package:mc_common_app/models/general_models/widgets_models.dart';
import 'package:mc_common_app/models/services_models/service_model.dart';
import 'package:mc_common_app/services/common_services.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/appointments_view_model.dart';
import 'package:mc_common_app/views/location_views/pick_location_page.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/dropdown/dropdow_field.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:mc_common_app/widgets/txt_field.dart';
import 'package:provider/provider.dart';

class AppointmentServicePickBottomSheet extends StatelessWidget {
  const AppointmentServicePickBottomSheet({super.key});

  @override
  Widget build(BuildContext context) {
    AppointmentsVM appointmentsVM = context.watch<AppointmentsVM>();
    return SizedBox(
        height: MediaQuery.of(context).size.height * 0.85,
        child: Column(
          children: [
            Container(
              margin: const EdgeInsets.all(8),
              height: 8,
              width: 60,
              decoration: const BoxDecoration(color: MyColors.lightTextColor, borderRadius: BorderRadius.all(Radius.circular(20))),
            ),
            12.height,
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                LocaleKeys.selectCategory.tr().toText(fontSize: 24, isBold: true),
              ],
            ),
            30.height,
            Expanded(
              child: ListView(
                children: [
                  Builder(
                    builder: (context) {
                      return DropdownField(
                        (DropValue value) => appointmentsVM.updateProviderCategoryId(SelectionModel(selectedId: value.id, selectedOption: value.value, itemPrice: value.subValue)),
                        list: appointmentsVM.branchCategories,
                        hint: LocaleKeys.selectCategory.tr(),
                        dropdownValue: appointmentsVM.branchSelectedCategoryId.selectedId != -1
                            ? DropValue(appointmentsVM.branchSelectedCategoryId.selectedId, appointmentsVM.branchSelectedCategoryId.selectedOption, "")
                            : null,
                      );
                    },
                  ),
                  if (appointmentsVM.isFetchingServices) ...[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [const CircularProgressIndicator().paddingAll(10)],
                    ),
                  ] else if (appointmentsVM.branchServices.isNotEmpty) ...[
                    8.height,
                    Builder(
                      builder: (context) {
                        List<DropValue> serviceCategories = [];
                        for (var element in appointmentsVM.branchServices) {
                          if (element.categoryId == appointmentsVM.branchSelectedCategoryId.selectedId) {
                            serviceCategories.add(DropValue(
                              element.serviceProviderServiceId ?? 0,
                              element.serviceDescription!,
                              "",
                            ));
                          }
                        }

                        return DropdownField(
                          (DropValue value) => appointmentsVM.updateBranchServiceId(SelectionModel(selectedId: value.id, selectedOption: value.value, itemPrice: value.subValue)),
                          list: serviceCategories,
                          hint: LocaleKeys.selectService.tr(),
                          dropdownValue: appointmentsVM.branchSelectedServiceId.selectedId != -1
                              ? DropValue(appointmentsVM.branchSelectedServiceId.selectedId, appointmentsVM.branchSelectedServiceId.selectedOption, "")
                              : null,
                        );
                      },
                    ),
                  ],
                  if (appointmentsVM.branchSelectedServiceId.selectedId != -1 && !appointmentsVM.isFetchingServices) ...[
                    16.height,
                    Row(children: [LocaleKeys.selectServiceLocation.tr().toText(fontSize: 16, isBold: true, color: MyColors.black)]),
                    8.height,
                    Row(
                      children: [
                        Expanded(
                          child: ShowFillButton(
                            borderColor: !(appointmentsVM.currentServiceSelection != null && (appointmentsVM.currentServiceSelection!.isAllowAppointmentHome ?? false))
                                ? Colors.transparent
                                : MyColors.darkPrimaryColor,
                            isDisabled: !(appointmentsVM.currentServiceSelection != null && (appointmentsVM.currentServiceSelection!.isAllowAppointmentHome ?? false)),
                            isFilled: appointmentsVM.isHomeTapped,
                            maxHeight: 48,
                            title: LocaleKeys.home.tr(),
                            txtColor: appointmentsVM.isHomeTapped ? MyColors.white : MyColors.darkTextColor,
                            onPressed: () {
                              if (appointmentsVM.currentServiceSelection != null && (appointmentsVM.currentServiceSelection!.isAllowAppointmentHome ?? false)) {
                                appointmentsVM.updateIsHomeTapped(true);
                              } else {
                                Utils.showToast(LocaleKeys.serviceNotAvailableAtHomeLocation.tr());
                              }
                            },
                          ),
                        ),
                        12.width,
                        Expanded(
                          child: ShowFillButton(
                            isFilled: !appointmentsVM.isHomeTapped,
                            txtColor: !appointmentsVM.isHomeTapped ? MyColors.white : MyColors.darkTextColor,
                            maxHeight: 48,
                            title: LocaleKeys.workshop.tr(),
                            onPressed: () => appointmentsVM.updateIsHomeTapped(false),
                          ),
                        ),
                      ],
                    ),
                    if (appointmentsVM.isHomeTapped) ...[
                      12.height,
                      TxtField(
                        hint: LocaleKeys.pickLocation.tr(),
                        errorValue: appointmentsVM.pickHomeLocationError,
                        value: appointmentsVM.currentLocationInfoModel == null ? "" : appointmentsVM.currentLocationInfoModel!.address,
                        isNeedClickAll: true,
                        postfixData: Icons.add_location_outlined,
                        postFixDataColor: MyColors.darkPrimaryColor,
                        onTap: () {
                          navigateTo(
                            context,
                            PickLocationPage(
                              onPickAddress: (double latitude, double longitude, String address) async {
                                appointmentsVM.setState(ViewState.idle);

                                double distance = injector.get<CommonAppServices>().getDistanceBetween(
                                      curLatitude: double.parse(appointmentsVM.selectedBranchModel!.latitude!),
                                      curLongitude: double.parse(appointmentsVM.selectedBranchModel!.longitude!),
                                      destLatitude: latitude,
                                      destLongitude: longitude,
                                    );
                                log("distance: $distance");
                                log("customerLocationRange : ${appointmentsVM.currentServiceSelection!.customerLocationRange}");

                                if (distance > (appointmentsVM.currentServiceSelection!.customerLocationRange ?? 0)) {
                                  Utils.showToast(LocaleKeys.serviceNotProvided.tr());
                                  appointmentsVM.currentServiceSelection!.servicelocationInfo = CurrentLocationInfoModel(
                                    address: '',
                                    latitude: 0.0,
                                    longitude: 0.0,
                                    distanceToBranch: 0.0,
                                    homeChargesInCurrentService: 0.0,
                                  );
                                  appointmentsVM.updateCurrentLocationInfoModel(null);
                                  return;
                                }

                                CurrentLocationInfoModel temp = CurrentLocationInfoModel(
                                  address: address,
                                  latitude: latitude,
                                  longitude: longitude,
                                  distanceToBranch: distance,
                                  homeChargesInCurrentService: double.parse(appointmentsVM.currentServiceSelection!.rangePricePerKm ?? "0.0"),
                                );

                                log("appointmentsVM.currentServiceSelection!.rangePricePerKm : ${temp.toString()}");
                                appointmentsVM.updateCurrentLocationInfoModel(temp);
                              },
                            ),
                          );
                        },
                      ),
                      14.height,
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          const Icon(Icons.warning, color: MyColors.adPendingStatusColor, size: 19).paddingOnly(bottom: 2),
                          3.width,
                          Flexible(child: LocaleKeys.pickedLocationNotice.tr().toText(color: MyColors.adPendingStatusColor, fontSize: 12, isItalic: true)),
                        ],
                      ),
                    ]
                  ],
                ],
              ),
            ),
            SizedBox(
              width: double.infinity,
              child: Column(
                children: [
                  if (appointmentsVM.isHomeTapped &&
                      !appointmentsVM.isFetchingServices &&
                      appointmentsVM.currentServiceSelection != null &&
                      (appointmentsVM.currentServiceSelection!.isAllowAppointmentHome ?? false)) ...[
                    const Divider(thickness: 1, height: 1),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        if (appointmentsVM.currentLocationInfoModel == null) ...[
                          appointmentsVM.currentServiceSelection!.rangePricePerKm.toString().toText(fontSize: 30, isBold: true),
                          "${LocaleKeys.sar.tr()}/km".toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5),
                        ] else ...[
                          (appointmentsVM.currentServiceSelection!.servicelocationInfo.homeChargesInCurrentService * appointmentsVM.currentServiceSelection!.servicelocationInfo.distanceToBranch)
                              .toStringAsFixed(2)
                              .toText(
                                fontSize: 30,
                                isBold: true,
                              ),
                          LocaleKeys.sar.tr().toText(fontSize: 15, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 5),
                          10.width,
                          ("(${(appointmentsVM.currentServiceSelection!.servicelocationInfo.homeChargesInCurrentService).toStringAsFixed(2)} ${LocaleKeys.sar.tr()} x  ${appointmentsVM.currentServiceSelection!.servicelocationInfo.distanceToBranch.toStringAsFixed(2)} KMs )")
                              .toText(fontSize: 13, color: MyColors.lightTextColor)
                              .paddingOnly(bottom: 5),
                        ],
                      ],
                    ),
                    LocaleKeys.additionalChargesNotice.tr().toText(fontSize: 12, color: MyColors.lightTextColor),
                    22.height,
                  ],
                  SizedBox(
                    width: double.infinity,
                    child: ShowFillButton(
                      maxHeight: 55,
                      backgroundColor: !appointmentsVM.isServiceSelectionValidated() ? MyColors.lightTextColor.withOpacity(0.6) : MyColors.darkPrimaryColor,
                      title: LocaleKeys.next.tr(),
                      onPressed: () {
                        bool isValidated = appointmentsVM.isServiceSelectionValidated();
                        if (isValidated) {
                          appointmentsVM.getServiceItems(serviceId: appointmentsVM.branchSelectedServiceId.selectedId);
                          Navigator.pop(context);
                          navigateWithName(context, AppRoutes.bookAppointmentsItemView);
                        }
                      },
                    ),
                  ),
                ],
              ),
            ).paddingOnly(bottom: 20)
          ],
        )).horPaddingMain();
  }
}
