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/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/dashboard_view_model_customer.dart';
import 'package:mc_common_app/views/advertisement/custom_add_button.dart';
import 'package:mc_common_app/widgets/extensions/extensions_widget.dart';
import 'package:provider/provider.dart';

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

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

  Widget getCarouselSliderWidget(AppType appType, AppointmentsVM appointmentsVM) {
    return CarouselSlider.builder(
      options: CarouselOptions(
        height: appType == AppType.provider ? 110 : 140,
        viewportFraction: 1.0,
        enlargeCenterPage: false,
        enableInfiniteScroll: false,
      ),
      itemCount: appointmentsVM.myUpComingAppointments.length,
      itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) => BuildAppointmentContainerForCustomer(
        isForHome: appType == AppType.provider,
        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: 21));
          } else {
            return getCarouselSliderWidget(AppState().currentAppType, model);
          }
        }
      }
    });
  }

// if (myUpComingAppointments.isEmpty) {
//   if (isNeedToShowEmptyMessage)
//     return "No Upcoming Appointment Available".toText().paddingAll(21);
//   return CustomAddButton(
//     needsBorder: true,
//     bgColor: MyColors.white,
//     onTap: () => context.read<DashboardVmCustomer>().onNavbarTapped(0),
//     text: "Add New Appointment",
//     icon: Container(
//       height: 24,
//       width: 24,
//       decoration: const BoxDecoration(
//           shape: BoxShape.circle, color: MyColors.darkTextColor),
//       child: const Icon(Icons.add, color: MyColors.white),
//     ),
//   ).padding(EdgeInsets.symmetric(vertical: 10, horizontal: 21));
//   return Container(
//     height: 86,
//     child: Row(
//       mainAxisAlignment: MainAxisAlignment.center,
//       children: [
//         Container(
//           height: 24,
//           width: 24,
//           decoration: BoxDecoration(
//               shape: BoxShape.circle, color: MyColors.darkTextColor),
//           child: Icon(
//             Icons.add,
//             color: MyColors.white,
//           ),
//         ),
//         SizedBox(width: 10),
//         "Add New Appointment".toText(
//           fontSize: 15,
//           isBold: true,
//           color: MyColors.lightTextColor,
//         ),
//       ],
//     ),
//   ).onPress(() {}).toWhiteContainer(
//       width: double.infinity,
//       margin: EdgeInsets.symmetric(horizontal: 21, vertical: 10));
// }
// return CarouselSlider.builder(
//   options: CarouselOptions(
//     height: 140,
//     viewportFraction: 1.0,
//     enlargeCenterPage: false,
//     enableInfiniteScroll: false,
//   ),
//   itemCount: myUpComingAppointments.length,
//   itemBuilder: (BuildContext context, int itemIndex, int pageViewIndex) => BuildAppointmentContainerForCustomer(
//     isForHome: true,
//     appointmentListModel: myUpComingAppointments[itemIndex],
//     onTapped: isNeedToShowEmptyMessage ? onAppointmentClick! : () => navigateWithName(context, AppRoutes.appointmentDetailView, arguments: myUpComingAppointments[itemIndex]),
//   ),
// );
}

class BuildAppointmentContainerForCustomer extends StatelessWidget {
  final bool? isForHome;
  final AppointmentListModel? appointmentListModel;
  final Function()? onTapped;

  const BuildAppointmentContainerForCustomer({Key? key, this.isForHome = false, this.onTapped, required this.appointmentListModel}) : super(key: key);

  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,
            isBold: true,
            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 Container(
      margin: const EdgeInsets.only(bottom: 10, left: 21, right: 21),
      child: Column(
        children: [
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              isForHome != null && isForHome!
                  ? Image.asset(
                      MyAssets.bnCar,
                      width: 56,
                      height: 56,
                      fit: BoxFit.fill,
                    ).toCircle(borderRadius: 100)
                  : Image.asset(
                      MyAssets.bnCar,
                      width: 80,
                      height: 85,
                      fit: BoxFit.cover,
                    ),
              8.width,
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    (AppState().currentAppType == AppType.provider ? appointmentListModel!.customerName ?? "" : appointmentListModel!.branchName ?? "")
                        .toText(color: MyColors.black, isBold: true, fontSize: 16),
                    Row(
                      children: [
                        MyAssets.miniClock.buildSvg(height: 12),
                        2.width,
                        "${appointmentListModel!.duration ?? ""}  ${appointmentListModel!.appointmentDate!.toFormattedDateWithoutTime()}".toText(
                          color: MyColors.lightTextColor,
                          fontSize: 12,
                        ),
                      ],
                    ),
                    9.height,
                    isForHome != null && isForHome!
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              "Appointment Details".toText(
                                color: MyColors.primaryColor,
                                isUnderLine: true,
                                isBold: true,
                                fontSize: 14,
                              ),
                              const Icon(Icons.arrow_forward),
                            ],
                          )
                        : Row(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              Expanded(
                                child: Column(
                                  children: buildServicesFromAppointment(appointmentListModel: appointmentListModel!),
                                ),
                              ),
                              const Icon(
                                Icons.arrow_forward,
                              ),
                            ],
                          ),
                  ],
                ),
              ),
            ],
          ),
        ],
      ).onPress(onTapped!).toWhiteContainer(width: double.infinity, allPading: 12),
    );
  }
}
