import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class CelebrationScreen extends StatefulWidget {
  const CelebrationScreen({super.key});

  @override
  State<CelebrationScreen> createState() => _CelebrationScreenState();
}

class _CelebrationScreenState extends State<CelebrationScreen> {
  bool isLoading = true;
  List<dynamic> celebrations = [];

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

  Future<void> fetchCelebrations() async {
    final url = Uri.parse("https://gelite.asia/api/celebration.php");

    try {
      final res = await http.get(url);
      final data = json.decode(res.body);

      if (data['success'] == true) {
        setState(() {
          celebrations = data['data'] ?? [];
          isLoading = false;
        });
      } else {
        setState(() {
          celebrations = [];
          isLoading = false;
        });
      }
    } catch (e) {
      setState(() {
        celebrations = [];
        isLoading = false;
      });
    }
  }

  int _parseYears(dynamic value1, dynamic value2) {
    if (value1 != null) {
      return int.tryParse(value1.toString()) ?? 0;
    }
    if (value2 != null) {
      return int.tryParse(value2.toString()) ?? 0;
    }
    return 0;
  }

  Widget _buildCelebrationItem(Map<String, dynamic> item) {
    final String? photoUrl = item['profile_photo'];
    final String name = (item['name'] ?? '').toString();
    final int years =
    _parseYears(item['celebration_year'], item['anniversary_years']);

    return Center(
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        elevation: 4,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // PASSPORT SIZE PHOTO
              ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: SizedBox(
                  width: 120,   // passport width
                  height: 150,  // passport height
                  child: photoUrl != null && photoUrl.isNotEmpty
                      ? Image.network(
                    photoUrl,
                    fit: BoxFit.cover,
                  )
                      : Image.asset(
                    "assets/default-avatar.png",
                    fit: BoxFit.cover,
                  ),
                ),
              ),

              const SizedBox(height: 12),

              // NAME
              Text(
                name,
                textAlign: TextAlign.center,
                style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),

              const SizedBox(height: 6),

              // YEARS
              Text(
                "$years Years of Celebration",
                style: const TextStyle(
                  fontSize: 15,
                  color: Colors.green,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Wedding Celebrations"),
        centerTitle: true,
      ),
      body: isLoading
          ? const Center(child: CircularProgressIndicator())
          : celebrations.isEmpty
          ? const Center(
        child: Text(
          "No celebrations today",
          style: TextStyle(fontSize: 16),
        ),
      )
          : RefreshIndicator(
        onRefresh: fetchCelebrations,
        child: ListView.builder(
          physics: const AlwaysScrollableScrollPhysics(),
          itemCount: celebrations.length,
          itemBuilder: (context, index) {
            final item =
            celebrations[index] as Map<String, dynamic>;
            return _buildCelebrationItem(item);
          },
        ),
      ),
    );
  }
}
