import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/dependencies.dart';
import 'package:hmg_patient_app_new/core/utils/loading_utils.dart';
import 'package:hmg_patient_app_new/core/utils/size_utils.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/string_extensions.dart';
import 'package:hmg_patient_app_new/extensions/widget_extensions.dart';
import 'package:hmg_patient_app_new/features/authentication/authentication_view_model.dart';
import 'package:hmg_patient_app_new/features/book_appointments/book_appointments_view_model.dart';
import 'package:hmg_patient_app_new/features/my_appointments/my_appointments_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/home/navigation_screen.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';
import 'package:hmg_patient_app_new/widgets/buttons/custom_button.dart';
import 'package:hmg_patient_app_new/widgets/chip/app_custom_chip_widget.dart';
import 'package:hmg_patient_app_new/widgets/routes/custom_page_route.dart';
import 'package:provider/provider.dart';

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

  @override
  State<ReviewAppointmentPage> createState() => _ReviewAppointmentPageState();
}

class _ReviewAppointmentPageState extends State<ReviewAppointmentPage> {
  late AppState appState;
  late BookAppointmentsViewModel bookAppointmentsViewModel;
  late AuthenticationViewModel authVM;
  late MyAppointmentsViewModel myAppointmentsViewModel;

  @override
  Widget build(BuildContext context) {
    bookAppointmentsViewModel = Provider.of<BookAppointmentsViewModel>(context, listen: false);
    myAppointmentsViewModel = Provider.of<MyAppointmentsViewModel>(context, listen: false);
    authVM = Provider.of<AuthenticationViewModel>(context, listen: false);
    appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.scaffoldBgColor,
      body: Column(
        children: [
          Expanded(
            child: CollapsingListView(
              title: LocaleKeys.reviewAppointment.tr(context: context),
              child: SingleChildScrollView(
                padding: EdgeInsets.symmetric(horizontal: 24.h),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 24.h),
                    LocaleKeys.docInfo.tr(context: context).toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 24.h,
                        hasShadow: false,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Image.network(
                                  bookAppointmentsViewModel.selectedDoctor.doctorImageURL!,
                                  width: 50.h,
                                  height: 50.h,
                                  fit: BoxFit.cover,
                                ).circle(100),
                                SizedBox(width: 8.h),
                                Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Row(
                                      children: [
                                        SizedBox(
                                          width: MediaQuery.of(context).size.width * 0.49,
                                          child:
                                              "${bookAppointmentsViewModel.selectedDoctor.doctorTitle} ${bookAppointmentsViewModel.selectedDoctor.name}".toString().toText16(isBold: true, maxlines: 1),
                                        ),
                                        Image.network(
                                          bookAppointmentsViewModel.selectedDoctor.nationalityFlagURL!,
                                          width: 20.h,
                                          height: 15.h,
                                          fit: BoxFit.cover,
                                        ),
                                      ],
                                    ),
                                    SizedBox(height: 2.h),
                                    (bookAppointmentsViewModel.selectedDoctor.speciality!.isNotEmpty ? bookAppointmentsViewModel.selectedDoctor.speciality!.first : "")
                                        .toString()
                                        .toText12(fontWeight: FontWeight.w500, color: AppColors.greyTextColor, maxLine: 1),
                                  ],
                                ),
                              ],
                            ),
                            SizedBox(height: 12.h),
                            Wrap(
                              direction: Axis.horizontal,
                              spacing: 8.h,
                              runSpacing: 8.h,
                              children: [
                                AppCustomChipWidget(
                                  labelText: "${LocaleKeys.clinic.tr(context: context)}: ${bookAppointmentsViewModel.selectedDoctor.clinicName}".needTranslation,
                                ),
                                AppCustomChipWidget(
                                  labelText: "${LocaleKeys.branch.tr(context: context)} ${bookAppointmentsViewModel.selectedDoctor.projectName}".needTranslation,
                                ),
                                AppCustomChipWidget(
                                  labelText: "${LocaleKeys.date.tr(context: context)}: ${bookAppointmentsViewModel.selectedAppointmentDate}".needTranslation,
                                ),
                                AppCustomChipWidget(
                                  labelText: "${LocaleKeys.time.tr(context: context)}: ${bookAppointmentsViewModel.selectedAppointmentTime}".needTranslation,
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                    LocaleKeys.patientInfo.tr(context: context).toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 24.h,
                        hasShadow: false,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Row(
                          children: [
                            Image.asset(
                              appState.getAuthenticatedUser()?.gender == 1 ? AppAssets.male_img : AppAssets.femaleImg,
                              width: 52.h,
                              height: 52.h,
                            ),
                            SizedBox(width: 8.h),
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                "${appState.getAuthenticatedUser()!.firstName} ${appState.getAuthenticatedUser()!.lastName}".toText16(isBold: true),
                                SizedBox(height: 8.h),
                                AppCustomChipWidget(labelText: "${appState.getAuthenticatedUser()!.age} Years Old"),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    SizedBox(height: 24.h),
                    "Hospital Information".needTranslation.toText16(isBold: true),
                    SizedBox(height: 16.h),
                    Container(
                      decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                        color: AppColors.whiteColor,
                        borderRadius: 12.h,
                        hasShadow: false,
                      ),
                      child: Padding(
                        padding: EdgeInsets.all(16.h),
                        child: Row(
                          children: [
                            bookAppointmentsViewModel.selectedDoctor.projectName!.toText16(isBold: true),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
              color: AppColors.whiteColor,
              borderRadius: 24.h,
              hasShadow: true,
            ),
            child: CustomButton(
              text: LocaleKeys.bookAppo.tr(context: context),
              onPressed: () async {
                initiateBookAppointment();
              },
              backgroundColor: AppColors.primaryRedColor,
              borderColor: AppColors.primaryRedColor,
              textColor: AppColors.whiteColor,
              fontSize: 16,
              fontWeight: FontWeight.w500,
              borderRadius: 12,
              padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
              height: 50.h,
            ).paddingSymmetrical(24.h, 24.h),
          ),
        ],
      ),
    );
  }

  void initiateBookAppointment() async {
    LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: false, loadingText: "Booking your appointment...".needTranslation);
    myAppointmentsViewModel.setIsAppointmentDataToBeLoaded(true);

    if (bookAppointmentsViewModel.isLiveCareSchedule) {
      await bookAppointmentsViewModel.insertSpecificAppointmentForLiveCare(onError: (err) {
        print(err.data["ErrorEndUserMessage"]);
        LoadingUtils.hideFullScreenLoader();
      }, onSuccess: (apiResp) async {
        LoadingUtils.hideFullScreenLoader();
        await Future.delayed(Duration(milliseconds: 50)).then((value) async {
          LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: true, loadingText: LocaleKeys.appointmentSuccess.tr());
          await Future.delayed(Duration(milliseconds: 4000)).then((value) {
            LoadingUtils.hideFullScreenLoader();
            bookAppointmentsViewModel.setIsLiveCareSchedule(false);
            Navigator.pushAndRemoveUntil(
                context,
                CustomPageRoute(
                  page: LandingNavigation(),
                ),
                (r) => false);
          });
        });
      });
    } else {
      //TODO: Add patient Derma package check API Here
      await bookAppointmentsViewModel.insertSpecificAppointment(onError: (err) {
        print(err.data["ErrorEndUserMessage"]);
        LoadingUtils.hideFullScreenLoader();
      }, onSuccess: (apiResp) async {
        LoadingUtils.hideFullScreenLoader();
        await Future.delayed(Duration(milliseconds: 50)).then((value) async {
          LoadingUtils.showFullScreenLoader(barrierDismissible: true, isSuccessDialog: true, loadingText: LocaleKeys.appointmentSuccess.tr());
          await Future.delayed(Duration(milliseconds: 4000)).then((value) {
            LoadingUtils.hideFullScreenLoader();
            bookAppointmentsViewModel.setIsLiveCareSchedule(false);
            Navigator.pushAndRemoveUntil(
                context,
                CustomPageRoute(
                  page: LandingNavigation(),
                ),
                (r) => false);
          });
        });
      });
    }
  }
}
