import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:mobile_pos/Provider/all_expanse_provider.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/income_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../GlobalComponents/button_global.dart';
import '../../const_commas.dart';
import '../../constant.dart';
import '../../currency.dart';
import 'add_income.dart';

/// ---------- SAFE HELPERS ----------
DateTime? safeParseDate(String? dateStr) {
  if (dateStr == null || dateStr.isEmpty) return null;
  try {
    return DateTime.tryParse(dateStr);
  } catch (_) {
    return null;
  }
}

double safeParseAmount(String? amount) {
  if (amount == null || amount.isEmpty) return 0;
  return double.tryParse(amount) ?? 0;
}

class IncomeList extends StatefulWidget {
  const IncomeList({super.key});

  @override
  _IncomeListState createState() => _IncomeListState();
}

class _IncomeListState extends State<IncomeList> {
  final dateController = TextEditingController();
  TextEditingController fromDateTextEditingController =
      TextEditingController(text: DateFormat.yMMMd().format(DateTime(2021)));
  TextEditingController toDateTextEditingController =
      TextEditingController(text: DateFormat.yMMMd().format(DateTime.now()));

  DateTime fromDate = DateTime(2021);
  DateTime toDate = DateTime.now();
  double totalIncome = 0;

  @override
  void dispose() {
    dateController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Consumer(builder: (context, ref, __) {
      final incomeData = ref.watch(incomeProvider);

      return Scaffold(
        backgroundColor: kMainColor,
        appBar: AppBar(
          backgroundColor: kMainColor,
          title: Text(
            'Income Report',
            style: GoogleFonts.poppins(
              color: Colors.white,
              fontSize: 20.0,
            ),
          ),
          iconTheme: const IconThemeData(color: Colors.white),
          centerTitle: true,
          elevation: 0.0,
        ),
        body: Container(
          alignment: Alignment.topCenter,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
              topRight: Radius.circular(30),
              topLeft: Radius.circular(30),
            ),
          ),
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                children: [
                  /// ----------- Date Pickers -----------
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
                    child: Row(
                      children: [
                        Expanded(
                          child: AppTextField(
                            textFieldType: TextFieldType.NAME,
                            readOnly: true,
                            controller: fromDateTextEditingController,
                            decoration: InputDecoration(
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              labelText: lang.S.of(context).formDate,
                              border: const OutlineInputBorder(),
                              suffixIcon: IconButton(
                                onPressed: () async {
                                  final DateTime? picked = await showDatePicker(
                                    initialDate: fromDate,
                                    firstDate: DateTime(2015, 8),
                                    lastDate: DateTime(2101),
                                    context: context,
                                  );
                                  if (picked != null) {
                                    setState(() {
                                      fromDateTextEditingController.text =
                                          DateFormat.yMMMd().format(picked);
                                      fromDate = picked;
                                      totalIncome = 0;
                                    });
                                  }
                                },
                                icon: const Icon(FeatherIcons.calendar),
                              ),
                            ),
                          ),
                        ),
                        const SizedBox(width: 10),
                        Expanded(
                          child: AppTextField(
                            textFieldType: TextFieldType.NAME,
                            readOnly: true,
                            controller: toDateTextEditingController,
                            decoration: InputDecoration(
                              floatingLabelBehavior: FloatingLabelBehavior.always,
                              labelText: lang.S.of(context).toDate,
                              border: const OutlineInputBorder(),
                              suffixIcon: IconButton(
                                onPressed: () async {
                                  final DateTime? picked = await showDatePicker(
                                    initialDate: toDate,
                                    firstDate: DateTime(2015, 8),
                                    lastDate: DateTime(2101),
                                    context: context,
                                  );
                                  if (picked != null) {
                                    setState(() {
                                      toDateTextEditingController.text =
                                          DateFormat.yMMMd().format(picked);
                                      toDate = picked.isToday ? DateTime.now() : picked;
                                      totalIncome = 0;
                                    });
                                  }
                                },
                                icon: const Icon(FeatherIcons.calendar),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 20),

                  /// ----------- Income Data Table -----------
                  incomeData.when(
                    data: (mainData) {
                      if (mainData.isNotEmpty) {
                        final List<IncomeModel> data = mainData.reversed.toList();
                        totalIncome = 0;

                        /// Calculate Total Income
                        for (var element in data) {
                          final incomeDate = safeParseDate(element.incomeDate);
                          final amount = safeParseAmount(element.amount);

                          if (incomeDate != null &&
                              (fromDate.isBefore(incomeDate) ||
                                  incomeDate.isAtSameMomentAs(fromDate)) &&
                              (toDate.isAfter(incomeDate) ||
                                  incomeDate.isAtSameMomentAs(toDate))) {
                            totalIncome += amount;
                          }
                        }

                        return SingleChildScrollView(
                          scrollDirection: Axis.horizontal,
                          child: DataTable(
                            headingRowColor: WidgetStateColor.resolveWith(
                                (states) => kMainColor.withValues(alpha: 0.2)),
                            border: TableBorder.all(color: kBorderColorTextField, width: 0.5),
                            columns: <DataColumn>[
                              const DataColumn(label: Text('Income For')),
                              DataColumn(label: Text(lang.S.of(context).date)),
                              DataColumn(
                                label: Text(
                                  lang.S.of(context).amount,
                                  overflow: TextOverflow.ellipsis,
                                  maxLines: 2,
                                ),
                              ),
                            ],
                            rows: List.generate(
                              data.length,
                              (index) {
                                final incomeDate = safeParseDate(data[index].incomeDate);
                                final amount = safeParseAmount(data[index].amount);

                                return DataRow(
                                  cells: [
                                    /// Income For + Category
                                    DataCell(
                                      Padding(
                                        padding: const EdgeInsets.only(top: 4),
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: [
                                            Text(
                                              data[index].incomeFor,
                                              maxLines: 2,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            const SizedBox(height: 2),
                                            Text(
                                              data[index].category.isEmpty
                                                  ? lang.S.of(context).notProvided
                                                  : data[index].category,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                              style: const TextStyle(
                                                color: Colors.grey,
                                                fontSize: 11,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),

                                    /// Date
                                    DataCell(
                                      Text(
                                        incomeDate != null
                                            ? DateFormat.yMMMd().format(incomeDate)
                                            : lang.S.of(context).notProvided,
                                        style: GoogleFonts.poppins(),
                                      ),
                                    ),

                                    /// Amount
                                    DataCell(
                                      Text(
                                        '$currency${myFormat.format(amount)}',
                                        style: GoogleFonts.poppins(),
                                      ),
                                    ),
                                  ],
                                );
                              },
                            ),
                          ),
                        );
                      } else {
                        return Padding(
                          padding: const EdgeInsets.all(20),
                          child: Center(
                            child: Text(lang.S.of(context).noDataAvailable),
                          ),
                        );
                      }
                    },
                    error: (Object error, StackTrace? stackTrace) {
                      return Text(error.toString());
                    },
                    loading: () {
                      return const Center(child: CircularProgressIndicator());
                    },
                  ),
                ],
              ),
            ),
          ),
        ),

        /// ----------- Bottom Total + Add Button -----------
        bottomNavigationBar: Container(
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(10.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  height: 50,
                  padding: const EdgeInsets.all(10),
                  decoration: const BoxDecoration(color: kDarkWhite),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const Text('Total Income'),
                      Text('$currency${myFormat.format(totalIncome)}'),
                    ],
                  ),
                ),
                ButtonGlobalWithoutIcon(
                  buttontext: 'Add Income',
                  buttonDecoration: kButtonDecoration.copyWith(color: kMainColor),
                  onPressed: () async {
                    if (await checkUserRolePermission(type: "income-create")) {
                      const AddIncome().launch(context);
                    }
                  },
                  buttonTextColor: Colors.white,
                ),
              ],
            ),
          ),
        ),
      );
    });
  }
}
