import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:nhance_partner/data/utils/toastNotification.dart';

import '../../../core/routing/routes.dart';
import '../../../core/services/api_service.dart';
import '../../../data/utils/Pagination.dart';
import '../../layouts/main_layout.dart';
import '../../layouts/responsive_layout.dart';
import '../../providers/manager_provider.dart';
import '../../providers/userRoleProvider.dart';
import '../../themes/indicators/export_btn.dart';
import '../../themes/indicators/search_field_theme.dart';
import '../../widgets/custom_Stdate_EnDate_Filter.dart';

class InvoiceList extends ConsumerStatefulWidget {
  const InvoiceList({super.key});

  @override
  ConsumerState<InvoiceList> createState() => _InvoiceListState();
}

class _InvoiceListState extends ConsumerState<InvoiceList> {
  int currentPage = 1;
  int itemsPerPage = 10;
  bool isLoading = false;
  List<Map<String, dynamic>> getInvoiceData = [];
  List<Map<String, dynamic>> originalData = [];
  List<Map<String, dynamic>> filteredData = [];
  dynamic roleId;
  dynamic userId;
  late ApiService apiService;
  final _formKey = GlobalKey<FormState>();
  Map<String, TextEditingController> controllers = {};
  List<String> tabHeader = ['startDate', 'endDate'];
  dynamic SelectedStatus;
  dynamic SelectedStaffId;

  @override
  void initState() {
    super.initState();
    apiService = ApiService();
    for (String field in tabHeader) {
      controllers[field] = TextEditingController();
    }

    Future.microtask(() {
      final id = ref.read(managerIdProvider);
      roleId = ref.read(userRoleProvider);
      userId = ref.read(userIdProvider);

      print("D49 => r : $roleId | mId: $id | uId: $userId ");
      getInvoiceList();
    });
  }

  // Get Broker List
  Future<void> getInvoiceList() async {
    print('getBroker called');
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.getInvoiceList();

      if (response['status'] == 'success') {
        print('getInvoiceList - ${response['data']}');
        final data = response['data'];
        print('D81 => getInvoiceList => ${response['data']}');

        // final fromDate = response['from_date'] ?? '';
        // final toDate = response['to_date'] ?? '';
        //
        // print('FromDate : $fromDate');
        // print('ToDate : $toDate');
        setState(() {
          // controllers['startDate']?.text = fromDate;
          // controllers['endDate']?.text = toDate;
          if (data is List) {
            // Already a list of maps
            getInvoiceData = List<Map<String, dynamic>>.from(data);
          } else if (data is Map) {
            // Single object, wrap in a list
            getInvoiceData = [Map<String, dynamic>.from(data)];
          } else {
            getInvoiceData = [];
          }
          originalData = getInvoiceData;
          filteredData = List.from(originalData);
        });
      } else {
        originalData = [];
        filteredData = [];
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  // Delete Invoice List
  Future<void> deleteInvoice(ID) async {
    setState(() {
      isLoading = true;
    });

    try {
      final response = await apiService.deleteInvoice(ID);

      if (response['status'] == 'success') {
        ToastHelper.showSuccessToast(context, response['data']);
        getInvoiceList();
      } else {
        ToastHelper.showSuccessToast(context, response['data']);
      }
    } catch (e) {
      print('Exception occurred: $e');
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  List<dynamic> get _paginatedData {
    // Sort descending by id first
    final sortedData = [...filteredData]
      ..sort((a, b) => int.parse(b['id']) - int.parse(a['id']));

    if (sortedData.isEmpty) return [];

    // Ensure currentPage is valid
    final maxPage = (sortedData.length / itemsPerPage).ceil();
    final safePage = currentPage.clamp(1, maxPage);

    final startIndex = (safePage - 1) * itemsPerPage;
    final endIndex = (startIndex + itemsPerPage).clamp(0, sortedData.length);

    return sortedData.sublist(startIndex, endIndex);
  }

  void filterDateRange() {}

  void refrshfilterDateRange() {
    setState(() {
      // SelectedStaffId = null;
      controllers['startDate']!.clear();
      controllers['endDate']!.clear();

      controllers['startDate']?.text = '';
      controllers['endDate']?.text = '';
      // Reset the FormField validation
      _formKey.currentState?.reset();
    });
    getInvoiceList();
  }

  void filterData(String query) {
    print("FilterDAta - $query");
    setState(() {
      filteredData = getInvoiceData.where((item) {
        // final isActiveStatus = item['is_active'] == "1" ? "active" : "inactive";

        return (_formatDate(item['updated_at']) ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (_formatDate(item['invoice_date']) ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['invoice_no'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['invoice_amount_indian_format'] ?? '-')
                .toLowerCase()
                .contains(query.toLowerCase()) ||
            (item['broker_name'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['pos_name'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            ) ||
            (item['payout_status'] ?? '-').toLowerCase().contains(
              query.toLowerCase(),
            )
        // ||
        // (item['status'] ?? '-').toLowerCase().contains(query.toLowerCase());
        ;
      }).toList();
    });
  }

  final TextEditingController _searchStaffController = TextEditingController();

  String _formatDateTime(String rawDate) {
    try {
      final dateTime = DateTime.parse(rawDate);
      return DateFormat('dd-MM-yyyy  HH:mm').format(dateTime); // 24-hour format
    } catch (e) {
      return rawDate; // fallback if parsing fails
    }
  }

  String _formatDate(String rawDate) {
    try {
      final dateTime = DateTime.parse(rawDate);
      return DateFormat('dd-MM-yyyy').format(dateTime); // 24-hour format
    } catch (e) {
      return rawDate; // fallback if parsing fails
    }
  }

  @override
  Widget build(BuildContext context) {
    return MainLayout(
      title: "Pay Out",
      body: SelectionArea(
        child: Container(
        // height: 30,
        // color: Colors.yellow.shade50,
        width: MediaQuery.of(context).size.width,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            // Container(
            //   height: 30,
            //   width: MediaQuery.of(context).size.width,
            //   child: GestureDetector(
            //     onTap: () {
            //       context.go(AppRoutes.dashboard);
            //     },
            //     child: Row(
            //       crossAxisAlignment: CrossAxisAlignment.center,
            //       mainAxisAlignment: MainAxisAlignment.start,
            //       children: [
            //         // Tooltip(
            //         //   message: 'Back',
            //         //   child: IconButton(
            //         //     icon: const Icon(
            //         //       Icons.arrow_left_sharp,
            //         //       size: 25,
            //         //       color: Color(0xFF425B5B),
            //         //     ),
            //         //     onPressed: () {
            //         //       context.go(AppRoutes.dashboard);
            //         //     },
            //         //     splashRadius: 18,
            //         //     hoverColor: Colors.black12,
            //         //     padding: const EdgeInsets.all(4),
            //         //     constraints: const BoxConstraints(),
            //         //   ),
            //         // ),
            //         // const SizedBox(width: 5), // spacing between icon and text
            //         Text(
            //           "Invoice",
            //           style: GoogleFonts.inter(
            //             fontSize: 14,
            //             fontWeight: FontWeight.w500,
            //           ),
            //         ),
            //       ],
            //     ),
            //   ),
            // ),
            //
            // SizedBox(height: 5),
            Expanded(
              child: Container(
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.all(8.0),
                child: _buildContent(context),
              ),
            ),

            Container(
              // height: 20,
              width: MediaQuery.of(context).size.width,
              // color: Colors.green.shade50,
              child: PaginationControls(
                currentPage: currentPage,
                itemsPerPage: itemsPerPage,
                // totalItems: dataVal.length,
                totalItems: filteredData.length,
                // activeColor: layoutColor, // your theme color
                onPageChanged: (page) {
                  setState(() {
                    currentPage = page;
                  });
                },
                onItemsPerPageChanged: (items) {
                  setState(() {
                    itemsPerPage = items;
                    currentPage = 1;
                  });
                },
              ),
            ),
          ],
        ),
      ) ,) ,
    );
  }

  Widget _buildContent(BuildContext context) {
    return Column(
      children: [
        Container(
          // height: 40,
          // color: Colors.pink,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Text(
                "Invoice",
                style: GoogleFonts.poppins(
                  fontSize: 14,
                  fontWeight: FontWeight.w400,
                ),
              ),

              Spacer(),
              ThemedSearchField(
                hintText: 'Search',
                // backgroundColor: Color(0xFFF6F8F8),
                onChanged: filterData,
                controller: _searchStaffController,
                txtHeight: 30,
                txtwidth: ResponsiveLayout.isMobile(context)
                    ? MediaQuery.of(context).size.width * 0.7
                    : MediaQuery.of(context).size.width * 0.15,
              ),
              SizedBox(width: 10),
              Tooltip(
                message: 'Raise Invoice',
                child: InkWell(
                  onTap: () async {
                    context.go(AppRoutes.payout);
                  },
                  child: Container(
                    padding: const EdgeInsets.all(4.0),
                    decoration: BoxDecoration(
                      color: const Color(0xFF2E7D6E),
                      // color: const Color(0xFF425B5B),
                      borderRadius: BorderRadius.circular(8.0),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        // Image.asset(
                        //   "assets/miscellaneous/export.png",
                        //   height: 25,
                        //   width: 25,
                        // ),
                        Icon(Icons.add, color: Colors.white, size: 18),
                        // Image.asset("assets/miscellaneous/export", height: 15, width: 15),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(width: 10),
              ExportBtn(
                sheetName: "Invoice",
                fileName: "Invoice_List",
                data: filteredData,
                txt: true,
                displayHeaders: [
                  "Invoice No",
                  "Invoice Date",
                  "Invoice Amount",
                  "Broker ",
                  "POS ",
                  "Status ",
                  "Updated Date",
                ],
                keys: [
                  "invoice_date",
                  "invoice_no",
                  "invoice_amount_indian_format",
                  "broker_name",
                  "pos_name",
                  "payout_status",
                  "updated_at",
                ],
              ),
            ],
          ),
        ),
        SizedBox(height: 5),
        Container(
          decoration: BoxDecoration(
            color: Color(0xFFF1F5F9),
            borderRadius: BorderRadius.circular(6),
          ),
          padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16),
          child: Row(
            children: [
              Expanded(flex: 3, child: Text('Invoice No', style: _headerStyle)),
              Expanded(
                flex: 2,
                child: Text('Invoice Date', style: _headerStyle),
              ),
              Expanded(
                flex: 2,
                child: Text('Invoice Amount', style: _headerStyle),
              ),
              Expanded(
                flex: 2,
                child: Text('Broker Name', style: _headerStyle),
              ),
              Expanded(flex: 2, child: Text('POS Name', style: _headerStyle)),
              Expanded(flex: 2, child: Text('Status', style: _headerStyle)),
              Expanded(
                flex: 2,
                child: Text('Updated Date', style: _headerStyle),
              ),
              Expanded(flex: 2, child: Text('Action', style: _headerStyle)),
            ],
          ),
        ),

        Expanded(child: _buildDataTable(context)),
      ],
    );
  }

  Widget _buildDataTable(BuildContext context) {
    if (filteredData.isEmpty) {
      return const SizedBox(
        height: 50,
        child: Center(child: Text('No available data')),
      );
    }

    final sortedData = [..._paginatedData];

    // Desktop: keep ListView.builder
    return ListView.builder(
      itemCount: sortedData.length + 1,
      itemBuilder: (context, index) {
        if (index == 0) return _buildHeader();
        final startIndex = (currentPage - 1) * itemsPerPage;
        final item = sortedData[index - 1];
        final sno = startIndex + index;
        return _buildDataRow(item, sno);
      },
    );
  }

  Widget _buildHeader() {
    return SizedBox.shrink();
  }

  Widget _buildDataRow(Map<String, dynamic> item, sno) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 16),
      // margin: const EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
        color: Colors.white,
        // color: Color(0xFFE0F7F9),
        border: const Border(
          bottom: BorderSide(color: Color(0xFFEAEAEA), width: 1),
        ),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Expanded(
            flex: 3,
            child: Text(item['invoice_no'] ?? '-', style: _dataBold),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['invoice_date'] != null
                  ? _formatDate(item['invoice_date'])
                  : '-',
              style: _dataBold,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['invoice_amount_indian_format'] ?? '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['broker_name'] != null ? item['broker_name'] : '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              item['pos_name'] != null ? item['pos_name'] : '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),
          Expanded(
            flex: 2,
            child: Text(
              // item['payout_status'] != null ? item['payout_status'] : '-',
              item['payout_status'] == '1'
                  ? 'Pending'
                  : item['payout_status'] != null
                  ? 'Completed'
                  : '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),

          Expanded(
            flex: 2,
            child: Text(
              item['updated_at'] != null
                  ? _formatDateTime(item['updated_at'])
                  : '-',
              style: _dataBold,
              softWrap: true,
              maxLines: 3,
            ),
          ),

          // ACTION ICONS (Edit + Delete)
          Expanded(
            flex: 2,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                // EDIT ICON
                IconButton(
                  icon: const Icon(
                    Icons.remove_red_eye_outlined,
                    color: Colors.blue,
                    size: 18,
                  ),
                  onPressed: () {
                    // TODO: handle edit
                    context.go(AppRoutes.payout, extra: item);
                    print("Edit clicked for ${item['invoice_no']}");
                  },
                  splashRadius: 18,
                  hoverColor: Colors.black12,
                  padding: const EdgeInsets.all(8),
                  constraints: const BoxConstraints(),
                ),

                // DELETE ICON
                IconButton(
                  icon: const Icon(Icons.delete, color: Colors.red, size: 18),
                  onPressed: () {
                    // TODO: handle delete
                    deleteInvoice(item['id']);
                    print("Delete clicked for ${item['invoice_no']}");
                  },
                  splashRadius: 18,
                  hoverColor: Colors.black12,
                  padding: const EdgeInsets.all(8),
                  constraints: const BoxConstraints(),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  static final _dataBold = GoogleFonts.inter(
    fontSize: 11.5,
    fontWeight: FontWeight.w400,
    color: Color(0xFF000000),
  );

  static final _headerStyle = GoogleFonts.poppins(
    fontSize: 11.2,
    fontWeight: FontWeight.w500,
    color: Color(0xFF1E293B),
  );
}
