import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.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/widgets/custom_error_screen.dart';
import 'package:niogu_app/core/providers/app_provider.dart';
import 'package:niogu_app/core/router/app_route.dart';
import 'package:niogu_app/core/enums/item_type.dart';
import 'package:niogu_app/core/enums/report_type.dart';
import 'package:niogu_app/core/enums/user_role.dart';
import 'package:niogu_app/core/widgets/custom_empty_screen.dart';
import 'package:niogu_app/features/outlets/presentation/providers/outlet_provider.dart';
import 'package:niogu_app/features/report/presentation/providers/report_provider.dart';
import 'package:niogu_app/features/report/presentation/widgets/filtered_date_range.dart';
import 'package:niogu_app/features/report/presentation/widgets/filtered_outlet.dart';
import 'package:niogu_app/features/report/presentation/widgets/filtered_type.dart';
import 'package:niogu_app/features/report/presentation/widgets/fixed_outlet.dart';
import 'package:niogu_app/features/report/presentation/widgets/report_header.dart';
import 'package:niogu_app/features/report/stock_report/domain/entities/stok_report.dart';
import 'package:niogu_app/features/report/stock_report/presentation/providers/stock_report_provider.dart';
import 'package:niogu_app/features/report/stock_report/presentation/widgets/stock_card_item.dart';
import 'package:niogu_app/features/report/stock_report/presentation/widgets/stock_report_shimmer.dart';
import 'package:niogu_app/features/report/transaction/presentation/widgets/sliver_header_delegate.dart';
import 'package:niogu_app/features/stock_in/domain/entities/stock_in_transfer.dart';
import 'package:sizer/sizer.dart';

class StockReportScreen extends ConsumerStatefulWidget {
  const StockReportScreen({super.key});

  @override
  ConsumerState<StockReportScreen> createState() => _StockReportScreenState();
}

class _StockReportScreenState extends ConsumerState<StockReportScreen>
    with AutomaticKeepAliveClientMixin {
  String? _selectedOutlet;

  String _selectedType = "Semua Barang";

  DateTimeRange? _selectedDateRange;

  List<DateTime?> _initialValue = [
    DateTime.now().subtract(const Duration(days: 7)),
    DateTime.now(),
  ];

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((_) {
      final currentOutletId = ref.read(currentOutletIdProvider);
      ref.read(filteredByOutletProvider(ReportType.stock_card).notifier).state =
          currentOutletId;
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  String _formatGroupDate(DateTime date) {
    return DateFormat('dd MMMM yyyy').format(date);
  }

  Future<void> _showDateRangePicker() async {
    final bool isTablet = 100.w >= 600;

    List<DateTime?> tempSelectedDates = List.from(_initialValue);

    showModalBottomSheet(
      context: context,
      useRootNavigator: true,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      constraints: BoxConstraints(maxWidth: double.infinity),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return Container(
              height: 80.h,
              width: double.infinity,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(4.5.w),
                ),
              ),
              constraints: BoxConstraints(
                maxHeight: 80.h,
                maxWidth: double.infinity,
              ),
              child: Column(
                children: [
                  SizedBox(height: 1.5.h),
                  Container(
                    width: 12.w,
                    height: 0.6.h,
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2.5.w),
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 2.h),
                    child: Text(
                      "Pilih Rentang Tanggal",
                      style: TextStyle(
                        fontSize: isTablet
                            ? AppFontSize.medium.sp
                            : AppFontSize.small.sp,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  Divider(height: 1, color: Colors.grey[200]),

                  Expanded(
                    child: CalendarDatePicker2(
                      config: CalendarDatePicker2Config(
                        calendarType: CalendarDatePicker2Type.range,
                        selectedDayHighlightColor: AppColor.primaryColor,
                        weekdayLabels: [
                          'Min',
                          'Sen',
                          'Sel',
                          'Rab',
                          'Kam',
                          'Jum',
                          'Sab',
                        ],
                        weekdayLabelTextStyle: TextStyle(
                          color: Colors.grey[600],
                          fontWeight: FontWeight.bold,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                        controlsTextStyle: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: isTablet
                              ? AppFontSize.medium.sp
                              : AppFontSize.small.sp,
                        ),
                        centerAlignModePicker: true,
                        firstDayOfWeek: 1,
                      ),
                      value: tempSelectedDates,
                      onValueChanged: (dates) {
                        setModalState(() {
                          tempSelectedDates = dates;
                        });
                      },
                    ),
                  ),

                  Container(
                    padding: EdgeInsets.all(5.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(
                            onPressed: () {
                              _selectedDateRange = null;
                              ref
                                      .read(
                                        filteredByDateTimeProvider(
                                          ReportType.stock_card,
                                        ).notifier,
                                      )
                                      .state =
                                  null;
                              context.pop();
                            },
                            style: OutlinedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              side: BorderSide(color: Colors.grey),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                            ),
                            child: Text(
                              "Atur Ulang",
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 3.w),
                        Expanded(
                          child: OutlinedButton(
                            onPressed: () => context.pop(),
                            style: OutlinedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              side: BorderSide(color: AppColor.primaryColor),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                            ),
                            child: Text(
                              "Batal",
                              style: TextStyle(
                                color: AppColor.primaryColor,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                        SizedBox(width: 3.w),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: tempSelectedDates.length < 2
                                ? null
                                : () {
                                    _initialValue = tempSelectedDates;
                                    final startDate = tempSelectedDates[0]!;

                                    final endDate = tempSelectedDates[1]!;

                                    final dateRange = DateTimeRange(
                                      start: startDate,
                                      end: endDate,
                                    );

                                    _selectedDateRange = dateRange;

                                    ref
                                            .read(
                                              filteredByDateTimeProvider(
                                                ReportType.stock_card,
                                              ).notifier,
                                            )
                                            .state =
                                        dateRange;

                                    context.pop();
                                  },
                            style: ElevatedButton.styleFrom(
                              padding: EdgeInsets.symmetric(vertical: 1.5.h),
                              backgroundColor: AppColor.primaryColor,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(2.5.w),
                              ),
                              disabledBackgroundColor: Colors.grey.shade300,
                            ),
                            child: Text(
                              "Pilih",
                              style: TextStyle(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: AppFontSize.medium.sp,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void _onSelectedOutletChange(String? value) {
    _selectedOutlet = value != '0' ? value : null;
    ref.read(filteredByOutletProvider(ReportType.stock_card).notifier).state =
        _selectedOutlet;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    final isLoggedIn = ref.watch(currentStatusLoginProvider);

    final List<SourceOutlet> sourceOutlets = [];

    final currentOutletId = ref.watch(currentOutletIdProvider);

    final currentUserRole = ref.watch(currentUserRoleProvider);

    final sourceOutletState = ref.watch(sourceOutletStreamProvider(true));

    final currentOutletName = ref.watch(currentOutletNameProvider);

    if (currentUserRole == UserRole.owner) {
      sourceOutletState.whenData((outlets) {
        sourceOutlets.addAll(outlets);
      });
    }

    final filteredStockReportState = ref.watch(filteredStockReportProvider);

    final stockReportEmptyState = isLoggedIn
        ? ref.watch(stockReportEmptyProvider)
        : StockReportItemEmpty.empty_database;

    return CustomScrollView(
      physics: const ClampingScrollPhysics(),
      slivers: [
        SliverAppBar(
          pinned: false,
          floating: true,
          snap: true,
          expandedHeight: 16.h,
          backgroundColor: Colors.white,
          elevation: 0,
          flexibleSpace: FlexibleSpaceBar(
            background: Material(
              color: Colors.white,
              elevation: 0,
              child: Padding(
                padding: EdgeInsets.fromLTRB(5.w, 2.h, 5.w, 1.h),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: currentUserRole == UserRole.owner
                              ? FilteredOutlet(
                                  value: sourceOutletState.isLoading
                                      ? currentOutletId!
                                      : (_selectedOutlet ?? currentOutletId!),
                                  sourceOutlets: sourceOutlets,
                                  onChanged: _onSelectedOutletChange,
                                )
                              : FixedOutlet(
                                  value:
                                      currentOutletName ?? 'Tidak ada outlet',
                                ),
                        ),

                        SizedBox(width: 3.w),

                        Expanded(
                          flex: 3,
                          child: FilteredType(
                            value: _selectedType,
                            items: ["Semua Barang", "Produk", "Bahan Baku"],
                            onChanged: (value) {
                              _selectedType = value!;
                              final type = value == 'Semua Barang'
                                  ? null
                                  : value == 'Produk'
                                  ? ItemType.product_variant
                                  : ItemType.raw_material;
                              ref
                                      .read(filteredByItemTypeProvider.notifier)
                                      .state =
                                  type;
                            },
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 1.5.h),

                    FilteredDateRange(
                      value: _selectedDateRange != null
                          ? "${_formatGroupDate(_selectedDateRange!.start)} - ${_formatGroupDate(_selectedDateRange!.end)}"
                          : "Filter Tanggal",
                      onTap: _showDateRangePicker,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),

        filteredStockReportState.when(
          data: (stockReports) {
            switch (stockReportEmptyState) {
              case StockReportItemEmpty.loading:
                return const SliverToBoxAdapter(child: SizedBox());
              case StockReportItemEmpty.empty_database:
                return const SliverToBoxAdapter(
                  child: CustomEmptyScreen(
                    title: "Tidak Ada Aktivitas Arus Stok",
                    body: "Kamu belum melakukan aktivitas arus stok",
                  ),
                );
              case StockReportItemEmpty.empty_search_result:
                return SliverMainAxisGroup(
                  slivers: [
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: SliverHeaderDelegate(
                        child: ReportHeader(
                          rightTitle: "Riwayat Arus Stok",
                          leftTitle: "Unduh Riwayat",
                        ),
                      ),
                    ),
                    const SliverToBoxAdapter(
                      child: CustomEmptyScreen(body: "Barang Tidak Ditemukan"),
                    ),
                  ],
                );
              case StockReportItemEmpty.has_data:
                return SliverMainAxisGroup(
                  slivers: [
                    SliverPersistentHeader(
                      pinned: true,
                      delegate: SliverHeaderDelegate(
                        child: ReportHeader(
                          rightTitle: "Riwayat Arus Stok",
                          leftTitle: "Unduh Riwayat",
                        ),
                      ),
                    ),
                    SliverPadding(
                      padding: EdgeInsets.symmetric(
                        horizontal: 5.w,
                        vertical: 2.h,
                      ),
                      sliver: SliverList(
                        delegate: SliverChildBuilderDelegate((context, index) {
                          final item = stockReports[index];
                          return StockCardItem(
                            item: item,
                            onTap: () async {
                              FocusScope.of(context).unfocus();

                              final dateRange = ref.read(
                                filteredByDateTimeProvider(
                                  ReportType.stock_card,
                                ),
                              );

                              final startDate = dateRange?.start;

                              final endDate = dateRange?.end;

                              final stockReportDetail = await ref
                                  .read(stockReportRepositoryProvider)
                                  .getStockReportById(
                                    id: item.id,
                                    itemType: item.itemType,
                                    startDate: startDate,
                                    endDate: endDate,
                                  );

                              await Future.delayed(
                                const Duration(milliseconds: 400),
                              );

                              context.pushNamed(
                                AppRoute.stockReportDetailScreen,
                                extra: stockReportDetail,
                              );
                            },
                          );
                        }, childCount: stockReports.length),
                      ),
                    ),
                  ],
                );
            }
          },
          error: (error, stackTrace) {
            return SliverToBoxAdapter(
              child: CustomErrorScreen(
                message: "Ups,terjadi kesalahan",
                onRefresh: () {},
              ),
            );
          },
          loading: () =>
              const SliverToBoxAdapter(child: const StockReportShimmer()),
        ),
      ],
    );
  }
}
