import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:hyper_local/utils/extensions.dart';
import 'package:hyper_local/utils/widgets/custom_appbar_without_navbar.dart';
import 'package:hyper_local/utils/widgets/custom_card.dart';
import 'package:hyper_local/utils/widgets/custom_scaffold.dart';
import 'package:hyper_local/utils/widgets/custom_text.dart';
import 'package:hyper_local/utils/widgets/empty_state_widget.dart';
import 'package:hyper_local/utils/widgets/loading_widget.dart';
import 'package:hyper_local/utils/currency_formatter.dart';
import 'package:hyper_local/l10n/app_localizations.dart';
import 'package:hyper_local/screens/pockets/cash_collection/bloc/cash_collection_bloc.dart';
import 'package:hyper_local/screens/pockets/cash_collection/bloc/cash_collection_event.dart';
import 'package:hyper_local/screens/pockets/cash_collection/bloc/cash_collection_state.dart';
import 'package:hyper_local/screens/pockets/cash_collection/model/cash_collection_model.dart';

import '../../../../config/colors.dart';
import '../../../../config/helper.dart';

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

  @override
  State<CashCollectionPage> createState() => _CashCollectionPageState();
}

class _CashCollectionPageState extends State<CashCollectionPage> {
  int _selectedTabIndex = 0;
  CashCollectionResponse? _currentResponse;

  final List<String> _submissionStatusOptions = ['pending', 'partially_submitted', 'submitted'];

  @override
  void initState() {
    super.initState();

    // Fetch initial data for pending status
    context.read<CashCollectionBloc>().add(FetchCashCollectionByDateRange('', submissionStatus: 'pending'));
  }

  void _fetchCashCollectionForStatus(String status) {
    // Fetch cash collection with specific submission status only
    context.read<CashCollectionBloc>().add(FetchCashCollectionByDateRange('', submissionStatus: status));
  }

  @override
  Widget build(BuildContext context) {
    return BlocBuilder<CashCollectionBloc, CashCollectionState>(
      builder: (context, state) {
        final totalCount = state.response?.data?.total;
        final countText = totalCount != null ? ' ($totalCount)' : '';

        return CustomScaffold(
          appBar: CustomAppBar(
            title: '${AppLocalizations.of(context)!.cashCollection}$countText',
            // additionalActions: [
            //   TextButton(
            //     onPressed: () {
            //       context.push('/all-cash-collection');
            //     },
            //     child: CustomText(
            //       text: AppLocalizations.of(context)!.all,
            //       fontWeight: FontWeight.w500,
            //       color: AppColors.textSecondaryColor,
            //       textAlign: TextAlign.center,
            //     ),
            //   ),
            // ],
          ),
          body: Column(
            children: [
              // Date Range Tabs
              // _buildDateRangeTabs(),

              // Submission Status Tabs
              Container(
                height: 60.h,
                padding: EdgeInsets.symmetric(horizontal: 8, vertical: 12.h),
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: _submissionStatusOptions.length,
                  itemBuilder: (context, index) {
                    final status = _submissionStatusOptions[index];
                    final isSelected = _selectedTabIndex == index;

                    return GestureDetector(
                      onTap: () {
                        setState(() {
                          _selectedTabIndex = index;
                        });
                        // Fetch data for the specific submission status
                        final status = _submissionStatusOptions[index];
                        _fetchCashCollectionForStatus(status);
                      },
                      child: Container(
                        margin: EdgeInsets.only(right: 12.w),
                        padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 0.h),
                        alignment: Alignment.center, // Add this line
                        decoration: BoxDecoration(
                          color: isSelected ? AppColors.primaryColor : Colors.transparent,
                          borderRadius: BorderRadius.circular(20.r),
                          border: Border.all(
                            color:
                                isSelected
                                    ? Colors.transparent
                                    : Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
                            width: 1,
                          ),
                        ),
                        child: CustomText(
                          text: _getStatusDisplayText(status),

                          fontSize: 13,
                          fontWeight: FontWeight.w600,
                          color: isSelected ? Colors.white : Theme.of(context).colorScheme.onSurface,
                          maxLines: 1,
                          textAlign: TextAlign.center,
                          overflow: TextOverflow.visible,
                        ),
                      ),
                    );
                  },
                ),
              ),

              // Content
              Expanded(child: _buildTabContent(_submissionStatusOptions[_selectedTabIndex])),
            ],
          ),
        );
      },
    );
  }

  // Widget _buildDateRangeTabs() {
  //   final isDarkTheme = Theme.of(context).brightness == Brightness.dark;
  //
  //   return Container(
  //     height: 60.h,
  //     padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
  //     decoration: BoxDecoration(
  //       color: Theme.of(context).colorScheme.surface,
  //       border: Border(
  //         bottom: BorderSide(
  //           color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.1),
  //           width: 1,
  //         ),
  //       ),
  //     ),
  //     child: ListView.builder(
  //       scrollDirection: Axis.horizontal,
  //       itemCount: _dateRangeOptions.length,
  //       itemBuilder: (context, index) {
  //         final dateRange = _dateRangeOptions[index];
  //         final isSelected = _selectedDateRange == dateRange;
  //
  //         return GestureDetector(
  //           onTap: () => _onDateRangeChanged(dateRange),
  //           child: Container(
  //             margin: EdgeInsets.only(right: 12.w),
  //             padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 12.h),
  //             decoration: BoxDecoration(
  //               color: isSelected
  //                   ? AppColors.primaryColor
  //                   : Theme.of(context).colorScheme.surface,
  //               borderRadius: BorderRadius.circular(25.r),
  //               border: Border.all(
  //                 color: isSelected
  //                     ? AppColors.primaryColor
  //                     : Theme.of(context).colorScheme.outline.withValues(alpha: 0.3),
  //                 width: 1.5,
  //               ),
  //               boxShadow: isSelected ? [
  //                 BoxShadow(
  //                   color: AppColors.primaryColor.withValues(alpha: 0.3),
  //                   blurRadius: 8.r,
  //                   offset: Offset(0, 2.h),
  //                 ),
  //               ] : null,
  //             ),
  //             child: CustomText(
  //               text: _getDateRangeDisplayText(dateRange),
  //
  //               fontSize: 13.sp,
  //               fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
  //               color: isSelected
  //                   ? Colors.white
  //                   : Theme.of(context).colorScheme.onSurface,
  //             ),
  //           ),
  //         );
  //       },
  //     ),
  //   );
  // }

  Widget _buildTabContent(String status) {
    return RefreshIndicator(
      onRefresh: () async {
        final completer = Completer<void>();
        context.read<CashCollectionBloc>().add(
          FetchCashCollectionByDateRange('', submissionStatus: status, completer: completer),
        );
        await completer.future;
      },
      child: BlocConsumer<CashCollectionBloc, CashCollectionState>(
        listener: (context, state) {},
        builder: (context, state) {
          if (state.fetchStatus == ApiStatus.loading || state.fetchStatus == ApiStatus.initial) {
            return const Center(child: LoadingWidget());
          } else if (state.fetchStatus == ApiStatus.failed) {
            return ErrorStateWidget(
              onRetry: () {
                context.read<CashCollectionBloc>().add(FetchCashCollectionByDateRange('last_1_day'));
              },
            );
            // return _buildErrorState(state.message);
          } else if (state.fetchStatus == ApiStatus.success && state.response != null) {
            _currentResponse = state.response;
            final response = _currentResponse;
            if (response?.data?.cashCollections == null || response!.data!.cashCollections!.isEmpty) {
              return _buildEmptyState();
            }

            // Filter by submission status
            final filteredCollections =
                response.data!.cashCollections!.where((collection) => collection.submissionStatus == status).toList();

            if (filteredCollections.isEmpty) {
              return _buildEmptyState();
            }

            return _buildCashCollectionList(filteredCollections);
          }

          return _buildEmptyState();
        },
      ),
    );
  }

  Widget _buildCashCollectionList(List<CashCollectionModel> earnings) {
    return ListView.builder(
      padding: const EdgeInsets.all(8),
      itemCount: earnings.length,
      itemBuilder: (context, index) {
        final collection = earnings[index];
        return _buildCashCollectionCard(collection).fadeAndSlideAnimation();
      },
    );
  }

  Widget _buildCashCollectionCard(CashCollectionModel collection) {
    final status = collection.submissionStatus ?? 'pending';
    final statusColor = _getStatusColor(status);
    final statusText = _getStatusDisplayText(status);

    return Padding(
      padding: EdgeInsets.only(bottom: 10.h),
      child: CustomCard(
        borderRadius: 12.r,
        padding: EdgeInsets.all((isTablet() ? 12 : 16).w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Top Row: Order ID & Status Badge
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.receipt_long_rounded,
                      size: sz(18, seprateTabletSize: 14).sp,
                      color: AppColors.primaryColor,
                    ),
                    SizedBox(width: 8.w),
                    CustomText(
                      text: '${AppLocalizations.of(context)!.order} #${collection.orderId}',
                      fontSize: sz(15, seprateTabletSize: 12),
                      fontWeight: FontWeight.w700,
                      color: Theme.of(context).colorScheme.onSurface,
                    ),
                  ],
                ),
                Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: sz(10, seprateTabletSize: 8).w,
                    vertical: sz(4, seprateTabletSize: 3).h,
                  ),
                  decoration: BoxDecoration(
                    color: statusColor.withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(12.r),
                    border: Border.all(color: statusColor.withValues(alpha: 0.15), width: 1.r),
                  ),
                  child: CustomText(
                    text: statusText,
                    fontSize: sz(11, seprateTabletSize: 8),
                    fontWeight: FontWeight.w600,
                    color: statusColor,
                  ),
                ),
              ],
            ),
            SizedBox(height: 8.h),

            // Date Row
            Row(
              children: [
                Icon(
                  Icons.calendar_today_rounded,
                  size: sz(13, seprateTabletSize: 10).sp,
                  color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.4),
                ),
                SizedBox(width: 6.w),
                CustomText(
                  text:
                      '${AppLocalizations.of(context)!.date}: ${collection.orderDate ?? AppLocalizations.of(context)!.na}',
                  fontSize: sz(12, seprateTabletSize: 9),
                  color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.6),
                ),
              ],
            ),

            SizedBox(height: 12.h),
            Divider(color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.08), height: 1.h, thickness: 1.h),
            SizedBox(height: 12.h),

            // Bottom Financial Info Grid (3 Columns)
            Row(
              children: [
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      CustomText(
                        text: AppLocalizations.of(context)!.cashCollected,
                        fontSize: sz(11, seprateTabletSize: 8),
                        color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
                        fontWeight: FontWeight.w500,
                      ),
                      SizedBox(height: 4.h),
                      CustomText(
                        text: CurrencyFormatter.formatAmount(context, collection.cashCollected ?? '0'),
                        fontSize: sz(14, seprateTabletSize: 11),
                        fontWeight: FontWeight.w700,
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                    ],
                  ),
                ),
                Container(
                  height: 28.h,
                  width: 1.w,
                  color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.08),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 8.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CustomText(
                          text: AppLocalizations.of(context)!.cashSubmitted,
                          fontSize: sz(11, seprateTabletSize: 8),
                          color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
                          fontWeight: FontWeight.w500,
                        ),
                        SizedBox(height: 4.h),
                        CustomText(
                          text: CurrencyFormatter.formatAmount(context, collection.cashSubmitted ?? '0'),
                          fontSize: sz(14, seprateTabletSize: 11),
                          fontWeight: FontWeight.w700,
                          color: Theme.of(context).colorScheme.onSurface,
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  height: 28.h,
                  width: 1.w,
                  color: Theme.of(context).colorScheme.outline.withValues(alpha: 0.08),
                ),
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.only(left: 8.w),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        CustomText(
                          text: AppLocalizations.of(context)!.remaning,
                          fontSize: sz(11, seprateTabletSize: 8),
                          color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.5),
                          fontWeight: FontWeight.w500,
                        ),
                        SizedBox(height: 4.h),
                        CustomText(
                          text: CurrencyFormatter.formatAmount(context, collection.remainingAmount ?? '0'),
                          fontSize: sz(14, seprateTabletSize: 11),
                          fontWeight: FontWeight.w700,
                          color: status == 'submitted' ? Colors.green : AppColors.primaryColor,
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyState() {
    return EmptyStateWidget(
      title: AppLocalizations.of(context)!.noCashCollectionYet,
      subtitle: AppLocalizations.of(context)!.completeDeliveriesToSeeYourCashCollection,
      icon: Icons.account_balance_wallet_outlined,
      showRetryButton: false,
    );
  }

  String _getStatusDisplayText(String status) {
    switch (status) {
      case 'pending':
        return AppLocalizations.of(context)!.pending;
      case 'partially_submitted':
        return AppLocalizations.of(context)!.partiallySubmitted;
      case 'submitted':
        return AppLocalizations.of(context)!.submitted;
      default:
        return AppLocalizations.of(context)!.unknown;
    }
  }

  Color _getStatusColor(String status) {
    switch (status) {
      case 'pending':
        return Colors.orange;
      case 'partially_submitted':
        return Colors.blue;
      case 'submitted':
        return AppColors.primaryColor;
      default:
        return Colors.grey;
    }
  }
}
