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

import 'package:on_field_work/controller/project_controller.dart';
import 'package:on_field_work/controller/expense/expense_screen_controller.dart';
import 'package:on_field_work/helpers/utils/date_time_utils.dart';
import 'package:on_field_work/helpers/widgets/my_spacing.dart';
import 'package:on_field_work/helpers/widgets/my_text.dart';
import 'package:on_field_work/model/expense/expense_list_model.dart';
import 'package:on_field_work/view/expense/expense_detail_screen.dart';
import 'package:on_field_work/helpers/widgets/my_confirmation_dialog.dart';
import 'package:on_field_work/helpers/utils/mixins/ui_mixin.dart';

class ExpenseAppBar extends StatelessWidget implements PreferredSizeWidget {
  final ProjectController projectController;

  const ExpenseAppBar({required this.projectController, super.key});

  @override
  Size get preferredSize => const Size.fromHeight(72);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      backgroundColor: const Color(0xFFF5F5F5),
      elevation: 0.5,
      automaticallyImplyLeading: false,
      titleSpacing: 0,
      title: Padding(
        padding: MySpacing.xy(16, 0),
        child: Row(
          children: [
            IconButton(
              icon: const Icon(Icons.arrow_back_ios_new,
                  color: Colors.black, size: 20),
              onPressed: () => Get.toNamed('/dashboard/finance'),
            ),
            MySpacing.width(8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  MyText.titleLarge('Expense & Reimbursement', fontWeight: 700),
                  MySpacing.height(2),
                  GetBuilder<ProjectController>(
                    builder: (_) {
                      final name = projectController.selectedProject?.name ??
                          'Select Project';
                      return Row(
                        children: [
                          const Icon(Icons.work_outline,
                              size: 14, color: Colors.grey),
                          MySpacing.width(4),
                          Expanded(
                            child: MyText.bodySmall(
                              name,
                              overflow: TextOverflow.ellipsis,
                              color: Colors.grey[700],
                              fontWeight: 600,
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class SearchAndFilter extends StatefulWidget {
  final TextEditingController controller;
  final ValueChanged<String> onChanged;
  final VoidCallback onFilterTap;
  final ExpenseController expenseController;

  const SearchAndFilter({
    required this.controller,
    required this.onChanged,
    required this.onFilterTap,
    required this.expenseController,
    super.key,
  });

  @override
  State<SearchAndFilter> createState() => _SearchAndFilterState();
}

class _SearchAndFilterState extends State<SearchAndFilter> with UIMixin {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: MySpacing.fromLTRB(12, 10, 12, 8),
      child: Row(
        children: [
          Expanded(
            child: SizedBox(
              height: 35,
              child: TextField(
                controller: widget.controller,
                onChanged: widget.onChanged,
                decoration: InputDecoration(
                  contentPadding: const EdgeInsets.symmetric(horizontal: 12),
                  prefixIcon:
                      const Icon(Icons.search, size: 20, color: Colors.grey),
                  hintText: 'Search expenses...',
                  filled: true,
                  fillColor: Colors.white,
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: BorderSide(color: Colors.grey.shade300),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide:
                        BorderSide(color: contentTheme.primary, width: 1.5),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(5),
                    borderSide: BorderSide(color: Colors.grey.shade300),
                  ),
                ),
              ),
            ),
          ),
          MySpacing.width(4),
          Obx(() {
            return IconButton(
              icon: Stack(
                clipBehavior: Clip.none,
                children: [
                  const Icon(Icons.tune, color: Colors.black),
                  if (widget.expenseController.isFilterApplied)
                    Positioned(
                      top: -1,
                      right: -1,
                      child: Container(
                        width: 10,
                        height: 10,
                        decoration: BoxDecoration(
                          color: Colors.red,
                          shape: BoxShape.circle,
                          border: Border.all(color: Colors.white, width: 1.5),
                        ),
                      ),
                    ),
                ],
              ),
              onPressed: widget.onFilterTap,
            );
          }),
        ],
      ),
    );
  }
}

class ToggleButtonsRow extends StatelessWidget {
  final bool isHistoryView;
  final ValueChanged<bool> onToggle;

  const ToggleButtonsRow({
    required this.isHistoryView,
    required this.onToggle,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: MySpacing.fromLTRB(8, 12, 8, 5),
      child: Container(
        padding: const EdgeInsets.all(2),
        decoration: BoxDecoration(
          color: const Color(0xFFF0F0F0),
          borderRadius: BorderRadius.circular(10),
        ),
        child: Row(
          children: [
            _ToggleButton(
              label: 'Expenses',
              icon: Icons.receipt_long,
              selected: !isHistoryView,
              onTap: () => onToggle(false),
            ),
            _ToggleButton(
              label: 'History',
              icon: Icons.history,
              selected: isHistoryView,
              onTap: () => onToggle(true),
            ),
          ],
        ),
      ),
    );
  }
}

class _ToggleButton extends StatelessWidget {
  final String label;
  final IconData icon;
  final bool selected;
  final VoidCallback onTap;

  const _ToggleButton({
    required this.label,
    required this.icon,
    required this.selected,
    required this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: GestureDetector(
        onTap: onTap,
        child: AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          padding: const EdgeInsets.symmetric(vertical: 6, horizontal: 10),
          decoration: BoxDecoration(
            color: selected ? Colors.red : Colors.transparent,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(icon,
                  size: 16, color: selected ? Colors.white : Colors.grey),
              const SizedBox(width: 6),
              MyText.bodyMedium(label,
                  color: selected ? Colors.white : Colors.grey,
                  fontWeight: 600),
            ],
          ),
        ),
      ),
    );
  }
}

class ExpenseList extends StatelessWidget {
  final List<ExpenseModel> expenseList;
  final Future<void> Function()? onViewDetail;

  const ExpenseList({
    required this.expenseList,
    this.onViewDetail,
    super.key,
  });

  void _showDeleteConfirmation(BuildContext context, ExpenseModel expense) {
    final ExpenseController controller = Get.find<ExpenseController>();

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => ConfirmDialog(
        title: "Delete Expense",
        message: "Are you sure you want to delete this draft expense?",
        confirmText: "Delete",
        cancelText: "Cancel",
        icon: Icons.delete_forever,
        confirmColor: Colors.redAccent,
        onConfirm: () async {
          await controller.deleteExpense(expense.id);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (expenseList.isEmpty && !Get.find<ExpenseController>().isLoading.value) {
      return Center(child: MyText.bodyMedium('No expenses found.'));
    }

    return SafeArea(
      bottom: true,
      child: ListView.separated(
        padding: const EdgeInsets.fromLTRB(12, 12, 12, 100),
        itemCount: expenseList.length,
        separatorBuilder: (_, __) =>
            Divider(color: Colors.grey.shade300, height: 20),
        itemBuilder: (context, index) {
          final expense = expenseList[index];
          final formattedDate = DateTimeUtils.convertUtcToLocal(
            expense.transactionDate.toIso8601String(),
            format: 'dd MMM yyyy',
          );

          return Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(8),
              onTap: () async {
                await Get.to(() => ExpenseDetailScreen(expenseId: expense.id));
              },
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        MyText.bodyMedium(expense.expenseCategory.name,
                            fontWeight: 600),
                        Row(
                          children: [
                            MyText.bodyMedium('${expense.formattedAmount}',
                                fontWeight: 600),
                            if (expense.status.name.toLowerCase() ==
                                'draft') ...[
                              const SizedBox(width: 8),
                              GestureDetector(
                                onTap: () =>
                                    _showDeleteConfirmation(context, expense),
                                child: const Icon(Icons.delete,
                                    color: Colors.red, size: 20),
                              ),
                            ],
                          ],
                        ),
                      ],
                    ),
                    const SizedBox(height: 6),
                    Row(
                      children: [
                        MyText.bodySmall(formattedDate, fontWeight: 500),
                        const Spacer(),
                        Container(
                          padding: const EdgeInsets.symmetric(
                              horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Color(int.parse(
                                    '0xff${expense.status.color.substring(1)}'))
                                .withOpacity(0.5),
                            borderRadius: BorderRadius.circular(5),
                          ),
                          child: MyText.bodySmall(
                            expense.status.name,
                            color: Colors.white,
                            fontWeight: 500,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
