import 'dart:developer';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.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/enums.dart';
import 'package:mc_common_app/view_models/ad_view_model.dart';
import 'package:mc_common_app/views/advertisement/ad_creation_steps/ad_creation_steps_containers.dart';
import 'package:mc_common_app/views/advertisement/components/picked_images_container_widget.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:easy_localization/easy_localization.dart';

class VehicleDetails extends StatelessWidget {
  const VehicleDetails({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (BuildContext context, AdVM adVM, Widget? child) {
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          LocaleKeys.vehicleDetail.tr().toText(fontSize: 18, isBold: true),
          8.height,
          Builder(
            builder: (context) {
              List<DropValue> vehicleBrandsDrop = [];
              for (var element in adVM.vehicleBrands) {
                vehicleBrandsDrop.add(DropValue(element.id?.toInt() ?? 0, element.vehicleBrandDescription ?? "", ""));
              }
              return DropdownField(
                (DropValue value) => adVM.updateSelectionVehicleBrandId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                list: vehicleBrandsDrop,
                dropdownValue: adVM.vehicleBrandId.selectedId != -1 ? DropValue(adVM.vehicleBrandId.selectedId, adVM.vehicleBrandId.selectedOption, "") : null,
                hint: LocaleKeys.vehicleBrand.tr(),
                errorValue: adVM.vehicleBrandId.errorValue,
              );
            },
          ),
          if (adVM.vehicleBrandId.selectedId != -1) ...[
            if (adVM.isFetchingLists) ...[
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  CircularProgressIndicator(),
                ],
              ).paddingAll(10),
            ] else ...[
              8.height,
              if (AppState().currentAppType == AppType.provider) ...[
                Builder(builder: (context) {
                  List<DropValue> vehicleSellerTypesDrop = [];
                  for (var element in adVM.vehicleSellerTypes) {
                    vehicleSellerTypesDrop.add(DropValue(element.id?.toInt() ?? 0, element.sellerType ?? "", ""));
                  }

                  DropValue? model;
                  if (AppState().userType == UserType.providerDealer) {
                    model = vehicleSellerTypesDrop.firstWhere((element) => element.id == 2);
                  } else {
                    model = vehicleSellerTypesDrop.firstWhere((element) => element.id == 1);
                  }
                  adVM.updateSelectionVehicleSellerTypeId(SelectionModel(selectedId: model.id, selectedOption: model.value), needRefresh: false);

                  return DropdownField(
                    (DropValue value) => adVM.updateSelectionVehicleSellerTypeId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                    isSelectAble: false,
                    list: vehicleSellerTypesDrop,
                    dropdownValue: adVM.vehicleSellerTypeId.selectedId != -1 ? DropValue(adVM.vehicleSellerTypeId.selectedId, adVM.vehicleSellerTypeId.selectedOption, "") : null,
                    hint: LocaleKeys.vehicleSellerType.tr(),
                    errorValue: adVM.vehicleSellerTypeId.errorValue,
                  );
                }),
                8.height,
              ],
              Builder(builder: (context) {
                List<DropValue> vehicleModelsDrop = [];
                for (var element in adVM.vehicleModels) {
                  vehicleModelsDrop.add(DropValue(element.id?.toInt() ?? 0, element.model ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleModelId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleModelsDrop,
                  dropdownValue: adVM.vehicleModelId.selectedId != -1 ? DropValue(adVM.vehicleModelId.selectedId, adVM.vehicleModelId.selectedOption, "") : null,
                  hint: LocaleKeys.vehicleModel.tr(),
                  errorValue: adVM.vehicleModelId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleYearModelsDrop = [];
                for (var element in adVM.vehicleModelYears) {
                  vehicleYearModelsDrop.add(DropValue(element.id?.toInt() ?? 0, element.modelYear ?? "", ""));
                }

                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleModelYearId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleYearModelsDrop,
                  dropdownValue: adVM.vehicleModelYearId.selectedId != -1 ? DropValue(adVM.vehicleModelYearId.selectedId, adVM.vehicleModelYearId.selectedOption, "") : null,
                  hint: LocaleKeys.vehicleModelYear.tr(),
                  errorValue: adVM.vehicleModelYearId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleColorsDrop = [];
                for (var element in adVM.vehicleColors) {
                  vehicleColorsDrop.add(DropValue(element.id?.toInt() ?? 0, element.color ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleColorId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleColorsDrop,
                  hint: LocaleKeys.vehicleColor.tr(),
                  dropdownValue: adVM.vehicleColorId.selectedId != -1 ? DropValue(adVM.vehicleColorId.selectedId, adVM.vehicleColorId.selectedOption, "") : null,
                  errorValue: adVM.vehicleColorId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleConditionsDrop = [];
                for (var element in adVM.vehicleConditions) {
                  vehicleConditionsDrop.add(DropValue(element.id?.toInt() ?? 0, element.condition ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleConditionId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleConditionsDrop,
                  dropdownValue: adVM.vehicleConditionId.selectedId != -1 ? DropValue(adVM.vehicleConditionId.selectedId, adVM.vehicleConditionId.selectedOption, "") : null,
                  hint: LocaleKeys.vehicleCondition.tr(),
                  errorValue: adVM.vehicleConditionId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleCategoriesDrop = [];
                for (var element in adVM.vehicleCategories) {
                  vehicleCategoriesDrop.add(DropValue(element.id?.toInt() ?? 0, element.category ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleCategoryId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleCategoriesDrop,
                  hint: LocaleKeys.vehicleCategory.tr(),
                  dropdownValue: adVM.vehicleCategoryId.selectedId != -1 ? DropValue(adVM.vehicleCategoryId.selectedId, adVM.vehicleCategoryId.selectedOption, "") : null,
                  errorValue: adVM.vehicleCategoryId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleMileageDrop = [];
                for (var element in adVM.vehicleMileages) {
                  vehicleMileageDrop.add(DropValue(element.id?.toInt() ?? 0, "${element.mileageStart ?? ""} - ${element.mileageEnd ?? ""}", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleMileageId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleMileageDrop,
                  dropdownValue: adVM.vehicleMileageId.selectedId != -1 ? DropValue(adVM.vehicleMileageId.selectedId, adVM.vehicleMileageId.selectedOption, "") : null,
                  hint: LocaleKeys.vehicleMileage.tr(),
                  errorValue: adVM.vehicleMileageId.errorValue,
                );
              }),
              8.height,
              Builder(builder: (context) {
                List<DropValue> vehicleTransmissionsDrop = [];
                for (var element in adVM.vehicleTransmissions) {
                  vehicleTransmissionsDrop.add(DropValue(element.id?.toInt() ?? 0, element.transmission ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleTransmissionId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                  list: vehicleTransmissionsDrop,
                  hint: LocaleKeys.vehicleTransmission.tr(),
                  dropdownValue: adVM.vehicleTransmissionId.selectedId != -1 ? DropValue(adVM.vehicleTransmissionId.selectedId, adVM.vehicleTransmissionId.selectedOption, "") : null,
                  errorValue: adVM.vehicleTransmissionId.errorValue,
                );
              }),
              8.height,

              Builder(builder: (context) {
                List<DropValue> vehicleCountriesDrop = [];
                for (var element in adVM.vehicleCountries) {
                  vehicleCountriesDrop.add(DropValue(element.id?.toInt() ?? 0, element.countryName ?? "", ""));
                }
                return DropdownField(
                  (DropValue value) => adVM.updateSelectionVehicleCountryId(SelectionModel(selectedOption: value.value, selectedId: value.id)),
                  list: vehicleCountriesDrop,
                  dropdownValue: adVM.vehicleCountryId.selectedId != -1 ? DropValue(adVM.vehicleCountryId.selectedId, adVM.vehicleCountryId.selectedOption, "") : null,
                  hint: LocaleKeys.vehicleCountry.tr(),
                  errorValue: adVM.vehicleCountryId.errorValue,
                );
              }),
              if (adVM.vehicleCountryId.selectedId != -1) ...[
                if (adVM.isCountryFetching) ...[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [const CircularProgressIndicator().paddingAll(10)],
                  ),
                ] else ...[
                  8.height,
                  Builder(builder: (context) {
                    List<DropValue> vehicleCitiesDrop = [];
                    for (var element in adVM.vehicleCities) {
                      vehicleCitiesDrop.add(DropValue(element.id?.toInt() ?? 0, element.cityName ?? "", ""));
                    }
                    return DropdownField(
                      (DropValue value) => adVM.updateSelectionVehicleCityId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                      list: vehicleCitiesDrop,
                      dropdownValue: adVM.vehicleCityId.selectedId != -1 ? DropValue(adVM.vehicleCityId.selectedId, adVM.vehicleCityId.selectedOption, "") : null,
                      hint: LocaleKeys.vehicleCity.tr(),
                      errorValue: adVM.vehicleCityId.errorValue,
                    );
                  }),
                ],
              ],
              8.height,
              TxtField(
                value: adVM.vehicleDemandAmount,
                errorValue: adVM.demandAmountError,
                keyboardType: TextInputType.number,
                numbersOnly: true,
                hint: LocaleKeys.demandAmount.tr(),
                onChanged: (v) => adVM.updateVehicleDemandAmount(v),
              ),
              8.height,
              TxtField(
                value: adVM.vehicleVin,
                errorValue: adVM.vehicleVinError,
                keyboardType: TextInputType.number,
                hint: LocaleKeys.vehicleVIN.tr(),
                onChanged: (v) => adVM.updateVehicleVin(v),
              ),
              8.height,
              TxtField(
                value: adVM.vehicleTitle,
                errorValue: adVM.vehicleTitleError,
                hint: LocaleKeys.vehicleTitle.tr(),
                onChanged: (v) => adVM.updateVehicleTitle(v),
              ),
              8.height,
              TxtField(
                value: adVM.warrantyDuration,
                errorValue: adVM.warrantyError,
                keyboardType: TextInputType.number,
                hint: LocaleKeys.warrantyAvailableYears.tr(),
                numbersOnly: true,
                allowOnlyOneDigit: true,
                onChanged: (v) => adVM.updateVehicleWarrantyDuration(v),
              ),
              8.height,
              TxtField(
                value: adVM.vehicleDescription,
                hint: LocaleKeys.vehicleDescription.tr(),
                maxLines: 5,
                errorValue: adVM.vehicleDescError,
                onChanged: (v) => adVM.updateVehicleDescription(v),
              ),
              22.height,
              LocaleKeys.financeAvailable.tr().toText(fontSize: 16),
              8.height,
              Container(
                width: 50,
                height: 30,
                decoration: BoxDecoration(
                  color: adVM.financeAvailableStatus ? MyColors.darkPrimaryColor : MyColors.white,
                  borderRadius: BorderRadius.circular(25.0),
                  border: Border.all(color: MyColors.black, width: 1),
                ),
                child: Transform.scale(
                  scale: 0.8,
                  child: CupertinoSwitch(
                    activeColor: MyColors.darkPrimaryColor,
                    trackColor: MyColors.white,
                    thumbColor: MyColors.grey98Color,
                    value: adVM.financeAvailableStatus,
                    onChanged: (value) {
                      adVM.updateFinanceAvailableStatus(value);
                    },
                  ),
                ),
              ),
              28.height,
              LocaleKeys.vehiclePictures.tr().toText(fontSize: 18, isBold: true),
              8.height,
              if (adVM.pickedPostingImages.isEmpty) ...[
                DottedRectContainer(
                  onTap: () => context.read<AdVM>().pickMultipleImages(),
                  text: LocaleKeys.attachImage.tr(),
                  icon: MyAssets.attachmentIcon.buildSvg(),
                ),
              ],
              if (adVM.vehicleImageError != "") ...[
                10.height,
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    adVM.vehicleImageError.toText(fontSize: 14, color: Colors.red),
                  ],
                ).paddingOnly(right: 10)
              ],
              if (adVM.pickedPostingImages.isNotEmpty) ...[
                8.height,
                PickedFilesContainer(
                  pickedFiles: adVM.pickedPostingImages,
                  onCrossPressedPrimary: adVM.removeImageFromList,
                  onAddFilePressed: () {
                    context.read<AdVM>().pickMultipleImages();
                  },
                ),
              ],
              // if (adVM.isAdEditEnabled) ...[
              //   if (adVM.previousAdDetails!.vehicle!.image!.isNotEmpty) ...[
              //     16.height,
              //     "Old Images".toText(fontSize: 16),
              //     NetworkFilesContainerForVehiclePosting(
              //       networkFilesForVehiclePosting: adVM.vehicleOldImagesList,
              //       onCrossPressedPrimary: adVM.removeVehicleOldImagesList,
              //       onAddFilePressed: () => context.read<AdVM>().pickMultipleImages(),
              //     ),
              //   ],
              // ],
              15.height,
            ],
          ]
        ],
      ).toWhiteContainer(width: double.infinity, allPading: 12, margin: const EdgeInsets.symmetric(horizontal: 21, vertical: 10));
    });
  }
}
