import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:marco/controller/expense/expense_screen_controller.dart';
import 'package:marco/helpers/utils/base_bottom_sheet.dart';
import 'package:marco/helpers/utils/date_time_utils.dart';
import 'package:marco/helpers/widgets/my_spacing.dart';
import 'package:marco/helpers/widgets/my_text.dart';
import 'package:marco/helpers/widgets/my_text_style.dart';
import 'package:marco/model/employees/employee_model.dart';
import 'package:marco/model/expense/employee_selector_for_filter_bottom_sheet.dart';

class ExpenseFilterBottomSheet extends StatelessWidget {
  final ExpenseController expenseController;
  final ScrollController scrollController;

  const ExpenseFilterBottomSheet({
    super.key,
    required this.expenseController,
    required this.scrollController,
  });

  // FIX: create search adapter
  Future<List<EmployeeModel>> searchEmployeesForBottomSheet(
      String query) async {
    await expenseController
        .searchEmployees(query); // async method, returns void
    return expenseController.employeeSearchResults.toList();
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      return BaseBottomSheet(
        title: 'Filter Expenses',
        onCancel: () => Get.back(),
        onSubmit: () {
          expenseController.fetchExpenses();
          Get.back();
        },
        submitText: 'Submit',
        submitColor: Colors.indigo,
        submitIcon: Icons.check_circle_outline,
        child: SingleChildScrollView(
          controller: scrollController,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Align(
                alignment: Alignment.centerRight,
                child: TextButton(
                  onPressed: () => expenseController.clearFilters(),
                  child: MyText(
                    "Reset Filter",
                    style: MyTextStyle.labelMedium(
                      color: Colors.red,
                      fontWeight: 600,
                    ),
                  ),
                ),
              ),
              MySpacing.height(8),
              _buildProjectFilter(context),
              MySpacing.height(16),
              _buildStatusFilter(context),
              MySpacing.height(16),
              _buildDateRangeFilter(context),
              MySpacing.height(16),
              _buildPaidByFilter(context),
              MySpacing.height(16),
              _buildCreatedByFilter(context),
            ],
          ),
        ),
      );
    });
  }

  Widget _buildField(String label, Widget child) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        MyText.labelMedium(label),
        MySpacing.height(8),
        child,
      ],
    );
  }

  Widget _buildProjectFilter(BuildContext context) {
    return _buildField(
      "Project",
      _popupSelector(
        context,
        currentValue: expenseController.selectedProject.value.isEmpty
            ? 'Select Project'
            : expenseController.selectedProject.value,
        items: expenseController.globalProjects,
        onSelected: (value) => expenseController.selectedProject.value = value,
      ),
    );
  }

  Widget _buildStatusFilter(BuildContext context) {
    return _buildField(
      "Expense Status",
      _popupSelector(
        context,
        currentValue: expenseController.selectedStatus.value.isEmpty
            ? 'Select Expense Status'
            : expenseController.expenseStatuses
                    .firstWhereOrNull(
                        (e) => e.id == expenseController.selectedStatus.value)
                    ?.name ??
                'Select Expense Status',
        items: expenseController.expenseStatuses.map((e) => e.name).toList(),
        onSelected: (name) {
          final status = expenseController.expenseStatuses
              .firstWhere((e) => e.name == name);
          expenseController.selectedStatus.value = status.id;
        },
      ),
    );
  }

  Widget _buildDateRangeFilter(BuildContext context) {
    return _buildField(
      "Date Filter",
      Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Obx(() {
            return SizedBox(
              width: double.infinity, // Make it full width
              child: SegmentedButton<String>(
                segments: expenseController.dateTypes
                    .map(
                      (type) => ButtonSegment(
                        value: type,
                        label: Center(
                          // Center label text
                          child: MyText(
                            type,
                            style: MyTextStyle.bodySmall(
                              fontWeight: 600,
                              fontSize: 13,
                              height: 1.2,
                            ),
                          ),
                        ),
                      ),
                    )
                    .toList(),
                selected: {expenseController.selectedDateType.value},
                onSelectionChanged: (newSelection) {
                  if (newSelection.isNotEmpty) {
                    expenseController.selectedDateType.value =
                        newSelection.first;
                  }
                },
                style: ButtonStyle(
                  visualDensity:
                      const VisualDensity(horizontal: -2, vertical: -2),
                  padding: MaterialStateProperty.all(
                    const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
                  ),
                  backgroundColor: MaterialStateProperty.resolveWith(
                    (states) => states.contains(MaterialState.selected)
                        ? Colors.indigo.shade100
                        : Colors.grey.shade100,
                  ),
                  foregroundColor: MaterialStateProperty.resolveWith(
                    (states) => states.contains(MaterialState.selected)
                        ? Colors.indigo
                        : Colors.black87,
                  ),
                  shape: MaterialStateProperty.all(
                    RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  side: MaterialStateProperty.resolveWith(
                    (states) => BorderSide(
                      color: states.contains(MaterialState.selected)
                          ? Colors.indigo
                          : Colors.grey.shade300,
                      width: 1,
                    ),
                  ),
                ),
              ),
            );
          }),
          MySpacing.height(16),
          Row(
            children: [
              Expanded(
                child: _dateButton(
                  label: expenseController.startDate.value == null
                      ? 'Start Date'
                      : DateTimeUtils.formatDate(
                          expenseController.startDate.value!, 'dd MMM yyyy'),
                  onTap: () => _selectDate(
                    context,
                    expenseController.startDate,
                    lastDate: expenseController.endDate.value,
                  ),
                ),
              ),
              MySpacing.width(12),
              Expanded(
                child: _dateButton(
                  label: expenseController.endDate.value == null
                      ? 'End Date'
                      : DateTimeUtils.formatDate(
                          expenseController.endDate.value!, 'dd MMM yyyy'),
                  onTap: () => _selectDate(
                    context,
                    expenseController.endDate,
                    firstDate: expenseController.startDate.value,
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildPaidByFilter(BuildContext context) {
    return _buildField(
      "Paid By",
      _employeeSelector(
        context: context,
        selectedEmployees: expenseController.selectedPaidByEmployees,
        searchEmployees: searchEmployeesForBottomSheet, // FIXED
        title: 'Search Paid By',
      ),
    );
  }

  Widget _buildCreatedByFilter(BuildContext context) {
    return _buildField(
      "Created By",
      _employeeSelector(
        context: context,
        selectedEmployees: expenseController.selectedCreatedByEmployees,
        searchEmployees: searchEmployeesForBottomSheet, // FIXED
        title: 'Search Created By',
      ),
    );
  }

  Future<void> _selectDate(
    BuildContext context,
    Rx<DateTime?> dateNotifier, {
    DateTime? firstDate,
    DateTime? lastDate,
  }) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: dateNotifier.value ?? DateTime.now(),
      firstDate: firstDate ?? DateTime(2020),
      lastDate: lastDate ?? DateTime.now().add(const Duration(days: 365)),
    );
    if (picked != null && picked != dateNotifier.value) {
      dateNotifier.value = picked;
    }
  }

  Widget _popupSelector(
    BuildContext context, {
    required String currentValue,
    required List<String> items,
    required ValueChanged<String> onSelected,
  }) {
    return PopupMenuButton<String>(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      onSelected: onSelected,
      itemBuilder: (context) => items
          .map((e) => PopupMenuItem<String>(
                value: e,
                child: MyText(e),
              ))
          .toList(),
      child: Container(
        padding: MySpacing.all(12),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          border: Border.all(color: Colors.grey.shade300),
          borderRadius: BorderRadius.circular(12),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              child: MyText(
                currentValue,
                style: const TextStyle(color: Colors.black87),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const Icon(Icons.arrow_drop_down, color: Colors.grey),
          ],
        ),
      ),
    );
  }

  Widget _dateButton({required String label, required VoidCallback onTap}) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: MySpacing.xy(16, 12),
        decoration: BoxDecoration(
          color: Colors.grey.shade100,
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.grey.shade300),
        ),
        child: Row(
          children: [
            const Icon(Icons.calendar_today, size: 16, color: Colors.grey),
            MySpacing.width(8),
            Expanded(
              child: MyText(
                label,
                style: MyTextStyle.bodyMedium(),
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Future<void> _showEmployeeSelectorBottomSheet({
    required BuildContext context,
    required RxList<EmployeeModel> selectedEmployees,
    required Future<List<EmployeeModel>> Function(String) searchEmployees,
    String title = 'Select Employee',
  }) async {
    final List<EmployeeModel>? result =
        await showModalBottomSheet<List<EmployeeModel>>(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (context) => EmployeeSelectorBottomSheet(
        selectedEmployees: selectedEmployees,
        searchEmployees: searchEmployees,
        title: title,
      ),
    );
    if (result != null) {
      selectedEmployees.assignAll(result);
    }
  }

  Widget _employeeSelector({
    required BuildContext context,
    required RxList<EmployeeModel> selectedEmployees,
    required Future<List<EmployeeModel>> Function(String) searchEmployees,
    String title = 'Search Employee',
  }) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Obx(() {
          if (selectedEmployees.isEmpty) {
            return const SizedBox.shrink();
          }
          return Wrap(
            spacing: 8,
            children: selectedEmployees
                .map((emp) => Chip(
                      label: MyText(emp.name),
                      onDeleted: () => selectedEmployees.remove(emp),
                    ))
                .toList(),
          );
        }),
        MySpacing.height(8),
        GestureDetector(
          onTap: () => _showEmployeeSelectorBottomSheet(
            context: context,
            selectedEmployees: selectedEmployees,
            searchEmployees: searchEmployees,
            title: title,
          ),
          child: Container(
            padding: MySpacing.all(12),
            decoration: BoxDecoration(
              color: Colors.grey.shade100,
              borderRadius: BorderRadius.circular(12),
              border: Border.all(color: Colors.grey.shade300),
            ),
            child: Row(
              children: [
                const Icon(Icons.search, color: Colors.grey),
                MySpacing.width(8),
                Expanded(child: MyText(title)),
              ],
            ),
          ),
        ),
      ],
    );
  }
}
