import 'dart:convert';

import 'package:fl_ks_smart_society_user/localization/localization_const.dart';
import 'package:fl_ks_smart_society_user/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

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

  @override
  State<BirthdayScreen> createState() => _BirthdayScreenState();
}

class _BirthdayScreenState extends State<BirthdayScreen> {
  static const String birthdayUrl = 'https://gelite.asia/api/birthday.php';

  bool _isLoading = false;
  String? _errorMessage;
  List<BirthdayMember> _members = [];

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

  Future<void> _fetchBirthdays() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final response = await http.post(Uri.parse(birthdayUrl));

      debugPrint('➡️ BIRTHDAY REQUEST URL: $birthdayUrl');
      debugPrint('⬅️ BIRTHDAY RESPONSE STATUS: ${response.statusCode}');
      debugPrint('⬅️ BIRTHDAY RESPONSE BODY: ${response.body}');

      if (!mounted) return;

      if (response.statusCode == 200) {
        dynamic jsonData;
        try {
          jsonData = json.decode(response.body);
        } catch (e) {
          debugPrint('❌ BIRTHDAY JSON DECODE ERROR: $e');
          setState(() {
            _errorMessage = 'Invalid response from server';
          });
          return;
        }

        final bool success = jsonData['success'] == true;
        final String message = jsonData['message']?.toString() ?? '';

        if (!success) {
          setState(() {
            _errorMessage = message.isNotEmpty ? message : 'Failed to load birthdays';
          });
          return;
        }

        final List dataList = jsonData['data'] as List? ?? [];

        final members = dataList
            .map((e) => BirthdayMember.fromJson(e as Map<String, dynamic>))
            .toList();

        setState(() {
          _members = members;
          if (_members.isEmpty && message.isNotEmpty) {
            _errorMessage = message; // e.g. "No birthdays today"
          }
        });
      } else {
        setState(() {
          _errorMessage = 'Server error while fetching birthdays';
        });
      }
    } catch (e) {
      debugPrint('❌ BIRTHDAY FETCH ERROR: $e');
      if (mounted) {
        setState(() {
          _errorMessage = 'Something went wrong while fetching birthdays';
        });
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.sizeOf(context);

    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: false,
        backgroundColor: whiteColor,
        titleSpacing: 0.0,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(
            Icons.arrow_back,
            color: blackColor,
          ),
        ),
        title: Text(
          // You can add a key in your localization,
          // or just use a hardcoded string here
          tr(context, 'birthday.title'),
          style: medium18Black,
        ),
      ),
      body: RefreshIndicator(
        onRefresh: _fetchBirthdays,
        child: Stack(
          children: [
            ListView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: const EdgeInsets.fromLTRB(
                fixPadding * 2.0,
                fixPadding * 3.0,
                fixPadding * 2.0,
                fixPadding * 2.0,
              ),
              children: [
                if (_isLoading)
                  const SizedBox(height: 200), // space for loader overlay
                if (!_isLoading && _members.isEmpty && _errorMessage != null)
                  _buildEmptyOrErrorWidget(),
                if (!_isLoading && _members.isNotEmpty)
                  ..._members.map((m) => _buildBirthdayCard(m, size)).toList(),
              ],
            ),
            if (_isLoading)
              Container(
                color: Colors.black.withOpacity(0.05),
                alignment: Alignment.center,
                child: const CircularProgressIndicator(),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildEmptyOrErrorWidget() {
    return Column(
      children: [
        const SizedBox(height: 80),
        Icon(
          Icons.cake_outlined,
          size: 72,
          color: Colors.grey.shade400,
        ),
        const SizedBox(height: 16),
        Text(
          _errorMessage ?? 'No birthdays today',
          style: regular16Black.copyWith(color: Colors.grey.shade600),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  Widget _buildBirthdayCard(BirthdayMember member, Size size) {
    final String celebrationText =
        '${member.celebrationYear ?? member.ageYears ?? 0} Year of Celebration';

    return Container(
      margin: const EdgeInsets.only(bottom: fixPadding * 2.0),
      padding: const EdgeInsets.all(fixPadding * 1.5),
      decoration: BoxDecoration(
        color: whiteColor,
        borderRadius: BorderRadius.circular(12.0),
        boxShadow: boxShadow2,
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Profile Photo
          SizedBox(
            height: size.height * 0.13,
            width: size.height * 0.13,
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12.0),
              child: _buildProfileImage(member.profilePhoto),
            ),
          ),
          const SizedBox(height: 12.0),
          // Name
          Text(
            member.name ?? '',
            style: medium18Black,
            textAlign: TextAlign.center,
            overflow: TextOverflow.ellipsis,
          ),
          const SizedBox(height: 6.0),
          // Celebration Year
          Text(
            celebrationText,
            style: regular15Grey.copyWith(fontStyle: FontStyle.italic),
            textAlign: TextAlign.center,
          ),
        ],
      ),
    );
  }

  Widget _buildProfileImage(String? profilePhoto) {
    if (profilePhoto == null || profilePhoto.isEmpty) {
      return Image.asset(
        "assets/profile/user-image.png",
        fit: BoxFit.cover,
      );
    }

    return Image.network(
      profilePhoto,
      fit: BoxFit.cover,
      errorBuilder: (_, __, ___) {
        return Image.asset(
          "assets/profile/user-image.png",
          fit: BoxFit.cover,
        );
      },
    );
  }
}

class BirthdayMember {
  final String? id;
  final String? name;
  final String? profilePhoto;
  final String? dob;
  final int? ageYears;
  final int? celebrationYear;

  BirthdayMember({
    this.id,
    this.name,
    this.profilePhoto,
    this.dob,
    this.ageYears,
    this.celebrationYear,
  });

  factory BirthdayMember.fromJson(Map<String, dynamic> json) {
    return BirthdayMember(
      id: json['id']?.toString(),
      name: json['name']?.toString(),
      profilePhoto: json['profile_photo']?.toString(),
      dob: json['dob']?.toString(),
      ageYears: json['age_years'] != null
          ? int.tryParse(json['age_years'].toString())
          : null,
      celebrationYear: json['celebration_year'] != null
          ? int.tryParse(json['celebration_year'].toString())
          : null,
    );
  }
}
