import 'package:carousel_slider/carousel_slider.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:mc_common_app/classes/app_state.dart';
import 'package:mc_common_app/classes/consts.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/main.dart';
import 'package:mc_common_app/models/appointments_models/appointment_list_model.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/view_models/appointments_view_model.dart';
import 'package:mc_common_app/view_models/base_view_model.dart';
import 'package:mc_common_app/view_models/dashboard_view_model_customer.dart';
import 'package:mc_common_app/widgets/common_widgets/custom_add_button_widget.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:mc_common_app/widgets/row_with_arrow.dart';
import 'package:provider/provider.dart';
import 'package:signalr_core/signalr_core.dart';
import 'package:sizer/sizer.dart';

class CommonAppointmentSliderWidget extends StatelessWidget {
  final Function(AppointmentListModel)? onAppointmentClick;

  const CommonAppointmentSliderWidget({super.key, this.onAppointmentClick});

  Widget getCarouselSliderWidget(AppType appType, AppointmentsVM appointmentsVM) {
    return CarouselSlider.builder(
      options: CarouselOptions(
        height: appType == AppType.provider ? 121 : 96,
        // TODO LATER FIX THIS HEIGHT
        viewportFraction: 1,
        pageSnapping: true,
        enlargeCenterPage: false,
        enableInfiniteScroll: false,
      ),
      itemCount: appointmentsVM.myUpComingAppointments.length,
      itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) => AppointmentHomeTileWidget(
        isForProvider: appType == AppType.provider,
        isForCustomerHome: true,
        appointmentListModel: appointmentsVM.myUpComingAppointments[itemIndex],
        onTapped: () {
          if (appType == AppType.provider) {
            onAppointmentClick!(appointmentsVM.myUpComingAppointments[itemIndex]);
          } else {
            navigateWithName(context, AppRoutes.appointmentDetailView, arguments: appointmentsVM.myUpComingAppointments[itemIndex]);
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (BuildContext context, AppointmentsVM model, Widget? child) {
      if (model.state == ViewState.busy) {
        return const Center(child: CircularProgressIndicator());
      } else {
        if (AppState().currentAppType == AppType.provider) {
          if (model.myUpComingAppointments.isEmpty) {
            return LocaleKeys.noUpcomingAppointments.tr().toText(fontSize: 16, color: MyColors.lightTextColor).paddingAll(21);
          } else {
            return getCarouselSliderWidget(AppState().currentAppType, model);
          }
        } else {
          if (model.myUpComingAppointments.isEmpty) {
            return CustomAddButton(
              needsBorder: true,
              bgColor: MyColors.white,
              onTap: () => context.read<DashboardVmCustomer>().onNavbarTapped(0),
              text: LocaleKeys.addNewAppointment.tr(),
              icon: Container(
                height: 24,
                width: 24,
                decoration: const BoxDecoration(shape: BoxShape.circle, color: MyColors.darkTextColor),
                child: const Icon(Icons.add, color: MyColors.white),
              ),
            ).padding(const EdgeInsets.symmetric(vertical: 10, horizontal: 0));
          } else {
            return getCarouselSliderWidget(AppState().currentAppType, model);
          }
        }
      }
    });
  }
}

class AppointmentHomeTileWidget extends StatelessWidget {
  final bool isForProvider;
  final bool isForCustomerHome;
  final AppointmentListModel? appointmentListModel;
  final Function()? onTapped;

  const AppointmentHomeTileWidget({super.key, this.isForProvider = false, this.onTapped, required this.appointmentListModel, this.isForCustomerHome = false});

  Widget showServices(String title, String icon, {bool isMoreText = false}) {
    return Row(
      children: [
        if (icon != "") ...[
          SvgPicture.asset(icon),
          8.width,
        ],
        Flexible(
          child: title.toText(
            fontSize: 12,
            letterSpacing: -0.48,
            color: isMoreText ? MyColors.primaryColor : MyColors.black,
          ),
        ),
      ],
    );
  }

  List<Widget> buildServicesFromAppointment({required AppointmentListModel appointmentListModel}) {
    if (appointmentListModel.appointmentServicesList == null || appointmentListModel.appointmentServicesList!.isEmpty) {
      return [const SizedBox()];
    }

    if (appointmentListModel.appointmentServicesList!.length == 1) {
      return [
        showServices(
          appointmentListModel.appointmentServicesList![0].providerServiceDescription,
          MyAssets.modificationsIcon,
        )
      ];
    }

    List<Widget> servicesList = List.generate(2, (index) => showServices(appointmentListModel.appointmentServicesList![index].providerServiceDescription, MyAssets.modificationsIcon));

    if (appointmentListModel.appointmentServicesList!.length > 1) {
      servicesList.add(
        showServices("+ ${appointmentListModel.appointmentServicesList!.length - 1}  More", "", isMoreText: true),
      );
    }
    return servicesList;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        isForProvider // need to be updated through backend
            ? const SizedBox()
            : Image.asset(
                MyAssets.bnCar,
                width: isForCustomerHome ? 46 : 70,
                height: isForCustomerHome ? 46 : 90,
                fit: BoxFit.cover,
              ).toCircle(
                borderRadius: isForCustomerHome ? 100 : 0,
              ),
        8.width,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              AppState().currentAppType == AppType.provider
                  ? (appointmentListModel!.branchName ?? "").toText(
                      color: MyColors.greyColor,
                      fontSize: 12,
                      letterSpacing: 0,
                      height: 19 / 12,
                    )
                  : const SizedBox(),
              (AppState().currentAppType == AppType.provider ? appointmentListModel!.customerName ?? "" : appointmentListModel!.branchName ?? "").toText(color: MyColors.black, fontSize: 16, letterSpacing: -0.64, height: 24 / 16),
              Row(
                children: [
                  !isForProvider ? MyAssets.miniClock.buildSvg(height: 12) : const SizedBox(),
                  2.width,
                  "${isForProvider ? "Appt. on:" : ""}  ${appointmentListModel!.duration ?? ""}  ${appointmentListModel!.appointmentDate!.toFormattedDateWithoutTime()}"
                      .toText(color: MyColors.lightTextColor, fontSize: 12, letterSpacing: -0.48, height: 19 / 12),
                ],
              ),
              8.height,
              !isForCustomerHome
                  ? Row(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Expanded(
                          child: Column(
                            children: buildServicesFromAppointment(appointmentListModel: appointmentListModel!),
                          ),
                        ),
                        //ic_arrow_right.svg
                        SvgPicture.asset(
                          MyAssets.arrowRight,
                          height: 9.69,
                          width: 13,
                        ),
                      ],
                    )
                  : Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        LocaleKeys.appointment_details.tr().toText(
                              color: MyColors.primaryColor,
                              isUnderLine: true,
                              fontSize: 14,
                              letterSpacing: -0.56,
                            ),
                        SvgPicture.asset(
                          MyAssets.arrowRight,
                          height: 9.69,
                          width: 13,
                        ),
                      ],
                    )
            ],
          ),
        ),
      ],
    ).onPress(onTapped!).toWhiteContainer(
          width: double.infinity,
          allPading: 12,
        );
  }
}

class AppointmentFragmentTileWidget extends StatelessWidget {
  final AppointmentListModel? appointmentListModel;
  final Function()? onTapped;

  const AppointmentFragmentTileWidget({super.key, this.onTapped, required this.appointmentListModel});

  Widget showServices(String title, String icon, {bool isMoreText = false}) {
    return Row(
      children: [
        if (icon != "") ...[
          SvgPicture.asset(icon),
          8.width,
        ],
        Flexible(
          child: title.toText(
            fontSize: 12,
            letterSpacing: -0.48,
            color: isMoreText ? MyColors.primaryColor : MyColors.black,
          ),
        ),
      ],
    );
  }

  List<Widget> buildServicesFromAppointment({required AppointmentListModel appointmentListModel}) {
    if (appointmentListModel.appointmentServicesList == null || appointmentListModel.appointmentServicesList!.isEmpty) {
      return [const SizedBox()];
    }

    if (appointmentListModel.appointmentServicesList!.length == 1) {
      return [
        showServices(
          appointmentListModel.appointmentServicesList![0].providerServiceDescription,
          MyAssets.modificationsIcon,
        )
      ];
    }

    List<Widget> servicesList = List.generate(1, (index) => showServices(appointmentListModel.appointmentServicesList![index].providerServiceDescription, MyAssets.modificationsIcon));

    if (appointmentListModel.appointmentServicesList!.length > 1) {
      servicesList.add(
        showServices("+ ${appointmentListModel.appointmentServicesList!.length - 1}  More", "", isMoreText: true),
      );
    }
    return servicesList;
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Image.asset(
          MyAssets.bnCar,
          width: 72,
          height: 95,
          fit: BoxFit.cover,
        ),
        8.width,
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              (appointmentListModel!.providerName ?? "").toText(color: MyColors.darkTextColor, fontSize: 16, letterSpacing: -0.64, height: 24 / 16),
              Row(
                children: [
                  ('Branch:').toText(color: MyColors.greyColor, fontSize: 12, letterSpacing: -0.48, height: 18 / 12),
                  2.width,
                  (appointmentListModel!.branchName ?? "").toText(color: MyColors.darkTextColor, fontSize: 12, letterSpacing: -0.48, height: 18 / 12),
                ],
              ),
              Row(
                children: [
                  MyAssets.miniClock.buildSvg(height: 12),
                  2.width,
                  "  ${appointmentListModel!.duration ?? ""}  ${appointmentListModel!.appointmentDate!.toFormattedDateWithoutTime()}".toText(color: MyColors.lightTextColor, fontSize: 12, letterSpacing: -0.48, height: 19 / 12),
                ],
              ),
              5.height,
              Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Expanded(
                    child: Column(
                      children: buildServicesFromAppointment(appointmentListModel: appointmentListModel!),
                    ),
                  ),
                  //ic_arrow_right.svg
                ],
              ).withArrow(isArrowEnabled: true)
            ],
          ),
        ),
      ],
    ).onPress(onTapped!).toWhiteContainer(
          width: double.infinity,
          allPading: 12,
        );
  }
}
