import 'dart:developer';

import 'package:easy_localization/easy_localization.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/general_models/widgets_models.dart';
import 'package:mc_common_app/utils/enums.dart';
import 'package:mc_common_app/utils/navigator.dart';
import 'package:mc_common_app/view_models/requests_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/views/location_views/pick_location_page.dart';
import 'package:mc_common_app/widgets/button/show_fill_button.dart';
import 'package:mc_common_app/widgets/common_widgets/app_bar.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 CreateRequestPage extends StatelessWidget {
  const CreateRequestPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: LocaleKeys.createRequest.tr(),
        onBackButtonTapped: () {
          context.read<RequestsVM>().resetRequestCreationForm();
          pop(context);
        },
      ),
      body: PopScope(
        onPopInvokedWithResult: (bool result, dynamic) {
          if (result) {
            context.read<RequestsVM>().resetRequestCreationForm();
          }
        },
        child: Consumer<RequestsVM>(builder: (context, requestsVM, widget) {
          return Column(
            children: [
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      LocaleKeys.requestType.tr().toText(fontSize: 18, isBold: true),
                      8.height,
                      if (requestsVM.isFetchingRequestType) ...[
                        const Center(
                          child: CircularProgressIndicator(),
                        ),
                      ] else ...[
                        if (AppState().getUser.data!.userInfo != null) ...[
                          TxtField(
                            value: "${AppState().getUser.data!.userInfo!.firstName ?? ""} ${AppState().getUser.data!.userInfo!.lastName ?? ""}",
                            isBackgroundEnabled: true,
                            isNeedClickAll: true,
                            hint: '',
                            onTap: () {},
                          ),
                        ],
                        8.height,
                        Builder(builder: (context) {
                          List<DropValue> requestTypeDrop = [];
                          for (var element in requestsVM.myRequestsTypeEnum) {
                            requestTypeDrop.add(DropValue(element.enumValue.toInt() ?? 0, element.enumValueStr ?? "", ""));
                          }
                          return DropdownField(
                            (DropValue value) => requestsVM.updateSelectionRequestTypeId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                            list: requestTypeDrop,
                            dropdownValue: requestsVM.requestTypeId.selectedId != -1 ? DropValue(requestsVM.requestTypeId.selectedId, requestsVM.requestTypeId.selectedOption, "") : null,
                            hint: LocaleKeys.requestType.tr(),
                            errorValue: requestsVM.requestTypeId.errorValue,
                          );
                        }),
                      ],
                      8.height,
                      if (requestsVM.requestTypeId.selectedId != -1)
                        if (requestsVM.isFetchingVehicleType) ...[
                          const Center(
                            child: CircularProgressIndicator(),
                          ),
                        ] else ...[
                          Builder(builder: (context) {
                            List<DropValue> vehicleTypeDrop = [];
                            for (var element in requestsVM.vehicleTypes) {
                              vehicleTypeDrop.add(DropValue(element.id?.toInt() ?? 0, element.vehicleTypeName ?? "", ""));
                            }
                            return DropdownField(
                              (DropValue value) => requestsVM.updateSelectionVehicleTypeId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                              list: vehicleTypeDrop,
                              dropdownValue: requestsVM.vehicleTypeId.selectedId != -1 ? DropValue(requestsVM.vehicleTypeId.selectedId, requestsVM.vehicleTypeId.selectedOption, "") : null,
                              hint: LocaleKeys.vehicleType.tr(),
                              errorValue: requestsVM.vehicleTypeId.errorValue,
                            );
                          }),
                        ],
                      8.height,
                      if (requestsVM.vehicleTypeId.selectedId != -1)
                        if (requestsVM.isFetchingVehicleDetail) ...[
                          const Center(
                            child: CircularProgressIndicator(),
                          ),
                        ] else ...[
                          Column(
                            children: [
                              TxtField(
                                hint: LocaleKeys.brand.tr(),
                                value: requestsVM.brand,
                                onChanged: (e) => requestsVM.updateBrand(e),
                              ),
                              8.height,
                              TxtField(
                                hint: LocaleKeys.model.tr(),
                                value: requestsVM.model,
                                onChanged: (e) => requestsVM.updateModel(e),
                              ),
                              8.height,
                              Builder(builder: (context) {
                                List<DropValue> vehicleYearModelsDrop = [];
                                for (var element in requestsVM.vehicleYears) {
                                  vehicleYearModelsDrop.add(DropValue(element.id?.toInt() ?? 0, element.modelYear ?? "", ""));
                                }

                                return DropdownField(
                                  (DropValue value) => requestsVM.updateSelectionVehicleYearId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                                  list: vehicleYearModelsDrop,
                                  dropdownValue: requestsVM.vehicleYearId.selectedId != -1 ? DropValue(requestsVM.vehicleYearId.selectedId, requestsVM.vehicleYearId.selectedOption, "") : null,
                                  hint: LocaleKeys.year.tr(),
                                  errorValue: requestsVM.vehicleYearId.errorValue,
                                );
                              }),
                              8.height,
                              Builder(
                                builder: (context) {
                                  List<DropValue> vehicleOwnerDrop = [];
                                  for (var element in requestsVM.vehicleConditionsEnum) {
                                    vehicleOwnerDrop.add(DropValue(element.id.toInt(), element.enumValueStr, ""));
                                  }
                                  return DropdownField(
                                    (DropValue value) => requestsVM.updateSelectionVehicleConditionId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                                    list: vehicleOwnerDrop,
                                    dropdownValue:
                                        requestsVM.vehicleConditionId.selectedId != -1 ? DropValue(requestsVM.vehicleConditionId.selectedId, requestsVM.vehicleConditionId.selectedOption, "") : null,
                                    hint: LocaleKeys.condition.tr(),
                                    errorValue: requestsVM.vehicleConditionId.errorValue,
                                  );
                                },
                              ),
                              8.height,
                              Builder(builder: (context) {
                                List<DropValue> vehicleCountriesDrop = [];
                                for (var element in requestsVM.vehicleCountries) {
                                  vehicleCountriesDrop.add(DropValue(element.id?.toInt() ?? 0, element.countryName ?? "", ""));
                                }
                                return DropdownField(
                                  (DropValue value) => requestsVM.updateSelectionVehicleCountryId(SelectionModel(selectedOption: value.value, selectedId: value.id)),
                                  list: vehicleCountriesDrop,
                                  dropdownValue:
                                      requestsVM.vehicleCountryId.selectedId != -1 ? DropValue(requestsVM.vehicleCountryId.selectedId, requestsVM.vehicleCountryId.selectedOption, "") : null,
                                  hint: LocaleKeys.country.tr(),
                                  errorValue: requestsVM.vehicleCountryId.errorValue,
                                );
                              }),
                              if (requestsVM.vehicleCountryId.selectedId != -1) ...[
                                if (requestsVM.isCountryFetching) ...[
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [const CircularProgressIndicator().paddingAll(10)],
                                  ),
                                ] else ...[
                                  8.height,
                                  Builder(builder: (context) {
                                    List<DropValue> vehicleCitiesDrop = [];
                                    for (var element in requestsVM.vehicleCities) {
                                      vehicleCitiesDrop.add(DropValue(element.id?.toInt() ?? 0, element.cityName ?? "", ""));
                                    }
                                    return DropdownField(
                                      (DropValue value) => requestsVM.updateSelectionVehicleCityId(SelectionModel(selectedId: value.id, selectedOption: value.value)),
                                      list: vehicleCitiesDrop,
                                      dropdownValue: requestsVM.vehicleCityId.selectedId != -1 ? DropValue(requestsVM.vehicleCityId.selectedId, requestsVM.vehicleCityId.selectedOption, "") : null,
                                      hint: LocaleKeys.city.tr(),
                                      errorValue: requestsVM.vehicleCityId.errorValue,
                                    );
                                  }),
                                ],
                              ],
                              // 8.height,
                              // TxtField(
                              //   hint: LocaleKeys.price.tr(),
                              //   value: requestsVM.price,
                              //   keyboardType: TextInputType.number,
                              //   onChanged: (e) => requestsVM.updatePrice(e),
                              // ),
                              8.height,
                              TxtField(
                                hint: LocaleKeys.description.tr(),
                                maxLines: 3,
                                value: requestsVM.description,
                                onChanged: (e) => requestsVM.updateDescription(e),
                              ),
                              8.height,

                              // 1 -> SpecialCarRequest
                              // 2 -> ServiceRequest

                              if (requestsVM.requestTypeId.selectedId == 2) ...[
                                TxtField(
                                  hint: LocaleKeys.address.tr(),
                                  isNeedClickAll: false,
                                  value: requestsVM.address,
                                  postfixWidget: IconButton(
                                      icon: const Icon(
                                        size: 28,
                                        Icons.add_location_outlined,
                                      ),
                                      onPressed: () {
                                        navigateTo(
                                          context,
                                          PickLocationPage(
                                            onPickAddress: (double latitude, double longitude, String address) {
                                              requestsVM.address = address;
                                              requestsVM.setState(ViewState.idle);
                                            },
                                          ),
                                        );
                                      }),
                                  onChanged: (e) => requestsVM.updateAddress(e),
                                ),
                                8.height,
                              ],
                              if (requestsVM.pickedVehicleImages.isEmpty) ...[
                                DottedRectContainer(
                                  onTap: () => context.read<RequestsVM>().pickMultipleImages(),
                                  text: LocaleKeys.attachImage.tr(),
                                  icon: MyAssets.attachmentIcon.buildSvg(),
                                ),
                              ],
                              if (requestsVM.vehicleImageError != "") ...[
                                10.height,
                                Row(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  children: [
                                    requestsVM.vehicleImageError.toText(fontSize: 14, color: Colors.red),
                                  ],
                                ).paddingOnly(right: 10)
                              ],
                              if (requestsVM.pickedVehicleImages.isNotEmpty) ...[
                                16.height,
                                PickedFilesContainer(
                                  pickedFiles: requestsVM.pickedVehicleImages,
                                  onCrossPressedPrimary: requestsVM.removeImageFromList,
                                  onAddFilePressed: () {
                                    context.read<RequestsVM>().pickMultipleImages();
                                  },
                                ),
                              ],
                            ],
                          ),
                        ]
                    ],
                  ).toContainer(isShadowEnabled: true, marginAll: 16, paddingAll: 12),
                ),
              ),
              ShowFillButton(
                title: LocaleKeys.createRequest.tr(),
                maxWidth: double.infinity,
                maxHeight: 55,
                margin: const EdgeInsets.all(16),
                onPressed: () async {
                  await context.read<RequestsVM>().onCreateRequestTapped(context);
                },
              )
            ],
          );
        }),
      ),
    );
  }
}
