import 'package:dropdown_search/dropdown_search.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../../../../application/checkout/checkout_form/checkout_form_bloc.dart';
import '../../../../application/order/order_form/order_form_bloc.dart';
import '../../../../application/order/order_loader/order_loader_bloc.dart';
import '../../../../common/theme/theme.dart';
import '../../../../domain/order/order.dart';
import '../../button/button.dart';
import '../../loader/loader_with_text.dart';
import '../../spaces/space.dart';
import '../dialog.dart';

class OrderAddItemDialog extends StatefulWidget {
  final CheckoutFormState checkoutState;
  const OrderAddItemDialog({super.key, required this.checkoutState});

  @override
  State<OrderAddItemDialog> createState() => _OrderAddItemDialogState();
}

class _OrderAddItemDialogState extends State<OrderAddItemDialog> {
  Order? selectedOrder;

  @override
  void initState() {
    super.initState();
    context.read<OrderLoaderBloc>().add(
      const OrderLoaderEvent.fetched(status: 'pending', isRefresh: true),
    );
  }

  @override
  Widget build(BuildContext context) {
    return CustomModalDialog(
      title: 'Tambah Pesanan',
      subtitle: 'Silahkan tambahkan pesanan ke pesanan yang sudah ada',
      contentPadding: const EdgeInsets.symmetric(
        horizontal: 16.0,
        vertical: 24.0,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Pilih Meja yang sudah dipesan',
            style: AppStyle.lg.copyWith(fontWeight: FontWeight.w600),
          ),
          const SpaceHeight(8.0),
          BlocBuilder<OrderLoaderBloc, OrderLoaderState>(
            builder: (context, state) {
              if (state.isFetching) {
                return const Center(child: LoaderWithText());
              }

              final availableOrders = state.orders;

              if (selectedOrder == null && availableOrders.isNotEmpty) {
                selectedOrder = availableOrders.first;
              }

              if (availableOrders.isEmpty) {
                return Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: AppColor.warning.withOpacity(0.1),
                    borderRadius: BorderRadius.circular(16),
                    border: Border.all(color: AppColor.warning, width: 1),
                  ),
                  child: Text(
                    'Tidak ada meja yang tersedia. Silakan pilih opsi lain.',
                    style: AppStyle.md.copyWith(color: AppColor.warning),
                  ),
                );
              }

              return DropdownSearch<Order>(
                items: state.orders,
                selectedItem: selectedOrder,

                // Dropdown properties
                dropdownDecoratorProps: DropDownDecoratorProps(
                  dropdownSearchDecoration: InputDecoration(
                    hintText: "Pilih Meja",
                    hintStyle: TextStyle(
                      color: Colors.grey.shade600,
                      fontSize: 14,
                    ),
                    prefixIcon: Icon(
                      Icons.category_outlined,
                      color: Colors.grey.shade500,
                      size: 20,
                    ),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide(
                        color: Colors.grey.shade300,
                        width: 1.5,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide(
                        color: Colors.grey.shade300,
                        width: 1.5,
                      ),
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide(
                        color: Colors.blue.shade400,
                        width: 2,
                      ),
                    ),
                    filled: true,
                    fillColor: Colors.white,
                    contentPadding: const EdgeInsets.symmetric(
                      horizontal: 16,
                      vertical: 16,
                    ),
                  ),
                ),

                // Popup properties
                popupProps: PopupProps.menu(
                  showSearchBox: true,
                  searchFieldProps: TextFieldProps(
                    decoration: InputDecoration(
                      hintText: "Cari meja...",
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                    ),
                  ),
                  menuProps: MenuProps(
                    backgroundColor: Colors.white,
                    elevation: 8,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  itemBuilder: (context, order, isSelected) {
                    return Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 12,
                      ),
                      decoration: BoxDecoration(
                        color: isSelected
                            ? Colors.blue.shade50
                            : Colors.transparent,
                        border: Border(
                          bottom: BorderSide(
                            color: Colors.grey.shade100,
                            width: 0.5,
                          ),
                        ),
                      ),
                      child: Row(
                        children: [
                          Container(
                            width: 8,
                            height: 8,
                            decoration: BoxDecoration(
                              color: isSelected
                                  ? Colors.blue.shade600
                                  : Colors.grey.shade400,
                              shape: BoxShape.circle,
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              "${order.tableNumber} - ${order.metadata['customer_name']}",
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: isSelected
                                    ? FontWeight.w600
                                    : FontWeight.w500,
                                color: isSelected
                                    ? Colors.blue.shade700
                                    : Colors.black87,
                              ),
                            ),
                          ),
                          if (isSelected)
                            Icon(
                              Icons.check,
                              color: Colors.blue.shade600,
                              size: 18,
                            ),
                        ],
                      ),
                    );
                  },
                  emptyBuilder: (context, searchEntry) {
                    return Container(
                      padding: const EdgeInsets.all(20),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Icon(
                            Icons.search_off,
                            color: Colors.grey.shade400,
                            size: 48,
                          ),
                          const SizedBox(height: 12),
                          Text(
                            searchEntry.isEmpty
                                ? "Tidak ada meja tersedia"
                                : "Tidak ditemukan meja dengan '$searchEntry'",
                            style: TextStyle(
                              color: Colors.grey.shade600,
                              fontSize: 14,
                            ),
                            textAlign: TextAlign.center,
                          ),
                        ],
                      ),
                    );
                  },
                ),

                // Item as string (for search functionality)
                itemAsString: (Order order) =>
                    "${order.tableNumber} - ${order.metadata['customer_name']}",

                // Comparison function
                compareFn: (Order? item1, Order? item2) {
                  return item1?.id == item2?.id;
                },

                // On changed callback
                onChanged: (Order? selectedOrder) {
                  if (selectedOrder != null) {
                    context.read<CheckoutFormBloc>().add(
                      CheckoutFormEvent.orderAddedItems(selectedOrder),
                    );
                    setState(() {
                      this.selectedOrder = selectedOrder;
                    });
                  }
                },

                // Validator (optional)
                validator: (Order? value) {
                  if (value == null) {
                    return "Meja harus dipilih";
                  }
                  return null;
                },
              );
            },
          ),
          const SpaceHeight(16),
          BlocBuilder<OrderFormBloc, OrderFormState>(
            builder: (context, state) {
              return AppElevatedButton.filled(
                isLoading: state.isAddingItemOrder,
                onPressed: state.isAddingItemOrder
                    ? null
                    : () {
                        context.read<OrderFormBloc>().add(
                          OrderFormEvent.addItemOrder(
                            orderId: selectedOrder?.id ?? '',
                            items: widget.checkoutState.items,
                          ),
                        );
                      },
                label: 'Simpan',
              );
            },
          ),
        ],
      ),
    );
  }
}
