import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:hmg_patient_app_new/core/app_assets.dart';
import 'package:hmg_patient_app_new/core/app_export.dart';
import 'package:hmg_patient_app_new/core/app_state.dart';
import 'package:hmg_patient_app_new/core/utils/utils.dart';
import 'package:hmg_patient_app_new/extensions/route_extensions.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/generated/locale_keys.g.dart';
import 'package:hmg_patient_app_new/theme/colors.dart';

import '../../core/dependencies.dart';

class CollapsingListView extends StatelessWidget {
  final String title;
  Widget? child;
  VoidCallback? search;
  VoidCallback? report;
  VoidCallback? logout;
  VoidCallback? aiOverview;
  VoidCallback? history;
  VoidCallback? instructions;
  VoidCallback? requests;
  VoidCallback? sendEmail;
  VoidCallback? doctorResponse;
  VoidCallback? downloadReport;
  VoidCallback? viewImage;
  VoidCallback? location;
  VoidCallback? downloadInvoice;
  Widget? bottomChild;
  Widget? trailing;
  bool isClose;
  bool isLeading;
  VoidCallback? leadingCallback;
  ScrollPhysics? physics;

  CollapsingListView({
    super.key,
    required this.title,
    this.child,
    this.search,
    this.isClose = false,
    this.bottomChild,
    this.report,
    this.logout,
    this.aiOverview,
    this.history,
    this.instructions,
    this.requests,
    this.sendEmail,
    this.doctorResponse,
    this.downloadReport,
    this.viewImage,
    this.location,
    this.downloadInvoice,
    this.isLeading = true,
    this.trailing,
    this.leadingCallback,
    this.physics,
  });

  final ScrollController _controller = ScrollController();

  @override
  Widget build(BuildContext context) {
    AppState appState = getIt.get<AppState>();
    return Scaffold(
      backgroundColor: AppColors.bgScaffoldColor,
      body: Column(
        children: [
          CustomScrollView(
            physics: physics,
            controller: _controller,
            slivers: [
              SliverAppBar(
                  automaticallyImplyLeading: isLeading,
                  pinned: true,
                  toolbarHeight: 40.h,
                  leadingWidth: isLeading ? 40.w + 32.w : double.infinity,
                  systemOverlayStyle: SystemUiOverlayStyle(statusBarBrightness: Brightness.light),
                  surfaceTintColor: Colors.transparent,
                  backgroundColor: AppColors.bgScaffoldColor,
                  bottom:
                      // isLeading
                      //     ?
                      ScrollAnimatedTitle(
                    title: title,
                    showBack: true,
                    controller: _controller,
                    search: search,
                    report: report,
                    logout: logout,
                    history: history,
                    instructions: instructions,
                    requests: requests,
                    sendEmail: sendEmail,
                    doctorResponse: doctorResponse,
                    downloadReport: downloadReport,
                    viewImage: viewImage,
                    location: location,
                    downloadInvoice: downloadInvoice,
                    bottomChild: bottomChild,
                    trailing: trailing,
                    aiOverview: aiOverview,
                  ),
                  // : null,
                  leading: Visibility(
                    visible: isLeading,
                    child: Container(
                      height: 32.h,
                      width: 32.w,
                      alignment: appState.isArabic() ? Alignment.centerRight : Alignment.centerLeft,
                      margin: EdgeInsets.fromLTRB(24.w, 0, 24.w, 0),
                      child: Transform.flip(
                        flipX: appState.isArabic(),
                        child: Utils.buildSvgWithAssets(
                            icon: isClose ? AppAssets.close_bottom_nav_trans : AppAssets.arrow_back_new, width: 24.h, height: 24.h),
                      ),
                    ).onPress(() {
                      if (leadingCallback != null) {
                        leadingCallback!();
                      } else {
                        context.pop();
                      }
                    }),
                  )
                  // : ScrollAnimatedTitle(
                  //     title: title,
                  //     showBack: false,
                  //     controller: _controller,
                  //     search: search,
                  //     report: report,
                  //     logout: logout,
                  //     history: history,
                  //     instructions: instructions,
                  //     requests: requests,
                  //     sendEmail: sendEmail,
                  //     bottomChild: bottomChild,
                  //     trailing: trailing,
                  //   ),
                  ),
              if (child != null)
                SliverToBoxAdapter(
                  child: child!,
                ),
            ],
          ).expanded,
          if (bottomChild != null) bottomChild!
        ],
      ),
    );
  }

// Widget actionButton(BuildContext context, double t, {required String title, required String icon}) {
//   return AnimatedSize(
//     duration: Duration(milliseconds: 150),
//     child: Container(
//       height: 40.h,
//       padding: EdgeInsets.all(8.w),
//       margin: EdgeInsets.only(right: 24.w),
//       decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
//         color: AppColors.secondaryLightRedColor,
//         borderRadius: 10.r,
//       ),
//       child: Row(
//         crossAxisAlignment: CrossAxisAlignment.center,
//         mainAxisAlignment: MainAxisAlignment.center,
//         mainAxisSize: MainAxisSize.min,
//         spacing: 8.h,
//         children: [
//           Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor),
//           if (t == 1)
//             Text(
//               title,
//               style: context.dynamicTextStyle(
//                 color: AppColors.primaryRedColor,
//                 letterSpacing: -0.4,
//                 fontSize: (12 - (2 * (1 - t))).f,
//                 fontWeight: FontWeight.lerp(
//                   FontWeight.w300,
//                   FontWeight.w600,
//                   t,
//                 )!,
//               ),
//             ),
//         ],
//       ),
//     ),
//   );
// }
}
//
// class ActionModel {
//   bool requireT;
//
// }

class ScrollAnimatedTitle extends StatefulWidget implements PreferredSizeWidget {
  final String title;
  final bool showBack;
  final ScrollController controller;

  VoidCallback? search;
  VoidCallback? report;
  VoidCallback? logout;
  VoidCallback? aiOverview;
  VoidCallback? history;
  VoidCallback? instructions;
  VoidCallback? requests;
  VoidCallback? sendEmail;
  VoidCallback? doctorResponse;
  VoidCallback? downloadReport;
  VoidCallback? viewImage;
  VoidCallback? location;
  VoidCallback? downloadInvoice;
  Widget? bottomChild;
  Widget? trailing;

  ScrollAnimatedTitle({
    super.key,
    required this.title,
    required this.controller,
    required this.showBack,
    this.search,
    this.report,
    this.logout,
    this.aiOverview,
    this.history,
    this.instructions,
    this.requests,
    this.sendEmail,
    this.doctorResponse,
    this.downloadReport,
    this.viewImage,
    this.location,
    this.downloadInvoice,
    this.bottomChild,
    this.trailing,
  });

  @override
  Size get preferredSize => const Size.fromHeight(56.0);

  @override
  State<ScrollAnimatedTitle> createState() => _ScrollAnimatedTitleState();
}

class _ScrollAnimatedTitleState extends State<ScrollAnimatedTitle> {
  static const double _maxFont = 26;
  static const double _minFont = 18;

  static const double _maxHeight = 80;
  static const double _minHeight = 56;

  double _fontSize = _maxFont;

  @override
  void initState() {
    super.initState();
    widget.controller.addListener(_onScroll);
  }

  @override
  void dispose() {
    widget.controller.removeListener(_onScroll);
    super.dispose();
  }

  double t = 1.0;

  void _onScroll() {
    final double offset = widget.controller.offset;

    // control animation range
    const double range = 120;

    final double t = (1 - (offset / range)).clamp(0.0, 1.0);
    this.t = t;
    setState(() {
      _fontSize = _minFont + (_maxFont - _minFont) * t;
    });
  }

  @override
  Widget build(BuildContext context) {
    final isRtl = Directionality.of(context) == TextDirection.RTL;
    return Container(
      // height: (widget.preferredSize.height - _fontSize / 2).h,
      height: 56.h,
      alignment:
          isRtl ? (widget.showBack ? Alignment.topRight : Alignment.centerRight) : (widget.showBack ? Alignment.topLeft : Alignment.centerLeft),
      padding: EdgeInsets.fromLTRB(24.w, 0, 24.w, 0),
      child: Row(
        spacing: 4.h,
        children: [
          Text(
            widget.title,
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: _fontSize.f,
              fontWeight: FontWeight.bold,
              letterSpacing: -0.5,
            ),
          ).expanded,
          ...[
            if (widget.logout != null)
              actionButton(context, t, title: LocaleKeys.logout.tr(context: context), icon: AppAssets.logout).onPress(widget.logout!),
            if (widget.report != null)
              actionButton(context, t, title: LocaleKeys.feedback.tr(context: context), icon: AppAssets.report_icon).onPress(widget.report!),
            if (widget.history != null)
              actionButton(context, t, title: LocaleKeys.history.tr(context: context), icon: AppAssets.insurance_history_icon)
                  .onPress(widget.history!),
            if (widget.instructions != null)
              actionButton(context, t, title: LocaleKeys.instructions.tr(context: context), icon: AppAssets.requests).onPress(widget.instructions!),
            if (widget.requests != null)
              actionButton(context, t, title: LocaleKeys.requests.tr(context: context), icon: AppAssets.insurance_history_icon)
                  .onPress(widget.requests!),
            if (widget.sendEmail != null)
              actionButton(context, t, title: LocaleKeys.sendEmail.tr(context: context), icon: AppAssets.email).onPress(widget.sendEmail!),
            if (widget.doctorResponse != null)
              actionButton(context, t, title: LocaleKeys.doctorResponses.tr(context: context), icon: AppAssets.doctorResponseIcon)
                  .onPress(widget.doctorResponse!),
            if (widget.search != null) Utils.buildSvgWithAssets(icon: AppAssets.search_icon).onPress(widget.search!),
            if (widget.aiOverview != null)
              actionButton(context, t, title: LocaleKeys.aiOverView.tr(context: context), icon: AppAssets.aiOverView, isAiButton: true)
                  .onPress(widget.aiOverview!),
            if (widget.downloadReport != null)
              actionButton(context, t, title: LocaleKeys.downloadReport.tr(context: context), icon: AppAssets.download)
                  .onPress(widget.downloadReport!),
            if (widget.viewImage != null)
              actionButton(context, t, title: LocaleKeys.viewRadiologyImage.tr(context: context), icon: AppAssets.download)
                  .onPress(widget.viewImage!),
            if (widget.location != null)
              actionButton(context, t, title: LocaleKeys.sortByLocation.tr(context: context), icon: AppAssets.location).onPress(widget.location!),
            if (widget.downloadInvoice != null)
              actionButton(context, t, title: LocaleKeys.downloadInvoice.tr(context: context), icon: AppAssets.download)
                  .onPress(widget.downloadInvoice!),
            if (widget.trailing != null) widget.trailing!,
          ]
        ],
      ),
    );
  }

  Widget actionButton(BuildContext context, double t, {required String title, required String icon, bool isAiButton = false}) {
    return isAiButton
        ? AnimatedSize(
            duration: Duration(milliseconds: 150),
            child: Center(
              child: Container(
                height: isFoldable ? 50.h : 40.h,
                padding: EdgeInsets.all(8.w),
                decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                    color: AppColors.whiteColor, borderRadius: 8.r, side: BorderSide(width: 1, color: AppColors.borderGrayColor)),
                child: ShaderMask(
                  blendMode: BlendMode.srcIn,
                  shaderCallback: (bounds) => AppColors.aiLinearGradient.createShader(bounds),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    spacing: 8.h,
                    children: [
                      Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w),
                      Text(
                        title,
                        style: context.dynamicTextStyle(
                          color: AppColors.primaryRedColor,
                          letterSpacing: -0.4,
                          fontSize: (14 - (2 * (1 - t))).f,
                          fontWeight: FontWeight.lerp(
                            FontWeight.w400,
                            FontWeight.w600,
                            t,
                          )!,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          )
        : AnimatedSize(
            duration: Duration(milliseconds: 150),
            child: Container(
              height: isFoldable ? 50.h : 40.h,
              padding: EdgeInsets.all(8.w),
              decoration: RoundedRectangleBorder().toSmoothCornerDecoration(
                color: AppColors.secondaryLightRedColor,
                borderRadius: 10.r,
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                spacing: 8.h,
                children: [
                  Utils.buildSvgWithAssets(icon: icon, iconColor: AppColors.primaryRedColor, height: 24.h, width: 24.w),
                  if (t >= .5)
                    Text(
                      title,
                      style: context.dynamicTextStyle(
                        color: AppColors.primaryRedColor,
                        letterSpacing: -0.4,
                        fontSize: (12 - (2 * (1 - t))).f,
                        fontWeight: FontWeight.lerp(
                          FontWeight.w500,
                          FontWeight.w700,
                          t,
                        )!,
                      ),
                    ),
                ],
              ),
            ),
          );
  }
}
