import 'package:flutter/material.dart';
import 'package:mypoint_flutter_app/widgets/image_loader.dart';

import '../../faqs/faqs_model.dart';
import '../../voucher/sub_widget/voucher_section_title.dart';
import '../models/main_section_config_model.dart';

class NewsCarouselWidget extends StatelessWidget {
  final List<PageItemModel> items;
  final MainSectionConfigModel? sectionConfig;
  final void Function(PageItemModel)? onTap;
  const NewsCarouselWidget({super.key, required this.items, this.sectionConfig, this.onTap});

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

  @override
  Widget build(BuildContext context) {
    final widthItem = 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: widthItem*9/16 + 72,
          child: ListView.separated(
            scrollDirection: Axis.horizontal,
            padding: const EdgeInsets.symmetric(horizontal: 16),
            itemCount: items.length,
            separatorBuilder: (_, __) => const SizedBox(width: 12),
            itemBuilder: (context, index) => _buildItem(context, items[index]),
          ),
        ),
      ],
    );
  }

  Widget _buildItem(BuildContext context, PageItemModel news) {
    final widthItem = MediaQuery.of(context).size.width/1.6;
    return GestureDetector(
      onTap: () => onTap?.call(news),
      child: Container(
        width: widthItem,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.grey.shade200),
          color: Colors.white,
          boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.05), blurRadius: 6, offset: const Offset(0, 2))],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: const BorderRadius.only(topLeft: Radius.circular(16), topRight: Radius.circular(16)),
              child: loadNetworkImage(
                url: news.thumbnail ?? '',
                height: widthItem * 9/16,
                width: double.infinity,
                fit: BoxFit.cover,
                placeholderAsset: 'assets/images/bg_default_169.png',
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(12),
              child: Text(
                news.title ?? '',
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
                style: const TextStyle(fontSize: 14, fontWeight: FontWeight.bold, color: Colors.black87),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
