import 'dart:developer';

import 'package:dropdown_search/dropdown_search.dart';
import 'package:enaklo_pos/core/components/buttons.dart';
import 'package:enaklo_pos/core/components/custom_modal_dialog.dart';
import 'package:enaklo_pos/core/components/flushbar.dart';
import 'package:enaklo_pos/core/components/spaces.dart';
import 'package:enaklo_pos/core/constants/colors.dart';
import 'package:enaklo_pos/core/extensions/build_context_ext.dart';
import 'package:enaklo_pos/data/models/response/customer_response_model.dart';
import 'package:enaklo_pos/data/models/response/table_model.dart';
import 'package:enaklo_pos/presentation/home/bloc/get_table_status/get_table_status_bloc.dart';
import 'package:enaklo_pos/presentation/home/bloc/order_form/order_form_bloc.dart';
import 'package:enaklo_pos/presentation/home/models/order_type.dart';
import 'package:enaklo_pos/presentation/home/models/product_quantity.dart';
import 'package:enaklo_pos/presentation/success/pages/success_save_order_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class PaymentSaveDialog extends StatefulWidget {
  final TableModel? selectedTable;
  final String customerName;
  final OrderType orderType;
  final List<ProductQuantity> items;
  final Customer? customer;
  const PaymentSaveDialog({
    super.key,
    required this.selectedTable,
    required this.customerName,
    required this.orderType,
    required this.items,
    required this.customer,
  });

  @override
  State<PaymentSaveDialog> createState() => _PaymentSaveDialogState();
}

class _PaymentSaveDialogState extends State<PaymentSaveDialog> {
  TableModel? selectTable;

  @override
  void initState() {
    super.initState();
    context
        .read<GetTableStatusBloc>()
        .add(GetTableStatusEvent.getTablesStatus('available'));
    if (widget.selectedTable != null) {
      selectTable = widget.selectedTable;
    }
  }

  @override
  Widget build(BuildContext context) {
    return CustomModalDialog(
      title: 'Bayar Nanti',
      subtitle: 'Simpan pesanan dan bayar nanti',
      contentPadding:
          const EdgeInsets.symmetric(horizontal: 16.0, vertical: 24.0),
      minWidth: context.deviceWidth * 0.4,
      minHeight: context.deviceHeight * 0.4,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                'Pilih Meja',
                style: TextStyle(
                  color: AppColors.black,
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SpaceHeight(6.0),
              BlocBuilder<GetTableStatusBloc, GetTableStatusState>(
                  builder: (context, state) {
                return state.maybeWhen(
                  orElse: () =>
                      Center(child: const CircularProgressIndicator()),
                  loading: () =>
                      Center(child: const CircularProgressIndicator()),
                  success: (tables) {
                    final availableTables = tables;

                    if (selectTable == null && availableTables.isNotEmpty) {
                      selectTable = availableTables.first;
                    }

                    if (availableTables.isEmpty) {
                      return Container(
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          color: Colors.orange[50],
                          borderRadius: BorderRadius.circular(16),
                          border: Border.all(
                            color: Colors.orange,
                            width: 1,
                          ),
                        ),
                        child: const Text(
                          'Tidak ada meja yang tersedia. Silakan pilih opsi lain.',
                          style: TextStyle(color: Colors.orange),
                        ),
                      );
                    }

                    return DropdownSearch<TableModel>(
                      items: tables,
                      selectedItem: selectTable,

                      // 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, category, 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(
                                    category.tableName ?? "",
                                    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: (TableModel table) => table.tableName ?? "",

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

                      // On changed callback
                      onChanged: (TableModel? selectedTable) {
                        if (selectedTable != null) {
                          setState(() {
                            selectTable = selectedTable;
                          });
                          log("selectTable: ${selectTable!.tableName}");
                        }
                      },

                      // Validator (optional)
                      validator: (TableModel? value) {
                        if (value == null) {
                          return "Meja harus dipilih";
                        }
                        return null;
                      },
                    );
                  },
                );
              }),
            ],
          ),
          SpaceHeight(24),
          BlocListener<OrderFormBloc, OrderFormState>(
            listener: (context, state) {
              state.maybeWhen(
                orElse: () {},
                success: (data) {
                  context.pop();
                  context.pushReplacement(SuccessSaveOrderPage(
                    productQuantity: widget.items,
                    orderId: data.id ?? "",
                  ));
                },
                error: (message) => AppFlushbar.showError(context, message),
              );
            },
            child: BlocBuilder<OrderFormBloc, OrderFormState>(
              builder: (context, state) {
                return state.maybeWhen(
                  orElse: () => Button.filled(
                    onPressed: () {
                      context.read<OrderFormBloc>().add(
                            OrderFormEvent.create(
                              items: widget.items,
                              customerName: widget.customerName,
                              orderType: widget.orderType,
                              table: selectTable!,
                              customer: widget.customer,
                            ),
                          );
                    },
                    label: "Simpan",
                  ),
                  loading: () => Center(
                    child: const CircularProgressIndicator(),
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}
