import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

import 'package:marco/controller/expense/expense_detail_controller.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/helpers/utils/base_bottom_sheet.dart';
import 'package:marco/helpers/widgets/my_snackbar.dart';


class ReimbursementBottomSheet extends StatefulWidget {
  final String expenseId;
  final String statusId;
  final void Function() onClose;
  final Future<bool> Function({
    required String comment,
    required String reimburseTransactionId,
    required String reimburseDate,
    required String reimburseById,
    required String statusId,
  }) onSubmit;

  const ReimbursementBottomSheet({
    super.key,
    required this.expenseId,
    required this.onClose,
    required this.onSubmit,
    required this.statusId,
  });

  @override
  State<ReimbursementBottomSheet> createState() =>
      _ReimbursementBottomSheetState();
}

class _ReimbursementBottomSheetState extends State<ReimbursementBottomSheet> {
  final ExpenseDetailController controller =
      Get.find<ExpenseDetailController>();

  final TextEditingController commentCtrl = TextEditingController();
  final TextEditingController txnCtrl = TextEditingController();
  final RxString dateStr = ''.obs;

  @override
  void dispose() {
    commentCtrl.dispose();
    txnCtrl.dispose();
    super.dispose();
  }

  void _showEmployeeList() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (_) {
        return SizedBox(
          height: 300,
          child: Obx(() {
            final employees = controller.allEmployees;
            if (employees.isEmpty) {
              return const Center(child: Text("No employees found"));
            }
            return ListView.builder(
              itemCount: employees.length,
              itemBuilder: (_, index) {
                final emp = employees[index];
                final fullName = '${emp.firstName} ${emp.lastName}'.trim();
                return ListTile(
                  title: Text(fullName.isNotEmpty ? fullName : "Unnamed"),
                  onTap: () {
                    controller.selectedReimbursedBy.value = emp;
                    Navigator.pop(context);
                  },
                );
              },
            );
          }),
        );
      },
    );
  }

  InputDecoration _inputDecoration(String hint) {
    return InputDecoration(
      hintText: hint,
      hintStyle: MyTextStyle.bodySmall(xMuted: true),
      filled: true,
      fillColor: Colors.grey.shade100,
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: BorderSide(color: Colors.grey.shade300),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(12),
        borderSide: const BorderSide(color: Colors.blueAccent, width: 1.5),
      ),
      contentPadding: MySpacing.all(16),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Obx(() {
      return BaseBottomSheet(
        title: "Reimbursement Info",
        isSubmitting: controller.isLoading.value,
        onCancel: () {
          widget.onClose();
          Navigator.pop(context);
        },
        onSubmit: () async {
          if (commentCtrl.text.trim().isEmpty ||
              txnCtrl.text.trim().isEmpty ||
              dateStr.value.isEmpty ||
              controller.selectedReimbursedBy.value == null) {
            showAppSnackbar(
              title: "Incomplete",
              message: "Please fill all fields",
              type: SnackbarType.warning,
            );
            return;
          }

          final success = await widget.onSubmit(
            comment: commentCtrl.text.trim(),
            reimburseTransactionId: txnCtrl.text.trim(),
            reimburseDate: dateStr.value,
            reimburseById: controller.selectedReimbursedBy.value!.id,
            statusId: widget.statusId,
          );

          if (success) {
            Get.back();
            showAppSnackbar(
              title: "Success",
              message: "Reimbursement submitted",
              type: SnackbarType.success,
            );
          } else {
            showAppSnackbar(
              title: "Error",
              message: controller.errorMessage.value,
              type: SnackbarType.error,
            );
          }
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            MyText.labelMedium("Comment"),
            MySpacing.height(8),
            TextField(
              controller: commentCtrl,
              decoration: _inputDecoration("Enter comment"),
            ),
            MySpacing.height(16),
            MyText.labelMedium("Transaction ID"),
            MySpacing.height(8),
            TextField(
              controller: txnCtrl,
              decoration: _inputDecoration("Enter transaction ID"),
            ),
            MySpacing.height(16),
            MyText.labelMedium("Reimbursement Date"),
            MySpacing.height(8),
            GestureDetector(
              onTap: () async {
                final picked = await showDatePicker(
                  context: context,
                  initialDate: dateStr.value.isEmpty
                      ? DateTime.now()
                      : DateFormat('yyyy-MM-dd').parse(dateStr.value),
                  firstDate: DateTime(2020),
                  lastDate: DateTime(2100),
                );
                if (picked != null) {
                  dateStr.value = DateFormat('yyyy-MM-dd').format(picked);
                }
              },
              child: AbsorbPointer(
                child: TextField(
                  controller: TextEditingController(text: dateStr.value),
                  decoration: _inputDecoration("Select Date").copyWith(
                    suffixIcon: const Icon(Icons.calendar_today),
                  ),
                ),
              ),
            ),
            MySpacing.height(16),
            MyText.labelMedium("Reimbursed By"),
            MySpacing.height(8),
            GestureDetector(
              onTap: _showEmployeeList,
              child: AbsorbPointer(
                child: TextField(
                  controller: TextEditingController(
                    text: controller.selectedReimbursedBy.value == null
                        ? ""
                        : '${controller.selectedReimbursedBy.value?.firstName ?? ''} ${controller.selectedReimbursedBy.value?.lastName ?? ''}',
                  ),
                  decoration: _inputDecoration("Select Employee").copyWith(
                    suffixIcon: const Icon(Icons.expand_more),
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    });
  }
}
