import 'package:flutter/material.dart';
import '../../../widgets/image_loader.dart';
import '../../voucher/sub_widget/voucher_section_title.dart';
import '../models/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});

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

  @override
  Widget build(BuildContext context) {
    final width = MediaQuery.of(context).size.width;
    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/1.6,
          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 imageUrl = (achievement.images?.isNotEmpty == true) ? achievement.images?.first.imageUrl : "";
    return GestureDetector(
      onTap: onTap,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: loadNetworkImage(
          url: imageUrl,
          fit: BoxFit.cover,
          width: 280,
          height: 140,
          placeholderAsset: 'assets/images/ic_logo.png',
        ),
      ),
    );
  }
}
