import 'package:enaklo_pos/core/components/buttons.dart';
import 'package:enaklo_pos/core/components/spaces.dart';
import 'package:enaklo_pos/presentation/home/models/order_model.dart';
import 'package:enaklo_pos/presentation/sales/blocs/day_sales/day_sales_bloc.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_detail.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_list_order.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_order_information.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_payment.dart';
import 'package:enaklo_pos/presentation/sales/widgets/sales_right_title.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../core/constants/colors.dart';
import '../widgets/sales_card.dart';
import '../widgets/sales_title.dart';

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

  @override
  State<SalesPage> createState() => _SalesPageState();
}

class _SalesPageState extends State<SalesPage> {
  DateTime startDate = DateTime.now();
  DateTime endDate = DateTime.now();
  OrderModel? orderDetail;

  int _total = 0;
  String searchQuery = '';

  @override
  void initState() {
    context
        .read<DaySalesBloc>()
        .add(DaySalesEvent.getRangeDateSales(startDate, endDate));
    super.initState();
  }

  List<OrderModel> _filterOrders(List<OrderModel> orders) {
    if (searchQuery.isEmpty) {
      return orders;
    }

    return orders.where((order) {
      final customerName = order.customerName.toLowerCase();
      final queryLower = searchQuery.toLowerCase();
      return customerName.contains(queryLower);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        backgroundColor: AppColors.background,
        body: Row(
          children: [
            Expanded(
              flex: 2,
              child: Material(
                color: AppColors.white,
                child: Column(
                  children: [
                    SalesTitle(
                      startDate: startDate,
                      endDate: endDate,
                      total: _total,
                      onChanged: (value) {
                        setState(() {
                          searchQuery = value;
                        });
                      },
                      onDateRangeChanged: (start, end) {
                        setState(() {
                          startDate = start;
                          endDate = end;
                        });

                        context.read<DaySalesBloc>().add(
                            DaySalesEvent.getRangeDateSales(
                                startDate, endDate));
                      },
                    ),
                    Expanded(
                      child: BlocBuilder<DaySalesBloc, DaySalesState>(
                        builder: (context, state) {
                          return state.maybeWhen(
                            orElse: () => const Center(
                              child: CircularProgressIndicator(),
                            ),
                            loaded: (orders) {
                              final filtered = _filterOrders(orders);
                              if (filtered.isEmpty) {
                                return Center(
                                  child: Text(
                                    "Belum ada transaksi saat ini. ",
                                    style: TextStyle(
                                      fontSize: 16.0,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                );
                              } else {
                                WidgetsBinding.instance
                                    .addPostFrameCallback((_) {
                                  setState(() {
                                    _total = filtered.length;
                                  });
                                });

                                return SingleChildScrollView(
                                  child: Column(
                                    children: List.generate(
                                      filtered.length,
                                      (index) => GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            orderDetail = filtered[index];
                                          });
                                        },
                                        child: SalesCard(
                                          order: orders[index],
                                          isActive:
                                              orders[index] == orderDetail,
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }
                            },
                          );
                        },
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              flex: 4,
              child: orderDetail == null
                  ? Center(
                      child: Text(
                        "Belum ada order yang dipilih.",
                        style: TextStyle(
                          fontSize: 16.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    )
                  : Column(
                      children: [
                        SalesRightTitle(
                          order: orderDetail,
                          actionWidget: [
                            Button.outlined(
                              onPressed: () {},
                              label: 'Refund',
                              icon: Icon(Icons.autorenew),
                            ),
                          ],
                        ),
                        Padding(
                          padding: const EdgeInsets.all(16.0),
                          child: Column(
                            children: [
                              Row(
                                children: [
                                  Expanded(
                                    child: SalesOrderInformation(
                                      order: orderDetail,
                                    ),
                                  ),
                                  SpaceWidth(16),
                                  Expanded(
                                    child: SalesDetail(
                                      order: orderDetail,
                                    ),
                                  ),
                                ],
                              ),
                              SalesListOrder(
                                order: orderDetail,
                              ),
                              SalesPayment(
                                order: orderDetail,
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
