import 'dart:convert';

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

import 'CelebrationSend.dart'; // <- new screen

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

  @override
  State<CelebrationToday> createState() => _CelebrationTodayState();
}

class _CelebrationTodayState extends State<CelebrationToday>
    with SingleTickerProviderStateMixin {
  TabController? tabController;

  List<dynamic> birthdayList = [];
  List<dynamic> anniversaryList = [];
  List<dynamic> companyOpenList = [];

  List<dynamic> birthdayTemplates = [];
  List<dynamic> anniversaryTemplates = [];
  List<dynamic> companyOpenTemplates = [];

  bool isLoading = true;
  String? errorMessage;

  final String apiUrl =
      'https://rmbferodeunited.in/api/celebration.php'; // celebration.php
  final String baseImageUrl =
      'https://rmbferodeunited.in/uploads/profile_photo/';

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 3, vsync: this);
    fetchCelebrations();
  }

  Future<void> fetchCelebrations() async {
    setState(() {
      isLoading = true;
      errorMessage = null;
    });

    final Map<String, dynamic> requestBody = {
      "date": DateTime.now().toIso8601String().substring(0, 10),
      "type": "all",
      "base_image_url": baseImageUrl,
    };

    try {
      final String jsonBody = jsonEncode(requestBody);

      print('--- CelebrationToday Request ---');
      print('URL: $apiUrl');
      print('JSON: $jsonBody');

      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {"Content-Type": "application/json"},
        body: jsonBody,
      );

      print('--- CelebrationToday Response ---');
      print('Status: ${response.statusCode}');
      print('Raw body: ${response.body}');

      if (response.statusCode == 200) {
        final data = json.decode(response.body);

        if (data['status'] == 'success') {
          final Map<String, dynamic> dataSection =
          (data['data'] ?? {}) as Map<String, dynamic>;

          setState(() {
            birthdayList = dataSection['birthday'] ?? [];
            anniversaryList = dataSection['anniversary'] ?? [];
            companyOpenList = dataSection['company_open'] ?? [];

            final templates = data['templates'] ?? {};
            birthdayTemplates = templates['birthday'] ?? [];
            anniversaryTemplates = templates['anniversary'] ?? [];
            companyOpenTemplates = templates['companyopen'] ?? [];

            isLoading = false;
          });

          print('Counts -> B:${birthdayList.length} '
              'A:${anniversaryList.length} C:${companyOpenList.length}');
        } else {
          setState(() {
            isLoading = false;
            errorMessage = data['message']?.toString() ?? 'Unknown error';
          });
        }
      } else {
        setState(() {
          isLoading = false;
          errorMessage = 'HTTP ${response.statusCode}';
        });
      }
    } catch (e) {
      setState(() {
        isLoading = false;
        errorMessage = 'Failed to load data';
      });
      print('Error in fetchCelebrations: $e');
    }
  }

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

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor,
        elevation: 0.0,
        titleSpacing: 0.0,
        toolbarHeight: 50.0,
        centerTitle: false,
        automaticallyImplyLeading: false,
        leading: IconButton(
          onPressed: () => Navigator.pop(context),
          icon: const Icon(Icons.arrow_back, color: Colors.white),
        ),
        title: Text(
          getTranslate(context, 'celebration.celebration_today'),
          style: const TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
            fontFamily: 'Inter',
          ),
        ),
        foregroundColor: Colors.white,
      ),
      body: Column(
        children: [
          // ✅ Added SizedBox with 20 space between AppBar and TabBar
          const SizedBox(height: 25),
          tabBar(),
          Expanded(
            child: isLoading
                ? const Center(child: CircularProgressIndicator())
                : (errorMessage != null
                ? Center(child: Text(errorMessage!, style: medium14Grey))
                : TabBarView(
              controller: tabController,
              children: [
                celebrationTabContent(
                  size: size,
                  members: birthdayList,
                  type: 'birthday',
                  templates: birthdayTemplates,
                ),
                celebrationTabContent(
                  size: size,
                  members: anniversaryList,
                  type: 'anniversary',
                  templates: anniversaryTemplates,
                ),
                celebrationTabContent(
                  size: size,
                  members: companyOpenList,
                  type: 'companyopen',
                  templates: companyOpenTemplates,
                ),
              ],
            )),
          ),
        ],
      ),
    );
  }

  Widget celebrationTabContent({
    required Size size,
    required List<dynamic> members,
    required String type,
    required List<dynamic> templates,
  }) {
    final String emptyText;
    if (type == 'birthday') {
      emptyText = getTranslate(context, 'celebration_birthday_today');
    } else if (type == 'anniversary') {
      emptyText = getTranslate(context, 'celebration.no_anniversary_today');
    } else {
      emptyText = getTranslate(context, 'celebration_company_open_today');
    }

    return members.isEmpty
        ? Center(child: Text(emptyText, style: medium14Grey))
        : ListView.builder(
      padding: const EdgeInsets.symmetric(vertical: fixPadding * 0.5),
      physics: const BouncingScrollPhysics(),
      itemCount: members.length,
      itemBuilder: (context, index) {
        final item = members[index];

        final String name =
        (item['full_name'] ?? '').toString().trim();
        final String imageUrl = (item['image_url'] ??
            item['profile_image'] ??
            '')
            .toString()
            .trim();

        String dateText = '';
        if (type == 'birthday') {
          dateText = (item['dob'] ?? '').toString();
        } else if (type == 'anniversary') {
          dateText = (item['anniversary'] ?? '').toString();
        } else {
          dateText = (item['company_open_date'] ?? '').toString();
        }

        return GestureDetector(
          onTap: () {
            print('Tap member: $name, type: $type, date: $dateText');

            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (_) => CelebrationSend(
                  member: item,
                  type: type,
                  dateString: dateText,
                  templates: templates,
                ),
              ),
            );
          },
          child: Container(
            margin: const EdgeInsets.symmetric(
              vertical: fixPadding,
              horizontal: fixPadding * 2.0,
            ),
            padding: const EdgeInsets.all(fixPadding * 0.8),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(10.0),
              color: whiteColor,
              boxShadow: [
                BoxShadow(
                  color: blackColor.withOpacity(0.2),
                  blurRadius: 6.0,
                ),
              ],
            ),
            child: Row(
              children: [
                Container(
                  height: 58.0,
                  width: 58.0,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(5.0),
                    color: greyColor.withOpacity(0.2),
                    image: imageUrl.isNotEmpty
                        ? DecorationImage(
                      image: NetworkImage(imageUrl),
                      fit: BoxFit.cover,
                    )
                        : null,
                  ),
                  child: imageUrl.isEmpty
                      ? const Icon(Icons.person, color: greyColor)
                      : null,
                ),
                widthSpace,
                Expanded(
                  child: Text(
                    name.isEmpty ? 'Member' : name,
                    style: semibold16Black33,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget tabBar() {
    return Stack(
      children: [
        Container(
          height: 35,
          decoration: const BoxDecoration(
            border: Border(
              bottom: BorderSide(
                color: Color(0xFFD9D9D9),
                width: 2,
              ),
            ),
          ),
        ),
        SizedBox(
          height: 35,
          child: TabBar(
            controller: tabController,
            labelStyle: semibold16Primary.copyWith(fontFamily: 'Inter'),
            labelColor: primaryColor,
            indicatorColor: primaryColor,
            unselectedLabelColor: greyColor,
            tabs: [
              Tab(text: getTranslate(context, 'celebration.birthday')),
              Tab(text: getTranslate(context, 'celebration.anniversary')),
              Tab(text: getTranslate(context, 'celebration.company_open')),
            ],
          ),
        ),
      ],
    );
  }
}
