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/size_config.dart';
import 'package:tm_app/data/services/model/liked_tender_feedback/liked_tender_feedback.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/shared/page_selection_dialog.dart';
import 'package:tm_app/views/shared/tender_app_bar.dart';

import '../../../core/utils/app_toast.dart';
import '../../shared/tablet_desktop_appbar.dart';
import '../../shared/tablet_navigation_widget.dart';
import '../widgets/like_filters_bottom_sheet.dart';

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

  @override
  State<LikedTendersTabletPage> createState() => _LikedTendersTabletPageState();
}

class _LikedTendersTabletPageState extends State<LikedTendersTabletPage> {
  late final LikedTendersViewModel viewModel;
  @override
  void initState() {
    viewModel = context.read<LikedTendersViewModel>();
    super.initState();
    viewModel.addListener(_viewModelListener);
  }

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

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

  @override
  Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> key = GlobalKey();
    return PopScope(
      onPopInvokedWithResult: (didPop, result) {
        if (kIsWeb) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            viewModel.updateHome();
          });
        }
      },
      child: Scaffold(
        key: key,
        backgroundColor: AppColors.backgroundColor,
        appBar: tabletAppBar(title: LikedTendersStrings.likedTenders, key: key),
        drawer: const TabletNavigationWidget(currentIndex: 1),
        body: SafeArea(
          child: Center(
            child: SizedBox(
              width: 720,
              child: Column(
                children: [
                  TabletDesktopAppbar(
                    title: LikedTendersStrings.likedTenders,
                    haveFilter: true,
                    onFilterPressed: () {
                      showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,
                        backgroundColor: AppColors.backgroundColor,
                        shape: const RoundedRectangleBorder(
                          borderRadius: BorderRadius.vertical(
                            top: Radius.circular(20),
                          ),
                        ),
                        constraints: BoxConstraints(
                          maxWidth: MediaQuery.sizeOf(context).width,
                          maxHeight: MediaQuery.sizeOf(context).height,
                        ),
                        builder: (context) => const LikeFiltersBottomSheet(),
                      );
                    },
                  ),
                  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 currentPage = viewModel.currentPage;
                        final totalPages = viewModel.data?.data?.meta?.pages ?? 1;
          
                        return Column(
                          children: [
                            _likedTendersList(feedback, viewModel),
          
                            SizedBox(height: 10.0.h()),
          
                            _likeTendersListPagesControll(
                              context,
                              totalPages,
                              viewModel,
                              currentPage,
                            ),
          
                            SizedBox(height: 30.0.h()),
                          ],
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _likeTendersListPagesControll(
    BuildContext context,
    int totalPages,
    LikedTendersViewModel viewModel,
    int currentPage,
  ) {
    return Row(
      children: [
        const Spacer(),
        Text(
          LikedTendersStrings.page,
          style: TextStyle(
            fontSize: 13.0.sp(),
            fontWeight: FontWeight.w300,
            color: AppColors.grey60,
          ),
        ),
        SizedBox(width: 10.0.w()),

        InkWell(
          onTap: () async {
            final selectedPage = await showDialog<int>(
              context: context,
              builder: (context) => PageSelectionDialog(totalPages: totalPages),
            );

            if (selectedPage != null) {
              await viewModel.jumpToPage(selectedPage);
            }
          },
          child: Container(
            decoration: BoxDecoration(
              border: Border.all(color: AppColors.grey30, width: 1),
              borderRadius: BorderRadius.circular(4),
            ),
            child: Row(
              children: [
                SizedBox(width: 5.0.w()),
                Text(
                  '$currentPage',
                  style: TextStyle(
                    fontSize: 14.0.sp(),
                    fontWeight: FontWeight.w500,
                    color: AppColors.grey70,
                  ),
                ),
                SizedBox(width: 5.0.w()),
                SvgPicture.asset(AssetsManager.arrowDownSmall),
                SizedBox(width: 5.0.w()),
              ],
            ),
          ),
        ),

        SizedBox(width: 5.0.w()),
        Text(
          LikedTendersStrings.of,
          style: TextStyle(
            fontSize: 14.0.sp(),
            fontWeight: FontWeight.w400,
            color: AppColors.grey60,
          ),
        ),
        SizedBox(width: 5.0.w()),
        Text(
          '$totalPages',
          style: TextStyle(
            fontSize: 13.0.sp(),
            fontWeight: FontWeight.w400,
            color: AppColors.grey60,
          ),
        ),
        SizedBox(width: 30.0.w()),
      ],
    );
  }

  Widget _likedTendersList(
    List<LikedTenderFeedback> feedback,
    LikedTendersViewModel viewModel,
  ) {
    return Expanded(
      child: ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 15.0.h()),
        itemCount: feedback.length,
        itemBuilder: (context, index) {
          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!),
            ),
          );
        },
      ),
    );
  }
}
