import 'package:flutter/material.dart';
import '../../../shared/widgets/image_loader.dart';
import '../../voucher/sub_widget/voucher_section_title.dart';
import '../../achievement/model/achievement_model.dart';
import '../models/main_section_config_model.dart';

class AchievementCarousel extends StatelessWidget {
  final List<AchievementModel> items;
  final MainSectionConfigModel? sectionConfig;
  final void Function(AchievementModel)? onTap;

  const AchievementCarousel({super.key, required this.items, this.sectionConfig, this.onTap});

  void _handleTapRightButton() {
    sectionConfig?.buttonViewAll?.directionalScreen?.begin();
  }

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width/1.6;
    if (items.isEmpty) return const SizedBox.shrink();

    return Column(
      children: [
        if ((sectionConfig?.name ?? "").isNotEmpty)
          HeaderSectionTitle(
            title: sectionConfig?.name?? "",
            onViewAll: sectionConfig?.buttonViewAll?.directionalScreen != null ? _handleTapRightButton : null,
          ),
        SizedBox(
          height: width*180/230,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: items.length,
            separatorBuilder: (_, _) => const SizedBox(width: 12),
            itemBuilder: (context, index) => AchievementCard(
              achievement: items[index],
              onTap: () => onTap?.call(items[index]),
            ),
          ),
        ),
      ],
    );
  }
}

class AchievementCard extends StatelessWidget {
  final AchievementModel achievement;
  final void Function()? onTap;

  const AchievementCard({super.key, required this.achievement, this.onTap});

  @override
  Widget build(BuildContext context) {
    final widthItem = MediaQuery.of(context).size.width/1.6;
    final imageUrl = (achievement.images?.isNotEmpty == true) ? achievement.images?.first.imageUrl : "";
    return GestureDetector(
      onTap: onTap,
      child: SizedBox(
        width: widthItem,
        child: ClipRRect(
          borderRadius: BorderRadius.circular(12),
          child: loadNetworkImage(
            url: imageUrl,
            fit: BoxFit.cover,
            width: double.infinity,
            height: widthItem*180/230,
            placeholderAsset: 'assets/images/ic_logo.png',
          ),
        ),
      ),
    );
  }
}
