import 'dart:developer';

import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:shimmer/shimmer.dart';

import '../../../../application/order/order_loader/order_loader_bloc.dart';
import '../../../../application/outlet/outlet_list_loader/outlet_list_loader_bloc.dart';
import '../../../../common/extension/extension.dart';
import '../../../../common/theme/theme.dart';
import '../../../../injection.dart';
import '../../../components/appbar/appbar.dart';
import '../../../components/widgets/empty_widget.dart';
import '../../../router/app_router.gr.dart';
import 'widgets/filter_header_delegate.dart';
import 'widgets/order_tile.dart';

@RoutePage()
class OrderPage extends StatefulWidget implements AutoRouteWrapper {
  const OrderPage({super.key});

  @override
  State<OrderPage> createState() => _OrderPageState();

  @override
  Widget wrappedRoute(BuildContext context) => MultiBlocProvider(
    providers: [
      BlocProvider(
        create: (_) =>
            getIt<OrderLoaderBloc>()
              ..add(OrderLoaderEvent.fetched(isRefresh: true)),
      ),
      BlocProvider(
        create: (_) =>
            getIt<OutletListLoaderBloc>()
              ..add(const OutletListLoaderEvent.fetched()),
      ),
    ],
    child: this,
  );
}

class _OrderPageState extends State<OrderPage> with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late AnimationController _slideController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  final ScrollController _scrollController = ScrollController();

  // Filter state
  final List<String> filterOptions = ['All', 'Completed', 'Pending'];

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

    _fadeController = AnimationController(
      duration: const Duration(milliseconds: 800),
      vsync: this,
    );

    _slideController = AnimationController(
      duration: const Duration(milliseconds: 1000),
      vsync: this,
    );

    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _fadeController, curve: Curves.easeInOut),
    );

    _slideAnimation =
        Tween<Offset>(begin: const Offset(0, 0.3), end: Offset.zero).animate(
          CurvedAnimation(parent: _slideController, curve: Curves.elasticOut),
        );

    _fadeController.forward();
    _slideController.forward();
  }

  @override
  void dispose() {
    _fadeController.dispose();
    _slideController.dispose();
    super.dispose();
  }

  Widget _buildShimmerOrderCard() {
    return Shimmer.fromColors(
      baseColor: Colors.grey[300]!,
      highlightColor: Colors.grey[100]!,
      child: Container(
        margin: const EdgeInsets.only(bottom: 12),
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 10,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 120,
                  height: 16,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                Container(
                  width: 60,
                  height: 20,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(10),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Container(
              width: double.infinity,
              height: 14,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
            ),
            const SizedBox(height: 6),
            Container(
              width: 200,
              height: 14,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(4),
              ),
            ),
            const SizedBox(height: 12),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Container(
                  width: 80,
                  height: 14,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
                Container(
                  width: 100,
                  height: 16,
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(4),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildShimmerList() {
    return ListView.builder(
      itemCount: 5, // Show 5 shimmer cards
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      itemBuilder: (context, index) => _buildShimmerOrderCard(),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.background,
      body: MultiBlocListener(
        listeners: [
          BlocListener<OrderLoaderBloc, OrderLoaderState>(
            listenWhen: (p, c) => p.outletId != c.outletId,
            listener: (context, state) {
              context.read<OrderLoaderBloc>().add(
                OrderLoaderEvent.fetched(isRefresh: true),
              );
            },
          ),
          BlocListener<OrderLoaderBloc, OrderLoaderState>(
            listenWhen: (p, c) => p.status != c.status,
            listener: (context, state) {
              context.read<OrderLoaderBloc>().add(
                OrderLoaderEvent.fetched(isRefresh: true),
              );
            },
          ),
          BlocListener<OrderLoaderBloc, OrderLoaderState>(
            listenWhen: (previous, current) =>
                previous.dateFrom != current.dateFrom ||
                previous.dateTo != current.dateTo,
            listener: (context, state) {
              context.read<OrderLoaderBloc>().add(
                OrderLoaderEvent.fetched(isRefresh: true),
              );
            },
          ),
        ],
        child: BlocBuilder<OutletListLoaderBloc, OutletListLoaderState>(
          builder: (context, outletListState) {
            return BlocBuilder<OrderLoaderBloc, OrderLoaderState>(
              builder: (context, state) {
                return NotificationListener<ScrollNotification>(
                  onNotification: (notification) {
                    if (notification is ScrollEndNotification &&
                        _scrollController.position.extentAfter == 0) {
                      context.read<OrderLoaderBloc>().add(
                        OrderLoaderEvent.fetched(),
                      );
                      return true;
                    }

                    return true;
                  },
                  child: CustomScrollView(
                    controller: _scrollController,
                    slivers: [
                      // Custom App Bar with Hero Effect
                      SliverAppBar(
                        expandedHeight: 120,
                        floating: true,
                        pinned: true,
                        backgroundColor: AppColor.primary,
                        centerTitle: false,
                        flexibleSpace: CustomAppBar(
                          title: context.lang.orders,
                          isBack: false,
                        ),
                      ),

                      // Pinned Filter Section
                      SliverPersistentHeader(
                        pinned: true,
                        delegate: FilterHeaderDelegate(
                          backgroundColor: AppColor.background,
                          padding: EdgeInsets.fromLTRB(
                            AppValue.padding,
                            10,
                            AppValue.padding,
                            10,
                          ),
                          startDate: state.dateFrom,
                          endDate: state.dateTo,
                          filterOptions: filterOptions,
                          selectedFilter: state.status,
                          selectedOutletId: state.outletId,
                          outletListState: outletListState,
                          onDateChanged: (startDate, endDate) {
                            if (startDate != null && endDate != null) {
                              log('Date changed');
                              context.read<OrderLoaderBloc>().add(
                                OrderLoaderEvent.rangeDateChanged(
                                  startDate,
                                  endDate,
                                ),
                              );
                            }
                          },
                          onFilterChanged: (filter) {
                            final status = filter.toLowerCase();
                            context.read<OrderLoaderBloc>().add(
                              OrderLoaderEvent.statusChanged(status),
                            );
                          },
                          onOutletChanged: (outletId) {
                            context.read<OrderLoaderBloc>().add(
                              OrderLoaderEvent.outletChanged(outletId),
                            );
                          },
                        ),
                      ),

                      // Content
                      SliverPadding(
                        padding: EdgeInsets.all(AppValue.padding),
                        sliver: SliverList(
                          delegate: SliverChildListDelegate([
                            FadeTransition(
                              opacity: _fadeAnimation,
                              child: SlideTransition(
                                position: _slideAnimation,
                                child: Column(
                                  children: [
                                    // Show filtered transaction count
                                    if (state.status != 'all' &&
                                        !state.isFetching)
                                      Padding(
                                        padding: const EdgeInsets.only(
                                          bottom: 16,
                                        ),
                                        child: Row(
                                          children: [
                                            Text(
                                              '${state.orders.length} ${state.status.toLowerCase()} ${context.lang.orders}',
                                              style: TextStyle(
                                                color: AppColor.textSecondary,
                                                fontSize: 14,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),

                                    // Order List with Shimmer Loading
                                    if (state.isFetching)
                                      _buildShimmerList()
                                    else if (state.orders.isEmpty)
                                      EmptyWidget(
                                        title: context.lang.order,
                                        message:
                                            context.lang.no_order_with_status(
                                              state.status.toLowerCase(),
                                            ),
                                      )
                                    else
                                      ListView.builder(
                                        itemCount: state.orders.length,
                                        shrinkWrap: true,
                                        physics:
                                            const NeverScrollableScrollPhysics(),
                                        padding: EdgeInsets.zero,
                                        itemBuilder: (context, index) {
                                          return OrderTile(
                                            onTap: () => context.router.push(
                                              OrderDetailRoute(
                                                order: state.orders[index],
                                              ),
                                            ),
                                            order: state.orders[index],
                                          );
                                        },
                                      ),
                                  ],
                                ),
                              ),
                            ),
                          ]),
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}
