import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';
import 'package:provider/provider.dart';
import 'package:tm_app/core/constants/assets.dart';
import 'package:tm_app/core/theme/colors.dart';
import 'package:tm_app/core/utils/app_toast.dart';
import 'package:tm_app/core/utils/size_config.dart';
import 'package:tm_app/view_models/liked_tenders_view_model.dart';
import 'package:tm_app/views/liked_tenders/strings/liked_tenders_strings.dart';
import 'package:tm_app/views/liked_tenders/widgets/liked_tenders_list_item.dart';
import 'package:tm_app/views/login/widgets/widgets.dart';

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

  @override
  State<LikedTendersMobilePage> createState() => _LikedTendersMobilePageState();
}

class _LikedTendersMobilePageState extends State<LikedTendersMobilePage> {
  late final ScrollController _scrollController;
  late final LikedTendersViewModel viewModel;

  @override
  void initState() {
    viewModel = context.read<LikedTendersViewModel>();
    super.initState();
    _scrollController = ScrollController()..addListener(_onScroll);
    viewModel.addListener(_viewModelListener);
  }

  void _viewModelListener() {
    if (mounted &&
        viewModel.approvalErrorMessage?.isNotEmpty == true &&
        viewModel.approvalStatus == false) {
      AppToast.error(context, viewModel.approvalErrorMessage!);
      viewModel.clearApprovalErrorMessage();
    }
  }

  void _onScroll() {
    if (!_scrollController.hasClients) {
      return;
    }
    final max = _scrollController.position.maxScrollExtent;
    final pos = _scrollController.position.pixels;
    const threshold = 200.0;
    if (max - pos <= threshold) {
      final vm = Provider.of<LikedTendersViewModel>(context, listen: false);
      vm.loadMoreIfNeeded();
    }
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    viewModel.removeListener(_viewModelListener);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      onPopInvokedWithResult: (didPop, result) {
        if (kIsWeb) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            viewModel.updateHome();
          });
        }
      },
      child: Scaffold(
        backgroundColor: AppColors.backgroundColor,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(60),
          child: AppBar(
            backgroundColor: AppColors.backgroundColor,
            elevation: 0,
            titleSpacing: 0,
            leading: IconButton(
              icon: SvgPicture.asset(
                AssetsManager.arrowLeft,
                height: 24.0.w(),
                width: 24.0.w(),
              ),
              onPressed: () => Navigator.pop(context),
            ),
            title: Text(
              LikedTendersStrings.likedTenders,
              style: TextStyle(
                color: AppColors.grey70,
                fontWeight: FontWeight.w600,
                fontSize: 20.0.sp(),
              ),
            ),
            actions: [
              IconButton(
                icon: SvgPicture.asset(
                  AssetsManager.filter,
                  height: 24.0.w(),
                  width: 24.0.w(),
                ),
                onPressed: () {
                  showModalBottomSheet(
                    backgroundColor: AppColors.backgroundColor,
                    context: context,
                    isScrollControlled: true,
                    shape: const RoundedRectangleBorder(
                      borderRadius: BorderRadius.vertical(
                        top: Radius.circular(20),
                      ),
                    ),
                    builder: (context) {
                      return Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            SizedBox(height: 10.0.h()),
                            Text(
                              LikedTendersStrings.filter,
                              style: TextStyle(
                                fontWeight: FontWeight.w600,
                                color: AppColors.grey70,
                                fontSize: 20.0.sp(),
                              ),
                            ),
                            SizedBox(height: 20.0.h()),
                            _buildFilterOption('Industry'),
                            _buildFilterOption('Finance'),
                            _buildFilterOption('Business'),
                            _buildFilterOption('IT'),
                            _buildFilterOption('Software'),
                            SizedBox(height: 20.0.h()),
                            BaseButton(
                              backgroundColor: AppColors.primary2,
                              borderRadius: 24,
                              isEnabled: true,
                              onPressed: () {
                                Navigator.pop(context);
                              },
                              text: 'Apply',
                              textColor: AppColors.textBlue,
                            ),
                          ],
                        ),
                      );
                    },
                  );
                },
              ),

              SizedBox(width: 16.0.w()),
            ],
          ),
        ),

        body: SafeArea(
          child: Column(
            children: [
              Expanded(
                child: Consumer<LikedTendersViewModel>(
                  builder: (context, viewModel, child) {
                    if (viewModel.isLoading &&
                        (viewModel.data?.data?.feedback ?? []).isEmpty) {
                      return const Center(
                        child: CircularProgressIndicator(
                          color: AppColors.secondary50,
                        ),
                      );
                    }
          
                    if (viewModel.errorMessage != null) {
                      return Center(child: Text(viewModel.errorMessage!));
                    }
          
                    final feedback = viewModel.data?.data?.feedback ?? [];
          
                    if (feedback.isEmpty) {
                      return const Center(
                        child: Text(LikedTendersStrings.noLikedTenders),
                      );
                    }
          
                    final itemCount =
                        feedback.length + (viewModel.isLoadingMore ? 1 : 0);
          
                    return ListView.builder(
                      controller: _scrollController,
                      padding: EdgeInsets.symmetric(
                        horizontal: 24.0.w(),
                        vertical: 15.0.h(),
                      ),
                      itemCount: itemCount,
                      itemBuilder: (context, index) {
                        if (index < feedback.length) {
                          final item = feedback[index];
          
                          return Padding(
                            padding: EdgeInsets.only(bottom: 20.0.h()),
                            child: Dismissible(
                              key: ValueKey(item.tenderId ?? index),
                              direction: DismissDirection.endToStart,
                              background: Container(
                                alignment: Alignment.centerRight,
                                padding: EdgeInsets.symmetric(
                                  horizontal: 20.0.w(),
                                ),
                                child: SvgPicture.asset(
                                  AssetsManager.trash,
                                  width: 32.0.w(),
                                  height: 32.0.h(),
                                ),
                              ),
                              onDismissed: (_) {
                                if (item.tenderId != null) {
                                  viewModel.removeTenderById(item.tenderId!);
                                }
                              },
                              child: LikedListItem(tender: item.tender!),
                            ),
                          );
                        } else {
                          return Padding(
                            padding: EdgeInsets.symmetric(vertical: 20.0.h()),
                            child: Center(
                              child: SizedBox(
                                width: 24.0.w(),
                                height: 24.0.h(),
                                child: const CircularProgressIndicator(
                                  color: AppColors.secondary50,
                                  strokeWidth: 2,
                                ),
                              ),
                            ),
                          );
                        }
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

Widget _buildFilterOption(String title) {
  return Padding(
    padding: EdgeInsets.symmetric(vertical: 8.0.h()),
    child: Align(
      alignment: Alignment.centerLeft,
      child: Text(
        title,
        style: TextStyle(
          fontSize: 16.0.sp(),
          color: AppColors.grey80,
          fontWeight: FontWeight.w400,
        ),
      ),
    ),
  );
}
