import 'package:flutter/material.dart';
import 'package:provider/provider.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/tablet_navigation_widget.dart';

import '../../../core/constants/assets.dart';
import '../../shared/tender_app_bar.dart';
import '../strings/home_strings.dart';
import '../widgets.dart';

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

  @override
  Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> key = GlobalKey();

    return Scaffold(
      key: key,

      appBar: tabletAppBar(title: HomeStrings.home, key: key),

      drawer: const TabletNavigationWidget(
        currentIndex: 0, // Home is index 0
      ),
      body: 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: Padding(
                padding: EdgeInsetsDirectional.fromSTEB(
                  24.0.w(),
                  24.0.h(),
                  24.0.w(),
                  24.0.h(),
                ),
                child: SafeArea(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // NotificationCard(),
                      SizedBox(height: 40.0.h()),
                      _progressBarsRow(homeViewModel),
                      SizedBox(height: 32.0.h()),
                      _firstTenderCardsRow(
                        context,
                        homeViewModel.tenderApprovalsStateResponse!,
                      ),
                      SizedBox(height: 8.0.h()),
                      _secondTenderCardsRow(homeViewModel, context),
                      SizedBox(height: 32.0.h()),
                      _yourTenderText(homeViewModel),
                      SizedBox(height: 8.0.h()),
                      _bottomListView(homeViewModel),
                    ],
                  ),
                ),
              ),
            );
          }
          return const Center(
            child: CircularProgressIndicator(color: AppColors.secondary50),
          );
        },
      ),
    );
  }

  Widget _progressBarsRow(HomeViewModel homeViewModel) {
    return Row(
      children: [
        const Spacer(),
        SizedBox(width: 20.0.w()),
        ProgressBarColumn(
          text: HomeStrings.partnership,
          value: homeViewModel.partnershipPercent,
          amount: homeViewModel.partnershipPercent.toString(),
          circularProgressIndicatorWidth: 176.0,
          circularProgressIndicatorHeight: 176.0,
          strokeWidth: 8.0,
        ),
        const Spacer(),
        ProgressBarColumn(
          text: HomeStrings.selfApply,
          value: homeViewModel.selfApplyPercent,
          amount: homeViewModel.selfApplyPercent.toString(),
          circularProgressIndicatorWidth: 176.0,
          circularProgressIndicatorHeight: 176.0,
          strokeWidth: 8.0,
        ),
        SizedBox(width: 20.0.w()),
        const Spacer(),
      ],
    );
  }

  Widget _firstTenderCardsRow(
    BuildContext context,
    TenderApprovalsStatsResponse tenderApprovalsStateResponse,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: TenderCard(
            backgroundColor: AppColors.primary20,
            iconPath: AssetsManager.arrows,
            title: HomeStrings.tenderSubmitted,
            amount:
                tenderApprovalsStateResponse.data!.submittedTenders.toString(),

            textColor: AppColors.mainBlue,
            enableTap: true,
            width: double.infinity,
            height: 148,
            onTap: () {
              const YourTendersRouteData().push(context);
            },
          ),
        ),
        const SizedBox(width: 16.0),
        Expanded(
          child: TenderCard(
            backgroundColor: AppColors.primary10,
            iconPath: AssetsManager.approve,
            title: HomeStrings.approvedTenders,
            amount: '0',
            textColor: AppColors.jellyBean,
            enableTap: true,
            width: double.infinity,
            height: 148,
            onTap: () {
              const YourTendersRouteData().push(context);
            },
          ),
        ),
      ],
    );
  }

  Widget _secondTenderCardsRow(
    HomeViewModel homeViewModel,
    BuildContext context,
  ) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Expanded(
          child: TenderCard(
            backgroundColor: AppColors.orange10,
            iconPath: AssetsManager.shield,
            title: HomeStrings.tenderValue,
            amount: '0',
            textColor: AppColors.orange,
            enableTap: true,
            width: double.infinity,
            height: 148,
            onTap: () {},
          ),
        ),
        const SizedBox(width: 16.0),
        Expanded(
          child: 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,
            width: double.infinity,
            height: 148,
            onTap: () {
              const LikedTendersRouteData().push(context);
            },
          ),
        ),
      ],
    );
  }

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

  Widget _bottomListView(HomeViewModel homeViewModel) {
    return SizedBox(
      width: double.infinity,
      height: 387.0.h(),
      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(
          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]);
            } else {
              return const Center(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: CircularProgressIndicator(
                    color: AppColors.secondary50,
                  ),
                ),
              );
            }
          },
        ),
      ),
    );
  }
}
