import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:tm_app/core/utils/size_config.dart';
import 'package:tm_app/view_models/tenders_view_model.dart';

import '../../../core/constants/common_strings.dart';
import '../../../core/theme/colors.dart';
import '../../../core/utils/app_toast.dart';
import '../../shared/tender_app_bar.dart';
import '../strings/tenders_strings.dart';
import '../widgets/main_tenders_slider.dart';

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

  @override
  State<MobileTendersPage> createState() => _MobileTendersPageState();
}

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

  void _viewModelListener() {
    if (viewModel.feedbackErrorMessage != null) {
      AppToast.error(context, viewModel.feedbackErrorMessage!);
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: tenderMobileAppBar(title: TendersStrings.tendersTitle),
      body: SafeArea(
        child: Consumer<TendersViewModel>(
          builder: (context, viewModel, child) {
            if (viewModel.isLoading) {
              return const Center(
                child: CircularProgressIndicator(color: AppColors.jellyBean),
              );
            }
            if (viewModel.errorMessage != null) {
              return Center(child: Text(viewModel.errorMessage!));
            }

            if ((viewModel.tendersResponse?.data?.tenders == null ||
                    viewModel.tendersResponse!.data!.tenders!.isEmpty) &&
                viewModel.isLoading == false) {
              return const Center(child: Text(CommonStrings.noData));
            }

            return SingleChildScrollView(
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 18.0.h()),
                child: MainTendersSlider(
                  tenders: viewModel.tendersResponse?.data?.tenders ?? [],
                ),
              ),
            );
          },
        ),
      ),
    );
  }
}
