import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:niogu_app/core/components/top_back_bar_app.dart';
import 'package:niogu_app/core/constants/app_color.dart';
import 'package:niogu_app/core/constants/app_font_size.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/enums/stock_card_type.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/features/report/stock_report/domain/entities/stok_report.dart';
import 'package:niogu_app/features/report/stock_report/presentation/widgets/header_card.dart';
import 'package:niogu_app/features/report/stock_report/presentation/widgets/movement_card.dart';
import 'package:niogu_app/features/report/stock_report/presentation/widgets/sticky_footer.dart';
import 'package:niogu_app/features/report/transaction/presentation/providers/transaction_report_provider.dart';
import 'package:sizer/sizer.dart';

class StockReportDetailScreen extends ConsumerWidget {
  final StockReportDetail stockReportDetail;
  StockReportDetailScreen({super.key, required this.stockReportDetail});

  bool _isBetween(DateTime value, DateTime start, DateTime end) {
    final endInclusive = end.add(const Duration(days: 1));
    return !value.isBefore(start) && value.isBefore(endInclusive);
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final movements = stockReportDetail.movements.where((m) {
          final start = stockReportDetail.startDate;
          final end = stockReportDetail.endDate;

          if (start == null || end == null) return true;

          return _isBetween(m.date, start, end);
        }).toList();

        final lastMovement = stockReportDetail.movements.where((movement) {
          final bool filter =
              movement.modeChange &&
              movement.beforeChange != null &&
              movement.afterChange != null;

          final start = stockReportDetail.startDate;

          final end = stockReportDetail.endDate;

          if (start == null || end == null) {
            return filter;
          }

          return filter && _isBetween(movement.date, start, end);
        });

        bool modeChange = lastMovement.lastOrNull?.modeChange ?? false;

        final beforeChange = lastMovement.lastOrNull?.beforeChange;

        final afterChange = lastMovement.lastOrNull?.afterChange;

        final dateChange = lastMovement.lastOrNull?.date;

        modeChange =
            modeChange &&
            beforeChange != null &&
            afterChange != null &&
            dateChange != null;

        return SafeArea(
          top: false,
          bottom: true,
          right: false,
          left: false,
          child: Scaffold(
            backgroundColor: const Color(0xFFF9FAFB),
            appBar: TopBackBarApp(
              title: "Rincian Arus Stok",
              onTap: () => context.pop(),
            ),
            body: Column(
              children: [
                Expanded(
                  child: CustomScrollView(
                    physics: const BouncingScrollPhysics(),
                    slivers: [
                      SliverToBoxAdapter(
                        child: HeaderCard(
                          modeChange: modeChange,
                          beforeChange: beforeChange,
                          afterChange: afterChange,
                          dateChange: dateChange,
                          stockReportDetail: stockReportDetail,
                        ),
                      ),

                      movements.isEmpty
                          ? SliverToBoxAdapter(
                              child: CustomEmptyScreen(
                                body: "Tidak Ada Aktivitas Arus Stok",
                              ),
                            )
                          : SliverPadding(
                              padding: EdgeInsets.symmetric(
                                horizontal: 5.w,
                                vertical: 2.h,
                              ),
                              sliver: SliverList(
                                delegate: SliverChildBuilderDelegate(
                                  (context, index) => MovementCard(
                                    movement: movements[index],
                                    unit: stockReportDetail.unit,
                                    onTap: () async {
                                      final movement = movements[index];

                                      if (movement.type == StockCardType.sale) {
                                        final orderDetail = await ref
                                            .read(
                                              transactionReportRepositoryProvider,
                                            )
                                            .getOrderDetail(
                                              movement.referenceId!,
                                            );

                                        context.pushNamed(
                                          AppRoute
                                              .transactionReportOrderDetailScreen,
                                          extra: orderDetail,
                                        );
                                      } else if (movement.type ==
                                          StockCardType.purchase) {
                                        final purchaseDetail = await ref
                                            .read(
                                              transactionReportRepositoryProvider,
                                            )
                                            .getPurchaseDetail(
                                              movement.referenceId!,
                                            );

                                        context.pushNamed(
                                          AppRoute
                                              .transactionReportPurchaseDetailScreen,
                                          extra: purchaseDetail,
                                        );
                                      }
                                    },
                                  ),
                                  childCount: movements.length,
                                ),
                              ),
                            ),
                    ],
                  ),
                ),

                StickyFooter(
                  modeChange: modeChange,
                  stockReportDetail: stockReportDetail,
                ),
              ],
            ),
            bottomNavigationBar: Container(
              padding: EdgeInsets.all(4.w),
              decoration: BoxDecoration(
                color: Colors.white,
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withOpacity(0.05),
                    blurRadius: 10,
                    offset: const Offset(0, -5),
                  ),
                ],
              ),
              child: Row(
                children: [
                  Expanded(
                    child: OutlinedButton.icon(
                      onPressed: () {},
                      style: OutlinedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 1.8.h),
                        side: BorderSide(color: AppColor.primaryColor),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(2.5.w),
                        ),
                      ),
                      icon: Icon(
                        Icons.share_outlined,
                        color: AppColor.primaryColor,
                        size: 5.w,
                      ),
                      label: Text(
                        "Bagikan",
                        style: TextStyle(
                          color: AppColor.primaryColor,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 3.w),
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: () {}, // Logic download PDF
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(vertical: 1.8.h),
                        backgroundColor: AppColor.primaryColor,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(2.5.w),
                        ),
                        elevation: 0,
                      ),
                      icon: Icon(
                        Icons.picture_as_pdf_outlined,
                        color: Colors.white,
                        size: 5.w,
                      ),
                      label: Text(
                        "Unduh PDF",
                        style: TextStyle(
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: AppFontSize.medium.sp,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }
}
