import 'dart:async';

import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_animations/flutter_staggered_animations.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/date_util.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/prescriptions/prescriptions_view_model.dart';
import 'package:hmg_patient_app_new/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/presentation/lab/lab_result_item_view.dart';
import 'package:hmg_patient_app_new/widgets/appbar/collapsing_list_view.dart';
import 'package:hmg_patient_app_new/presentation/prescriptions/prescription_detail_page.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/routes/custom_page_route.dart';
import 'package:hmg_patient_app_new/widgets/shimmer/movies_shimmer_widget.dart';
import 'package:hmg_patient_app_new/widgets/transitions/fade_page.dart';
import 'package:provider/provider.dart';

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

  @override
  State<PrescriptionsListPage> createState() => _PrescriptionsListPageState();
}

class _PrescriptionsListPageState extends State<PrescriptionsListPage> {
  int? expandedIndex;

  late PrescriptionsViewModel prescriptionsViewModel;

  @override
  void initState() {
    scheduleMicrotask(() {
      prescriptionsViewModel.initPrescriptionsViewModel();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    prescriptionsViewModel = Provider.of<PrescriptionsViewModel>(context, listen: false);
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: CollapsingListView(
        title: LocaleKeys.prescriptions.tr(context: context),
        child: SingleChildScrollView(
          child: Consumer<PrescriptionsViewModel>(builder: (context, model, child) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 16.h),
                // Clinic & Hospital Sort
                Row(
                  children: [
                    CustomButton(
                      text: LocaleKeys.byClinic.tr(context: context),
                      onPressed: () {
                        model.setIsSortByClinic(true);
                      },
                      backgroundColor: model.isSortByClinic ? AppColors.bgRedLightColor : AppColors.whiteColor,
                      borderColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.textColor.withOpacity(0.2),
                      textColor: model.isSortByClinic ? AppColors.primaryRedColor : AppColors.blackColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                      borderRadius: 10,
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      height: 40.h,
                    ),
                    SizedBox(width: 8.h),
                    CustomButton(
                      text: LocaleKeys.byHospital.tr(context: context),
                      onPressed: () {
                        model.setIsSortByClinic(false);
                      },
                      backgroundColor: model.isSortByClinic ? AppColors.whiteColor : AppColors.bgRedLightColor,
                      borderColor: model.isSortByClinic ? AppColors.textColor.withOpacity(0.2) : AppColors.primaryRedColor,
                      textColor: model.isSortByClinic ? AppColors.blackColor : AppColors.primaryRedColor,
                      fontSize: 12,
                      fontWeight: FontWeight.w500,
                      borderRadius: 10,
                      padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                      height: 40.h,
                    ),
                  ],
                ).paddingSymmetrical(24.h, 0.h),
                SizedBox(height: 20.h),
                // Expandable list
                ListView.builder(
                  itemCount: model.isPrescriptionsOrdersLoading
                      ? 4
                      : model.patientPrescriptionOrders.isNotEmpty
                          ? model.patientPrescriptionOrdersViewList.length
                          : 1,
                  physics: NeverScrollableScrollPhysics(),
                  shrinkWrap: true,
                  padding: const EdgeInsets.only(left: 0, right: 8),
                  itemBuilder: (context, index) {
                    final isExpanded = expandedIndex == index;
                    return model.isPrescriptionsOrdersLoading
                        ? LabResultItemView(
                            onTap: () {},
                            labOrder: null,
                            index: index,
                            isLoading: true,
                          )
                        : model.patientPrescriptionOrders.isNotEmpty
                            ? AnimationConfiguration.staggeredList(
                                position: index,
                                duration: const Duration(milliseconds: 500),
                                child: SlideAnimation(
                                  verticalOffset: 100.0,
                                  child: FadeInAnimation(
                                child: AnimatedContainer(
                                  duration: Duration(milliseconds: 300),
                                  curve: Curves.easeInOut,
                                  margin: EdgeInsets.symmetric(vertical: 8.h),
                                  decoration: RoundedRectangleBorder().toSmoothCornerDecoration(color: AppColors.whiteColor, borderRadius: 20.h, hasShadow: true),
                                  child: InkWell(
                                    onTap: () {
                                      setState(() {
                                        expandedIndex = isExpanded ? null : index;
                                      });
                                    },
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Padding(
                                          padding: EdgeInsets.all(16.h),
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Row(
                                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                children: [
                                                  CustomButton(
                                                    text: "${model.patientPrescriptionOrdersViewList[index].prescriptionsList!.length} Prescriptions Available",
                                                    onPressed: () {},
                                                    backgroundColor: AppColors.greyColor,
                                                    borderColor: AppColors.greyColor,
                                                    textColor: AppColors.blackColor,
                                                    fontSize: 10,
                                                    fontWeight: FontWeight.w500,
                                                    borderRadius: 8,
                                                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                    height: 30.h,
                                                  ),
                                                  Icon(isExpanded ? Icons.expand_less : Icons.expand_more),
                                                ],
                                              ),
                                              SizedBox(height: 8.h),
                                              model.patientPrescriptionOrdersViewList[index].filterName!.toText16(isBold: true)
                                            ],
                                          ),
                                        ),
                                        AnimatedSwitcher(
                                          duration: Duration(milliseconds: 500),
                                          switchInCurve: Curves.easeIn,
                                          switchOutCurve: Curves.easeOut,
                                          transitionBuilder: (Widget child, Animation<double> animation) {
                                            return FadeTransition(
                                              opacity: animation,
                                              child: SizeTransition(
                                                sizeFactor: animation,
                                                axisAlignment: 0.0,
                                                child: child,
                                              ),
                                            );
                                          },
                                          child: isExpanded
                                              ? Container(
                                                  key: ValueKey<int>(index),
                                                  padding: EdgeInsets.symmetric(horizontal: 16.h, vertical: 8.h),
                                                  child: Column(
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: [
                                                      ...model.patientPrescriptionOrdersViewList[index].prescriptionsList!.map((prescription) {
                                                        return Column(
                                                          crossAxisAlignment: CrossAxisAlignment.start,
                                                          children: [
                                                            Row(
                                                              mainAxisSize: MainAxisSize.min,
                                                              children: [
                                                                Image.network(
                                                                  prescription.doctorImageURL!,
                                                                  width: 24.h,
                                                                  height: 24.h,
                                                                  fit: BoxFit.fill,
                                                                ).circle(100),
                                                                SizedBox(width: 8.h),
                                                                Expanded(child: prescription.doctorName!.toText14(weight: FontWeight.w500)),
                                                              ],
                                                            ),
                                                            SizedBox(height: 8.h),
                                                            Row(
                                                              children: [
                                                                CustomButton(
                                                                  text: DateUtil.formatDateToDate(DateUtil.convertStringToDate(prescription.appointmentDate), false),
                                                                  onPressed: () {},
                                                                  backgroundColor: AppColors.greyColor,
                                                                  borderColor: AppColors.greyColor,
                                                                  textColor: AppColors.blackColor,
                                                                  fontSize: 10,
                                                                  fontWeight: FontWeight.w500,
                                                                  borderRadius: 8,
                                                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                                  height: 24.h,
                                                                ),
                                                                SizedBox(width: 8.h),
                                                                CustomButton(
                                                                  text: model.isSortByClinic ? prescription.name! : prescription.clinicDescription!,
                                                                  onPressed: () {},
                                                                  backgroundColor: AppColors.greyColor,
                                                                  borderColor: AppColors.greyColor,
                                                                  textColor: AppColors.blackColor,
                                                                  fontSize: 10,
                                                                  fontWeight: FontWeight.w500,
                                                                  borderRadius: 8,
                                                                  padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                                  height: 24.h,
                                                                ),
                                                              ],
                                                            ),
                                                            SizedBox(height: 8.h),
                                                            Row(
                                                              children: [
                                                                Expanded(
                                                                  flex: 6,
                                                                  child: CustomButton(
                                                                    text: prescription.isHomeMedicineDeliverySupported!
                                                                        ? LocaleKeys.resendOrder.tr(context: context)
                                                                        : LocaleKeys.prescriptionDeliveryError.tr(context: context),
                                                                    onPressed: () {},
                                                                    backgroundColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor.withOpacity(0.15) : AppColors.greyF7Color,
                                                                    borderColor: AppColors.successColor.withOpacity(0.01),
                                                                    textColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.35),
                                                                    fontSize: prescription.isHomeMedicineDeliverySupported! ? 14 : 12,
                                                                    fontWeight: FontWeight.w500,
                                                                    borderRadius: 12,
                                                                    padding: EdgeInsets.fromLTRB(10, 0, 10, 0),
                                                                    height: 40.h,
                                                                    icon: AppAssets.prescription_refill_icon,
                                                                    iconColor: prescription.isHomeMedicineDeliverySupported! ? AppColors.successColor : AppColors.textColor.withOpacity(0.35),
                                                                    iconSize: 14.h,
                                                                  ),
                                                                ),
                                                                SizedBox(width: 8.h),
                                                                Expanded(
                                                                  flex: 1,
                                                                  child: Container(
                                                                    height: 40.h,
                                                                    width: 40.h,
                                                                    decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                                                                      color: AppColors.textColor,
                                                                      borderRadius: 10.h,
                                                                    ),
                                                                    child: Padding(
                                                                      padding: EdgeInsets.all(8.h),
                                                                      child: Transform.flip(
                                                                        flipX: appState.isArabic(),
                                                                        child: Utils.buildSvgWithAssets(
                                                                          icon: AppAssets.forward_arrow_icon_small,
                                                                          iconColor: AppColors.whiteColor,
                                                                          width: 10.h,
                                                                          height: 10.h,
                                                                          fit: BoxFit.contain,
                                                                        ),
                                                                      ),
                                                                    ),
                                                                  ).onPress(() {
                                                                    model.setPrescriptionsDetailsLoading();
                                                                    Navigator.of(context).push(
                                                                      CustomPageRoute(
                                                                        page: PrescriptionDetailPage(prescriptionsResponseModel: prescription),
                                                                      ),
                                                                    );
                                                                  }),
                                                                ),
                                                              ],
                                                            ),
                                                            SizedBox(height: 12.h),
                                                            Divider(color: AppColors.borderOnlyColor.withValues(alpha: 0.05), height: 1.h),
                                                            SizedBox(height: 12.h),
                                                          ],
                                                        );
                                                      }).toList(),
                                                    ],
                                                  ),
                                                )
                                              : SizedBox.shrink(),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                              )
                            : Utils.getNoDataWidget(context, noDataText: "You don't have any prescriptions yet.".needTranslation);
                  },
                ).paddingSymmetrical(24.h, 0.h),
              ],
            );
          }),
        ),
      ),
    );
  }
}
