import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tm_app/core/constants/assets.dart';
import 'package:tm_app/core/routes/app_routes.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/tender_approvals_stats_response/tender_approvals_stats_response.dart';
import 'package:tm_app/view_models/home_view_model.dart';
import 'package:tm_app/views/shared/tender_app_bar.dart';

import '../strings/home_strings.dart';
import '../widgets.dart';

class MobileHomePage extends StatelessWidget {
  const MobileHomePage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: tenderMobileAppBar(title: HomeStrings.home),
      body: SafeArea(
        child: Consumer<HomeViewModel>(
          builder: (context, homeViewModel, child) {
            if (homeViewModel.isLoading) {
              return const Center(
                child: CircularProgressIndicator(color: AppColors.secondary50),
              );
            }

            if (homeViewModel.errorMessage != null) {
              return Center(child: Text(homeViewModel.errorMessage!));
            }

            if (homeViewModel.tenderApprovalsStateResponse != null &&
                homeViewModel.data != null &&
                homeViewModel.feedbackStats != null) {
              return SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // SizedBox(height: 18.0.h()),
                    // NotificationCard(),
                    SizedBox(height: 32.0.h()),
                    _progressBarsRow(homeViewModel),
                    SizedBox(height: 32.0.h()),
                    _firstTenderCardsRow(
                      context,
                      homeViewModel.tenderApprovalsStateResponse!,
                    ),
                    SizedBox(height: 8.0.h()),
                    _secondTenderCardsRow(homeViewModel, context),
                    SizedBox(height: 40.0.h()),
                    _yourTenderText(homeViewModel),
                    _bottomListView(homeViewModel),
                  ],
                ),
              );
            }
            return const Center(
              child: CircularProgressIndicator(color: AppColors.secondary50),
            );
          },
        ),
      ),
    );
  }

  Widget _progressBarsRow(HomeViewModel homeViewModel) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.0.w()),
      child: Row(
        children: [
          const Spacer(),
          SizedBox(width: 20.0.w()),
          ProgressBarColumn(
            text: HomeStrings.partnership,
            value: homeViewModel.partnershipPercent,
            amount: homeViewModel.partnershipPercent.toString(),
          ),
          const Spacer(),
          ProgressBarColumn(
            text: HomeStrings.selfApply,
            value: homeViewModel.selfApplyPercent,
            amount: homeViewModel.selfApplyPercent.toString(),
          ),
          SizedBox(width: 20.0.w()),
          const Spacer(),
        ],
      ),
    );
  }

  Widget _firstTenderCardsRow(
    BuildContext context,
    TenderApprovalsStatsResponse tenderApprovalsStateResponse,
  ) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.0.w()),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TenderCard(
            backgroundColor: AppColors.primary20,
            iconPath: AssetsManager.arrows,
            title: HomeStrings.tenderSubmitted,
            amount:
                tenderApprovalsStateResponse.data!.submittedTenders.toString(),
            textColor: AppColors.mainBlue,
            enableTap: true,
            onTap: () {
              const YourTendersRouteData().push(context);
            },
          ),
          TenderCard(
            backgroundColor: AppColors.primary10,
            iconPath: AssetsManager.approve,
            title: HomeStrings.approvedTenders,
            amount: '0',

            textColor: AppColors.jellyBean,
            enableTap: true,
            onTap: () {
              const YourTendersRouteData().push(context);
            },
          ),
        ],
      ),
    );
  }

  Widget _secondTenderCardsRow(
    HomeViewModel homeViewModel,
    BuildContext context,
  ) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.0.w()),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          TenderCard(
            backgroundColor: AppColors.orange10,
            iconPath: AssetsManager.shield,
            title: HomeStrings.tenderValue,
            amount: '0',
            textColor: AppColors.orange,
            enableTap: true,
            onTap: () {},
          ),
          TenderCard(
            backgroundColor: AppColors.grey10,
            iconPath: AssetsManager.thumbLike,
            title: HomeStrings.likedTenders,
            amount: homeViewModel.feedbackStats?.totalLikes.toString() ?? '0',
            textColor: AppColors.grey50,
            enableTap: (homeViewModel.feedbackStats?.totalLikes ?? 0) != 0,
            onTap: () {
              const LikedTendersRouteData().push(context).then((value) {
                homeViewModel.init();
              });
            },
          ),
        ],
      ),
    );
  }

  Widget _yourTenderText(HomeViewModel homeViewModel) {
    final isYourTenders =
        homeViewModel.data?.data?.tenders!.isNotEmpty ?? false;
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.0.w()),
      child: Text(
        isYourTenders
            ? HomeStrings.yourTenders
            : HomeStrings.recommendedTenders,
        style: TextStyle(
          fontSize: 18.0.sp(),
          fontWeight: FontWeight.w700,
          color: AppColors.grey80,
        ),
      ),
    );
  }

  Widget _bottomListView(HomeViewModel homeViewModel) {
    return Container(
      constraints: BoxConstraints(maxHeight: 387.0.h()),
      width: double.infinity,
      child: NotificationListener<ScrollNotification>(
        onNotification: (ScrollNotification scrollInfo) {
          if (scrollInfo.metrics.pixels >=
              scrollInfo.metrics.maxScrollExtent - 200) {
            if (!homeViewModel.isLoadingMore && homeViewModel.hasMore) {
              if (!homeViewModel.isRecommendedMode) {
                homeViewModel.getYourTenders();
              } else {
                homeViewModel.getHomeRecommendTenders();
              }
            }
          }
          return false;
        },
        child: ListView.builder(
          padding: EdgeInsets.symmetric(
            horizontal: 24.0.w(),
            vertical: 15.0.h(),
          ),
          itemCount:
              homeViewModel.tenders.length +
              (homeViewModel.isLoadingMore ? 1 : 0),
          scrollDirection: Axis.horizontal,
          itemBuilder: (context, index) {
            if (index < homeViewModel.tenders.length) {
              return TendersListItem(
                tender: homeViewModel.tenders[index],
                onTap: () {
                  TenderDetailRouteData(
                    tenderId: homeViewModel.tenders[index].id!,
                  ).push(context);
                },
              );
            } else {
              return const Center(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: CircularProgressIndicator(
                    color: AppColors.secondary50,
                  ),
                ),
              );
            }
          },
        ),
      ),
    );
  }
}
