import 'dart:convert';

import 'package:community_material_icon/community_material_icon.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.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/add_to_cart.dart';
import 'package:mobile_pos/Provider/customer_provider.dart';
import 'package:mobile_pos/Provider/product_provider.dart';
import 'package:mobile_pos/Provider/transactions_provider.dart';
import 'package:mobile_pos/Screens/Customers/Model/customer_model.dart';
import 'package:mobile_pos/Screens/Quotation/sales_contact.dart';
import 'package:mobile_pos/Screens/Sales/add_sales.dart';
import 'package:mobile_pos/const_commas.dart';
import 'package:mobile_pos/generated/l10n.dart' as lang;
import 'package:mobile_pos/model/print_transaction_model.dart';
import 'package:nb_utils/nb_utils.dart';

import '../../../Provider/profile_provider.dart';
import '../../../constant.dart';
import '../../currency.dart';
import '../../empty_screen_widget.dart';
import '../../generate_pdf.dart';
import '../../model/personal_information_model.dart';
import '../../model/transition_model.dart';
import '../../pdf/sales_pdf.dart';
import '../../thermal printing service/printing_provider/print_thermal_invoice_provider.dart';
import '../Home/home.dart';
import '../invoice_details/sales_invoice_details_screen.dart';

final quotationListPaginationProvider =
    StateNotifierProvider<QuotationListPaginationNotifier, QuotationListPaginationState>((ref) {
  return QuotationListPaginationNotifier();
});

class QuotationListPaginationState {
  final int currentPage;
  final int itemsPerPage;
  final bool isLoading;
  final bool hasMore;
  final List<SalesTransitionModel> displayedQuotations;
  final String searchQuery;

  QuotationListPaginationState({
    this.currentPage = 1,
    this.itemsPerPage = 10,
    this.isLoading = false,
    this.hasMore = true,
    List<SalesTransitionModel>? displayedQuotations,
    this.searchQuery = '',
  }) : displayedQuotations = displayedQuotations ?? [];

  QuotationListPaginationState copyWith({
    int? currentPage,
    int? itemsPerPage,
    bool? isLoading,
    bool? hasMore,
    List<SalesTransitionModel>? displayedQuotations,
    String? searchQuery,
  }) {
    return QuotationListPaginationState(
      currentPage: currentPage ?? this.currentPage,
      itemsPerPage: itemsPerPage ?? this.itemsPerPage,
      isLoading: isLoading ?? this.isLoading,
      hasMore: hasMore ?? this.hasMore,
      displayedQuotations: displayedQuotations ?? this.displayedQuotations,
      searchQuery: searchQuery ?? this.searchQuery,
    );
  }
}

class QuotationListPaginationNotifier extends StateNotifier<QuotationListPaginationState> {
  QuotationListPaginationNotifier() : super(QuotationListPaginationState());

  void resetPagination() {
    state = state.copyWith(
      currentPage: 1,
      displayedQuotations: [],
      hasMore: true,
    );
  }

  void updateSearchQuery(String query) {
    state = state.copyWith(
      searchQuery: query,
      currentPage: 1,
      displayedQuotations: [],
      hasMore: true,
    );
  }

  void loadMoreQuotations(List<SalesTransitionModel> allQuotations) {
    if (state.isLoading || !state.hasMore) return;

    state = state.copyWith(isLoading: true);

    // Filter quotations based on search query
    final filteredQuotations = _filterQuotations(allQuotations);

    final totalItems = filteredQuotations.length;
    final startIndex = (state.currentPage - 1) * state.itemsPerPage;
    final endIndex = startIndex + state.itemsPerPage;

    // Check if we have more items to load
    final hasMoreItems = endIndex < totalItems;

    // Get the next batch of quotations
    final nextBatch = endIndex <= totalItems
        ? filteredQuotations.sublist(startIndex, endIndex)
        : filteredQuotations.sublist(startIndex);

    // Update state
    final newDisplayedQuotations = [...state.displayedQuotations, ...nextBatch];

    state = state.copyWith(
      currentPage: state.currentPage + 1,
      isLoading: false,
      hasMore: hasMoreItems,
      displayedQuotations: newDisplayedQuotations,
    );
  }

  List<SalesTransitionModel> _filterQuotations(List<SalesTransitionModel> quotations) {
    return quotations.where((quotation) {
      // Apply search filter if query is provided
      if (state.searchQuery.isNotEmpty) {
        return quotation.invoiceNumber.toString().contains(state.searchQuery) ||
            quotation.customerName.toLowerCase().contains(state.searchQuery.toLowerCase()) ||
            quotation.customerPhone.contains(state.searchQuery);
      }

      return true;
    }).toList();
  }
}

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

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

class _QuotationListScreenState extends State<QuotationListScreen> {
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  String _searchQuery = '';

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);

    // Search debounce
    _searchController.addListener(() {
      if (_searchController.text != _searchQuery) {
        _debounceSearch();
      }
    });
  }

  @override
  void dispose() {
    _searchController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
      _loadMoreData();
    }
  }

  void _loadMoreData() {
    final ref = ProviderScope.containerOf(context);
    final providerData = ref.read(quotationProvider);

    providerData.whenData((quotations) {
      ref
          .read(quotationListPaginationProvider.notifier)
          .loadMoreQuotations(quotations.reversed.toList());
    });
  }

  void _resetAndLoadData() {
    final ref = ProviderScope.containerOf(context);
    ref.read(quotationListPaginationProvider.notifier).resetPagination();
    _loadMoreData();
  }

  void _debounceSearch() {
    Future.delayed(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          _searchQuery = _searchController.text;
        });
        final ref = ProviderScope.containerOf(context);
        ref.read(quotationListPaginationProvider.notifier).updateSearchQuery(_searchQuery);
        _resetAndLoadData();
      }
    });
  }

  void _onSearchChanged(String value) {
    setState(() {
      _searchQuery = value;
    });
    final ref = ProviderScope.containerOf(context);
    ref.read(quotationListPaginationProvider.notifier).updateSearchQuery(value);
    _resetAndLoadData();
  }

  Widget _buildQuotationListItem(SalesTransitionModel quotation, WidgetRef consumerRef,
      AsyncValue<PersonalInformationModel> profile) {
    return GestureDetector(
      onTap: () async {
        if (await checkUserRolePermission(type: "quotation-read")) {
          SalesInvoiceDetails(
            transitionModel: quotation,
            personalInformationModel: profile.value!,
            isFromQuotation: true,
          ).launch(context);
        }
      },
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(20),
            width: context.width(),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Flexible(
                      child: Text(
                        quotation.customerName.isNotEmpty
                            ? quotation.customerName
                            : quotation.customerPhone,
                        style: const TextStyle(fontSize: 16),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ),
                    const SizedBox(width: 10.0),
                    Text(
                      '#${quotation.invoiceNumber}',
                      style: const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '${lang.S.of(context).total} : $currency ${myFormat.format(quotation.totalAmount)}',
                      style: const TextStyle(color: Colors.grey),
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          DateFormat.yMMMd().format(DateTime.parse(quotation.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                        const SizedBox(height: 5),
                        Text(
                          DateFormat.jm().format(DateTime.parse(quotation.purchaseDate)),
                          style: const TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ],
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    InkWell(
                      onTap: () async {
                        if (await checkUserRolePermission(type: "quotation-update")) {
                          final cart = consumerRef.read(cartNotifier);
                          cart.clearCart();
                          if (quotation.productList != null) {
                            for (var element in quotation.productList!) {
                              cart.addToCartRiverPod(element);
                            }
                          }

                          AddSalesScreen(
                            transitionModel: quotation,
                            customerModel: CustomerModel(
                                quotation.customerName,
                                quotation.customerPhone,
                                quotation.customerType,
                                "",
                                "",
                                quotation.customerAddress,
                                (quotation.dueAmount ?? 0),
                                0,
                                0,
                                "",
                                gst: quotation.customerGst),
                          ).launch(context);
                        }
                      },
                      child: Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                            color: kMainColor.withValues(alpha: 0.1),
                            borderRadius: const BorderRadius.all(Radius.circular(4))),
                        child: Text(
                          "Convert to Sale",
                          style: TextStyle(color: kMainColor),
                        ),
                      ),
                    ),
                    profile.when(data: (data) {
                      return Row(
                        children: [
                          IconButton(
                            onPressed: () async {
                              PrintTransactionModel model = PrintTransactionModel(
                                  transitionModel: quotation, personalInformationModel: data);
                              consumerRef
                                  .watch(thermalPrinterProvider)
                                  .printSalesThermalInvoiceNow(
                                      transaction: model,
                                      productList: model.transitionModel?.productList,
                                      context: context);
                            },
                            icon: const Icon(
                              FeatherIcons.printer,
                              color: Colors.grey,
                            ),
                          ),
                          PopupMenuButton(
                            offset: const Offset(0, 30),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(4.0),
                            ),
                            padding: EdgeInsets.zero,
                            itemBuilder: (BuildContext bc) => [
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () async =>
                                      await GeneratePdf1().generateQuotationDocument(
                                    quotation,
                                    data,
                                    context,
                                  ),
                                  child: Row(
                                    children: [
                                      const Icon(
                                        Icons.picture_as_pdf,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).pdfView,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () {
                                    shareQuotationPDF(
                                      transactions: quotation,
                                      personalInformation: data,
                                      context: context,
                                    );
                                    finish(context);
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        CommunityMaterialIcons.share,
                                        color: Colors.grey,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).share,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              PopupMenuItem(
                                child: GestureDetector(
                                  onTap: () async {
                                    if (await checkUserRolePermission(type: "quotation-delete")) {
                                      showDialog(
                                        context: context,
                                        builder: (context2) => AlertDialog(
                                          title: Text(
                                              '${lang.S.of(context).areYouSureToDeleteThisSale}?'),
                                          content: Text(
                                            '${lang.S.of(context).theSaleWillBeDeletedAndAllTheDataWillSale}?',
                                            maxLines: 5,
                                          ),
                                          actions: [
                                            Text(lang.S.of(context).cancel)
                                                .onTap(() => Navigator.pop(context2)),
                                            Padding(
                                              padding: const EdgeInsets.all(20.0),
                                              child: Text(lang.S.of(context).yesDeleteForever)
                                                  .onTap(() async {
                                                EasyLoading.show();

                                                await FirebaseDatabase.instance
                                                    .ref(constUserId)
                                                    .child('Sales Quotation')
                                                    .orderByKey()
                                                    .get()
                                                    .then((value) {
                                                  for (var element in value.children) {
                                                    SalesTransitionModel transitionzModel =
                                                        SalesTransitionModel.fromJson(
                                                            jsonDecode(jsonEncode(element.value)));
                                                    if (element.key != null &&
                                                        transitionzModel.invoiceNumber ==
                                                            quotation.invoiceNumber) {
                                                      //delete the quotation
                                                      FirebaseDatabase.instance
                                                          .ref(constUserId)
                                                          .child('Sales Quotation')
                                                          .child(element.key!)
                                                          .remove();
                                                    }
                                                  }
                                                });
                                                consumerRef.refresh(transitionProvider);
                                                consumerRef.refresh(productProvider);
                                                consumerRef.refresh(customerProvider);
                                                consumerRef.refresh(quotationProvider);
                                                EasyLoading.showSuccess(lang.S.of(context).done);
                                                Navigator.pop(context2);
                                                Navigator.pop(bc);
                                              }),
                                            ),
                                          ],
                                        ),
                                      );
                                    }
                                  },
                                  child: Row(
                                    children: [
                                      const Icon(
                                        Icons.delete,
                                        color: kGreyTextColor,
                                      ),
                                      const SizedBox(width: 10.0),
                                      Text(
                                        lang.S.of(context).delete,
                                        style: kTextStyle.copyWith(color: kGreyTextColor),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                            onSelected: (value) {
                              Navigator.pushNamed(context, '$value');
                            },
                            child: const Icon(
                              FeatherIcons.moreVertical,
                              color: kGreyTextColor,
                            ),
                          ),
                        ],
                      );
                    }, error: (e, stack) {
                      return Text(e.toString());
                    }, loading: () {
                      return Text(lang.S.of(context).loading);
                    }),
                  ],
                ),
              ],
            ),
          ),
          Container(
            height: 0.5,
            width: context.width(),
            color: Colors.grey,
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        return await const Home().launch(context, isNewTask: true);
      },
      child: Scaffold(
        backgroundColor: kMainColor,
        appBar: AppBar(
          title: Text(
            "Quotation List",
            style: GoogleFonts.poppins(
              color: Colors.white,
              fontSize: 20.0,
            ),
          ),
          iconTheme: const IconThemeData(color: Colors.white),
          centerTitle: true,
          backgroundColor: kMainColor,
          elevation: 0.0,
        ),
        body: Consumer(builder: (context, consumerRef, __) {
          final providerData = consumerRef.watch(quotationProvider);
          final profile = consumerRef.watch(profileDetailsProvider);
          final paginationState = consumerRef.watch(quotationListPaginationProvider);

          return Container(
            alignment: Alignment.topCenter,
            decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topRight: Radius.circular(30), topLeft: Radius.circular(30))),
            child: Stack(
              alignment: Alignment.bottomCenter,
              children: [
                providerData.when(
                  data: (allQuotations) {
                    // Initial load of data
                    if (paginationState.displayedQuotations.isEmpty &&
                        !paginationState.isLoading) {
                      WidgetsBinding.instance.addPostFrameCallback((_) {
                        _resetAndLoadData();
                      });
                    }

                    final filteredQuotations = allQuotations.where((quotation) {
                      if (_searchQuery.isNotEmpty) {
                        return quotation.invoiceNumber.toString().contains(_searchQuery) ||
                            quotation.customerName
                                .toLowerCase()
                                .contains(_searchQuery.toLowerCase()) ||
                            quotation.customerPhone.contains(_searchQuery);
                      }
                      return true;
                    }).toList();

                    return Column(
                      children: [
                        // Search Field
                        Padding(
                          padding: const EdgeInsets.all(20.0),
                          child: AppTextField(
                            controller: _searchController,
                            textFieldType: TextFieldType.NUMBER,
                            onChanged: _onSearchChanged,
                            decoration: InputDecoration(
                                floatingLabelBehavior: FloatingLabelBehavior.never,
                                labelText: lang.S.of(context).invoiceNumber,
                                hintText: lang.S.of(context).enterInvoiceNumber,
                                border: const OutlineInputBorder(),
                                prefixIcon: const Icon(Icons.search)),
                          ),
                        ),

                        // Quotations List with Pagination
                        Expanded(
                          child: paginationState.displayedQuotations.isNotEmpty ||
                                  paginationState.isLoading
                              ? SingleChildScrollView(
                                  controller: _scrollController,
                                  child: Column(
                                    children: [
                                      ListView.builder(
                                        shrinkWrap: true,
                                        physics: const NeverScrollableScrollPhysics(),
                                        itemCount: paginationState.displayedQuotations.length +
                                            (paginationState.hasMore ? 1 : 0),
                                        itemBuilder: (context, index) {
                                          // Loading indicator at the end
                                          if (index ==
                                              paginationState.displayedQuotations.length) {
                                            return paginationState.hasMore
                                                ? const Padding(
                                                    padding: EdgeInsets.all(16.0),
                                                    child: Center(
                                                      child: CircularProgressIndicator(),
                                                    ),
                                                  )
                                                : filteredQuotations.isNotEmpty
                                                    ? Padding(
                                                        padding: const EdgeInsets.all(16.0),
                                                        child: Center(
                                                          child: Text(
                                                            lang.S.of(context).noDataFound,
                                                            style: const TextStyle(
                                                                color: Colors.grey),
                                                          ),
                                                        ),
                                                      )
                                                    : const SizedBox.shrink();
                                          }

                                          final quotation =
                                              paginationState.displayedQuotations[index];
                                          return _buildQuotationListItem(
                                              quotation, consumerRef, profile);
                                        },
                                      ),
                                    ],
                                  ),
                                )
                              : _searchQuery.isNotEmpty
                                  ? Center(
                                      child: Padding(
                                        padding: const EdgeInsets.only(top: 60),
                                        child: Text(
                                          lang.S.of(context).noDataFound,
                                          style: const TextStyle(color: Colors.grey, fontSize: 16),
                                        ),
                                      ),
                                    )
                                  : allQuotations.isEmpty
                                      ? const Padding(
                                          padding: EdgeInsets.only(top: 60),
                                          child: EmptyScreenWidget(),
                                        )
                                      : const Center(
                                          child: CircularProgressIndicator(),
                                        ),
                        ),
                      ],
                    );
                  },
                  error: (e, stack) {
                    return Center(
                      child: Padding(
                        padding: const EdgeInsets.all(20.0),
                        child: Text(
                          'Error loading quotations: $e',
                          style: const TextStyle(color: Colors.red),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    );
                  },
                  loading: () {
                    return const Center(child: CircularProgressIndicator());
                  },
                ),
              ],
            ),
          );
        }),
        bottomNavigationBar: Container(
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                  backgroundColor: kMainColor,
                  minimumSize: Size.fromHeight(48),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadiusGeometry.circular(8),
                  )),
              onPressed: () async {
                if (await checkUserRolePermission(type: "quotation-create")) {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => SalesContact(isFromHome: false)));
                }
              },
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "Add Quotation",
                    style: Theme.of(context).textTheme.titleMedium?.copyWith(
                          fontWeight: FontWeight.w600,
                          color: Colors.white,
                        ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
