import 'package:flutter/material.dart';
import 'package:provider/provider.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_tenders_response/liked_tenders_response.dart';
import 'package:tm_app/view_models/your_tenders_view_model.dart';
import 'package:tm_app/views/your_tenders/strings/your_tenders_strings.dart';
import 'package:tm_app/views/your_tenders/widgets/tender_card.dart';

import '../../../core/constants/tender_feedback.dart';

class LikedDislikedTendersList extends StatefulWidget {
  final LikedTendersResponse data;
  final String status;
  final bool isDesktop;
  final bool isMobile;

  const LikedDislikedTendersList({
    required this.data,
    required this.status,
    required this.isDesktop,
    required this.isMobile,
    super.key,
  });

  @override
  State<LikedDislikedTendersList> createState() =>
      _LikedDislikedTendersListState();
}

class _LikedDislikedTendersListState extends State<LikedDislikedTendersList> {
  final ScrollController _controller = ScrollController();

  @override
  void initState() {
    super.initState();
    _controller.addListener(_onScroll);
  }

  void _onScroll() {
    final vm = context.read<YourTendersViewModel>();
    if (_controller.position.pixels >=
        _controller.position.maxScrollExtent - 200) {
      vm.loadMoreFeedback();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final vm = context.watch<YourTendersViewModel>();
    final data = widget.data;

    if (data.data?.feedback == null || data.data!.feedback!.isEmpty) {
      return Center(
        child: Text(
          widget.status == TenderFeedback.liked.value
              ? YourTendersStrings.noLikedTenders
              : YourTendersStrings.noDislikedTenders,
          style: TextStyle(fontSize: 16.0.sp(), color: AppColors.grey70),
        ),
      );
    }

    final items = data.data!.feedback!;
    final itemCount = items.length + (vm.isLoadingMore ? 1 : 0);

    return ListView.builder(
      controller: widget.isMobile ? _controller : null,
      itemCount: itemCount,
      itemBuilder: (context, index) {
        if (index >= items.length) {
          return Padding(
            padding: EdgeInsets.symmetric(vertical: 16.0.h()),
            child: const Center(
              child: CircularProgressIndicator(color: AppColors.secondary50),
            ),
          );
        }

        final feedback = items[index];
        return Padding(
          padding: EdgeInsets.only(bottom: 16.0.h()),
          child: TenderCard(
            tender: feedback.tender!,
            isDesktop: widget.isDesktop,
            status: widget.status,
            submissionMode: '',
          ),
        );
      },
    );
  }
}
