import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:monitoring/config.dart';

class Berita {
  final int id;
  final String judul;
  final String? gambarUrl;

  Berita({required this.id, required this.judul, this.gambarUrl});

  factory Berita.fromJson(Map<String, dynamic> json) {
    return Berita(
      id: json['id'],
      judul: json['judul'] ?? '',
      gambarUrl: json['gambar_url'],
    );
  }
}

class BeritaCarousel extends StatefulWidget {
  const BeritaCarousel({
    super.key,
    required this.token,
    required bool isCircleStyle,
  });
  final String token;

  @override
  State<BeritaCarousel> createState() => _BeritaCarouselState();
}

class _BeritaCarouselState extends State<BeritaCarousel> {
  List<Berita> _beritaList = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    fetchBerita();
  }

  Future<void> fetchBerita() async {
    try {
      final dio = Dio(
        BaseOptions(
          baseUrl: '$baseUrl',
          headers: {
            'Accept': 'application/json',
            'Authorization': 'Bearer ${widget.token}',
          },
        ),
      );

      final response = await dio.get('/berita/published');
      final List raw = response.data['data'];
      setState(() {
        _beritaList = raw.map((e) => Berita.fromJson(e)).toList();
        _loading = false;
      });
    } catch (e) {
      debugPrint('Gagal ambil berita: $e');
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_loading) return const Center(child: CircularProgressIndicator());
    if (_beritaList.isEmpty) return const Text('Tidak ada berita.');

    return SizedBox(
      height: 160,
      child: PageView.builder(
        itemCount: _beritaList.length,
        controller: PageController(viewportFraction: 0.85),
        itemBuilder: (context, index) {
          final berita = _beritaList[index];
          return Container(
            margin: const EdgeInsets.symmetric(horizontal: 8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12),
              image: DecorationImage(
                image:
                    berita.gambarUrl != null
                        ? NetworkImage(berita.gambarUrl!)
                        : const AssetImage('assets/404.png') as ImageProvider,
                fit: BoxFit.cover,
              ),
            ),
            child: Container(
              alignment: Alignment.bottomLeft,
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.black54,
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(12),
                  bottomRight: Radius.circular(12),
                ),
              ),
              child: Text(
                berita.judul,
                style: const TextStyle(color: Colors.white, fontSize: 14),
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          );
        },
      ),
    );
  }
}
