import 'package:flutter/material.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/advertisment_models/vehicle_details_models.dart';
import 'package:mc_common_app/models/general_models/widgets_models.dart';
import 'package:mc_common_app/theme/colors.dart';
import 'package:mc_common_app/utils/utils.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/common_widgets/time_slots.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';
import 'package:sizer/sizer.dart';
import 'package:easy_localization/easy_localization.dart';

class BottomSheetAdDamagePartsContent extends StatefulWidget {
  const BottomSheetAdDamagePartsContent({super.key});

  @override
  State<BottomSheetAdDamagePartsContent> createState() => _BottomSheetAdDamagePartsContentState();
}

class _BottomSheetAdDamagePartsContentState extends State<BottomSheetAdDamagePartsContent> {
  bool checkBoxValue = false;

  @override
  Widget build(BuildContext context) {
    AdVM adVM = context.watch<AdVM>();
    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.damagePartList.tr().toText(fontSize: 24, isBold: true),
            ],
          ),
          8.height,
          TxtField(
            value: adVM.damagePartSearchValue,
            errorValue: "",
            hint: LocaleKeys.searchPart.tr(),
            onChanged: (value) {
              adVM.onSearchChangedForDamagePart(value);
            },
          ),
          8.height,
          Expanded(
            child: ListView.builder(
              shrinkWrap: true,
              itemCount: adVM.vehiclePartsSearchResults.isEmpty ? adVM.vehicleDamageParts.length : adVM.vehiclePartsSearchResults.length,
              itemBuilder: (BuildContext context, int index) {
                VehiclePartModel vehiclePart = adVM.vehiclePartsSearchResults.isEmpty ? adVM.vehicleDamageParts[index] : adVM.vehiclePartsSearchResults[index];

                return Column(
                  children: [
                    // CheckboxListTile(
                    //   value: false,
                    //   visualDensity: VisualDensity.compact,
                    //   contentPadding: EdgeInsets.zero,
                    //   controlAffinity: ListTileControlAffinity.leading,
                    //   title: "Rear Break Light".toText(
                    //     fontSize: 16,
                    //     isBold: true,
                    //   ),
                    //   onChanged: (value) {},
                    // ),
                    InkWell(
                      onTap: () {
                        if (vehiclePart.isSelected!) {
                          return;
                        }
                        adVM.vehicleDamageParts[index].isChecked = !(adVM.vehicleDamageParts[index].isChecked!);
                        setState(() {});
                      },
                      child: Row(
                        children: [
                          SizedBox(
                            height: 40.0,
                            width: 30.0,
                            child: Transform.scale(
                              scale: 1.3,
                              child: Checkbox(
                                value: vehiclePart.isSelected! ? true : vehiclePart.isChecked,
                                activeColor: vehiclePart.isSelected! ? MyColors.lightTextColor : MyColors.primaryColor,
                                onChanged: (value) {
                                  if (vehiclePart.isSelected!) {
                                    return;
                                  }
                                  adVM.vehicleDamageParts[index].isChecked = !(adVM.vehicleDamageParts[index].isChecked!);
                                  setState(() {});
                                },
                              ),
                            ),
                          ),
                          const SizedBox(width: 20),
                          vehiclePart.partName.toString().toText(
                                fontSize: 16,
                                color: vehiclePart.isSelected! ? MyColors.lightTextColor : MyColors.black,
                              )
                        ],
                      ),
                    ),
                    const Divider(thickness: 1),
                  ],
                );
              },
            ),
          ),
          SizedBox(
            width: double.infinity,
            child: ShowFillButton(
              title: LocaleKeys.addDamagePart.tr(),
              onPressed: () {
                for (var value in adVM.vehicleDamageParts) {
                  if (value.isChecked! && !value.isSelected!) {
                    adVM.addNewDamagePartCard(
                      damageCard: VehicleDamageCard(
                        partImageErrorValue: "",
                        partImages: null,
                        damagePartDescription: "",
                        partSelectedId: SelectionModel(selectedOption: value.partName!, selectedId: value.id!, errorValue: ""),
                      ),
                    );
                    value.isChecked = false;
                    value.isSelected = true;
                  }
                }
                Navigator.pop(context);
              },
            ).paddingOnly(bottom: 10),
          ),
        ],
      ),
    ).horPaddingMain();
  }
}

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

  bool isButtonTappable(AdVM adVM) {
    bool status = (adVM.selectedVehicleAdsSpecialServicesId.selectedId != -1) && (adVM.selectedVehicleAdsSpecialServicesId.selectedOption != "");
    if (status) {
      return true;
    }
    return false;
  }

  Widget descriptionCard({required String description}) {
    if (description.isEmpty) {
      return const SizedBox();
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        ("${LocaleKeys.description.tr()}:").toText(fontSize: 14),
        description.toText(color: MyColors.lightTextColor),
      ],
    ).paddingOnly(left: 2);
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(
      builder: (BuildContext context, AdVM adVM, Widget? child) {
        return SizedBox(
          height: MediaQuery.of(context).size.height * 0.7,
          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,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    LocaleKeys.addSpecialService.tr().toText(fontSize: 24, isBold: true),
                    8.height,
                    Builder(
                      builder: (context) {
                        List<DropValue> vehicleAdsSpecialServices = [];
                        for (var element in adVM.vehicleAdsSpecialServices) {
                          if (!element.isSelected!) {
                            vehicleAdsSpecialServices.add(DropValue(element.id?.toInt() ?? 0, element.name ?? "", element.price == null ? "" : element.price!.toInt().toString()));
                          }
                        }
                        return DropdownField(
                          (DropValue value) => adVM.updateSelectedVehicleAdsSpecialServicesId(SelectionModel(selectedId: value.id, selectedOption: value.value, itemPrice: value.subValue)),
                          list: vehicleAdsSpecialServices,
                          hint: LocaleKeys.selectService.tr(),
                          dropdownValue: adVM.selectedVehicleAdsSpecialServicesId.selectedId != -1 ? DropValue(adVM.selectedVehicleAdsSpecialServicesId.selectedId, adVM.selectedVehicleAdsSpecialServicesId.selectedOption, "") : null,
                        );
                      },
                    ),
                    if (adVM.selectedVehicleAdsSpecialServicesId.selectedId != -1) ...[
                      if (adVM.isFetchingLists) ...[
                        Center(child: const CircularProgressIndicator().paddingAll(20)),
                      ] else ...[
                        8.height,
                        if ((adVM.selectedVehicleAdsSpecialServicesId.selectedId == 1 && adVM.ssPhotoScheduleModel != null)) ...[
                          // Builder(
                          //   builder: (context) {
                          //     List<DropValue> vehicleAdsSpecialServiceDates = adVM.populateScheduleDatesForAdPhotoService();
                          //
                          //     return DropdownField(
                          //       (DropValue value) => adVM.updateVehicleVehicleAdsPhotoServiceDate(SelectionModel(
                          //         selectedId: value.id,
                          //         selectedOption: value.value,
                          //       )),
                          //       list: vehicleAdsSpecialServiceDates,
                          //       hint: "Select Date",
                          //       dropdownValue: adVM.vehicleAdsPhotoServiceDate.selectedId != -1
                          //           ? DropValue(
                          //               adVM.vehicleAdsPhotoServiceDate.selectedId,
                          //               adVM.vehicleAdsPhotoServiceDate.selectedOption,
                          //               "",
                          //             )
                          //           : null,
                          //     );
                          //   },
                          // ),
                          // 22.height,
                        ] else if ((adVM.selectedVehicleAdsSpecialServicesId.selectedId == 3 && adVM.ssCarCheckScheduleModel != null)) ...[
                          // Builder(
                          //   builder: (context) {
                          //     List<DropValue> vehicleAdsSpecialServiceDates = adVM.populateScheduleDatesForAdCarCheckService();
                          //
                          //     return DropdownField(
                          //       (DropValue value) => adVM.updateVehicleAdsCarCheckServicesDate(SelectionModel(
                          //         selectedId: value.id,
                          //         selectedOption: value.value,
                          //       )),
                          //       list: vehicleAdsSpecialServiceDates,
                          //       hint: "Select Date",
                          //       dropdownValue: adVM.vehicleAdsCarCheckServicesDate.selectedId != -1
                          //           ? DropValue(
                          //               adVM.vehicleAdsCarCheckServicesDate.selectedId,
                          //               adVM.vehicleAdsCarCheckServicesDate.selectedOption,
                          //               "",
                          //             )
                          //           : null,
                          //     );
                          //   },
                          // ),
                          // 22.height,
                        ],
                        if (adVM.selectedVehicleAdsSpecialServicesId.selectedId != 3 && adVM.selectedVehicleAdsSpecialServicesId.selectedId != 1) ...[
                          descriptionCard(
                            description: adVM.vehicleAdsSpecialServices.firstWhere((element) => element.id == adVM.selectedVehicleAdsSpecialServicesId.selectedId).description ?? "",
                          ),
                        ],
                        if (adVM.adSSTimeSlots.isNotEmpty) ...[
                          LocaleKeys.availableSlots.tr().toText(fontSize: 15, isBold: true),
                          8.height,
                          BuildTimeSlots(
                            timeSlots: adVM.adSSTimeSlots,
                            onPressed: (index) => adVM.updateIsSelectedInSlots(index),
                          ),
                        ],
                        22.height,
                        LocaleKeys.serviceAmount.tr().toText(fontSize: 16, isBold: true, color: MyColors.lightTextColor),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            adVM.selectedVehicleAdsSpecialServicesId.itemPrice.toText(fontSize: 20, isBold: true),
                            SizedBox(width: 1.w),
                            LocaleKeys.sar.tr().toText(fontSize: 12, isBold: true, color: MyColors.lightTextColor).paddingOnly(bottom: 2),
                          ],
                        ),
                      ],
                    ],
                  ],
                ),
              ),
              SizedBox(
                width: double.infinity,
                child: ShowFillButton(
                  backgroundColor: !isButtonTappable(adVM) ? MyColors.lightTextColor.withOpacity(0.6) : MyColors.darkPrimaryColor,
                  title: LocaleKeys.addService.tr(),
                  onPressed: () {
                    if (!isButtonTappable(adVM)) {
                      return;
                    }
                    Navigator.pop(context);

                    adVM.addNewSpecialServiceCard(
                      specialServiceCard: SpecialServiceCard(
                        serviceSelectedId: adVM.selectedVehicleAdsSpecialServicesId,
                        description: adVM.vehicleAdsSpecialServices.firstWhere((element) => element.id == adVM.selectedVehicleAdsSpecialServicesId.selectedId).description ?? "",
                        duration: "",
                        serviceDate: "",
                        serviceDateError: "",
                        serviceTimeError: "",
                        address: "",
                        serviceTime: "",
                      ),
                    );

                    // adVM.addNewSpecialServiceCard(
                    //   specialServiceCard: SpecialServiceCard(
                    //     serviceDate: adVM.vehicleAdsSpecialServicesId.selectedId == 1
                    //         ? adVM.vehicleAdsPhotoServiceDate.selectedOption
                    //         : adVM.vehicleAdsSpecialServicesId.selectedId == 3
                    //             ? adVM.vehicleAdsCarCheckServicesDate.selectedOption
                    //             : "",
                    //     serviceDateError: "",
                    //     serviceSelectedId: adVM.vehicleAdsSpecialServicesId,
                    //     serviceTimeError: "",
                    //     description: adVM.vehicleAdsSpecialServices.firstWhere((element) => element.id == adVM.vehicleAdsSpecialServicesId.selectedId).description ?? "",
                    //     duration: adVM.vehicleAdsSpecialServicesId.selectedId == 1
                    //         ? adVM.ssPhotoScheduleModel!.distanceKM.toString()
                    //         : adVM.vehicleAdsSpecialServicesId.selectedId == 3
                    //             ? adVM.ssCarCheckScheduleModel!.distanceKM.toString()
                    //             : "",
                    //     address: adVM.vehicleAdsSpecialServicesId.selectedId == 1
                    //         ? "${adVM.ssPhotoScheduleModel!.photoOfficeName} - ${adVM.ssPhotoScheduleModel!.areaName}"
                    //         : adVM.vehicleAdsSpecialServicesId.selectedId == 3
                    //             ? adVM.ssCarCheckScheduleModel!.address
                    //             : "",
                    //     serviceTime: adVM.slotSelectedIndex == null || adVM.adSSTimeSlots.isEmpty ? "" : adVM.adSSTimeSlots[adVM.slotSelectedIndex!].slot,
                    //   ),
                    // );
                  },
                ).paddingOnly(bottom: 10),
              ),
            ],
          ).horPaddingMain(),
        );
      },
    );
  }
}
