// lib/screens/celebration/CelebrationSend.dart

import 'dart:convert';

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

// Global theme
import 'package:fl_sevengen_society_user_app/theme/theme.dart';

class CelebrationSend extends StatefulWidget {
  final Map<String, dynamic> member;
  final String type; // birthday | anniversary | companyopen
  final String dateString; // yyyy-MM-dd
  final List<dynamic> templates; // [{id, key, message}]

  const CelebrationSend({
    super.key,
    required this.member,
    required this.type,
    required this.dateString,
    required this.templates,
  });

  @override
  State<CelebrationSend> createState() => _CelebrationSendState();
}

class _CelebrationSendState extends State<CelebrationSend> {
  int? selectedTemplateId;
  String? selectedMessageText;
  bool isSending = false;

  final String sendApiUrl =
      'https://rmbferodeunited.in/api/celebrationsend.php';

  // Local colors (no conflict with theme.dart)
  static const Color _gradientPink1 = Color(0xFFFD5790);
  static const Color _gradientPink2 = Color(0xFFFB9BB5);

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

    print('--- CelebrationSend initState ---');
    print('Member: ${widget.member}');
    print('Type: ${widget.type}');
    print('Date: ${widget.dateString}');
    print('Templates count: ${widget.templates.length}');

    if (widget.templates.isNotEmpty) {
      selectedTemplateId = widget.templates.first['id'];
      selectedMessageText =
          (widget.templates.first['message'] ?? '').toString();
    }
  }

  Future<void> sendCelebration() async {
    if (selectedMessageText == null ||
        selectedMessageText!.trim().isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('Please select a message')),
      );
      return;
    }

    setState(() => isSending = true);

    try {
      final prefs = await SharedPreferences.getInstance();

      // Sender (logged-in user) — from SharedPreferences
      final String wishRid = prefs.getString('rid_no') ?? '';
      final String wishName = prefs.getString('member_name') ?? '';
      final String wishPhone = prefs.getString('member_phone') ?? '';

      if (wishRid.isEmpty) {
        throw Exception('Sender RID not found');
      }

      // Celebration member (receiver)
      final String celebRid =
      (widget.member['rid_no'] ?? '').toString();
      final String celebName =
      (widget.member['full_name'] ?? '').toString();
      final String celebPhone =
      (widget.member['phone'] ??
          widget.member['profile_phone'] ??
          '')
          .toString();

      final Map<String, dynamic> body = {
        "celeb_rid": celebRid,
        "celeb_name": celebName,
        "celeb_phone": celebPhone,
        "wish_rid": wishRid, // always from SharedPreferences
        "wish_name": wishName,
        "wish_phone": wishPhone,
        "message": selectedMessageText,
        "type": widget.type,
        "date": widget.dateString,
      };

      final String jsonBody = jsonEncode(body);

      print('--- CelebrationSend Request ---');
      print('URL: $sendApiUrl');
      print('JSON: $jsonBody');

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

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

      if (response.statusCode == 200) {
        final Map<String, dynamic> resp =
        jsonDecode(response.body);
        print('Decoded response: $resp');

        if (resp['status'] == 'success') {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Sent successfully')),
          );
          Navigator.pop(context, true);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content:
              Text(resp['message'] ?? 'Send failed'),
            ),
          );
        }
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content:
            Text('Server error: ${response.statusCode}'),
          ),
        );
      }
    } catch (e, st) {
      print('Error in sendCelebration: $e');
      print('StackTrace: $st');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text(e.toString())),
      );
    } finally {
      if (mounted) {
        setState(() => isSending = false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final String name =
    (widget.member['full_name'] ?? '').toString();
    final String imageUrl =
    (widget.member['image_url'] ??
        widget.member['profile_image'] ??
        '')
        .toString();

    return Scaffold(
      appBar: AppBar(
        backgroundColor: primaryColor, // primary background
        elevation: 0,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white, // white icon
          ),
          onPressed: () => Navigator.pop(context),
        ),
        title: const Text(
          'Celebration',
          style: TextStyle(
            fontSize: 18, // font size 18
            fontWeight: FontWeight.w600,
            color: Colors.white, // white text
            fontFamily: 'Inter',
          ),
        ),
        foregroundColor: Colors.white,
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(fixPadding * 2),
          child: Column(
            children: [
              // Avatar
              Container(
                padding: const EdgeInsets.all(4),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  gradient: LinearGradient(
                    colors: [_gradientPink1, _gradientPink2],
                  ),
                ),
                child: CircleAvatar(
                  radius: 64,
                  backgroundColor: whiteColor,
                  backgroundImage:
                  imageUrl.isNotEmpty
                      ? NetworkImage(imageUrl)
                      : null,
                  child: imageUrl.isEmpty
                      ? const Icon(
                    Icons.person,
                    size: 64,
                    color: greyColor,
                  )
                      : null,
                ),
              ),
              const SizedBox(height: fixPadding * 2),

              Text(
                name.isEmpty ? 'Member' : name,
                style: semibold18Black33.copyWith(
                  fontSize: 22,
                ),
              ),

              const SizedBox(height: fixPadding / 2),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(
                    Icons.calendar_month,
                    size: 18,
                    color: _gradientPink1,
                  ),
                  const SizedBox(width: 6),
                  Text(
                    widget.dateString,
                    style: medium14Grey,
                  ),
                ],
              ),

              const SizedBox(height: fixPadding * 3),

              Align(
                alignment: Alignment.centerLeft,
                child: Text(
                  'Select message',
                  style: medium14Grey.copyWith(
                    color: black33Color,
                  ),
                ),
              ),
              const SizedBox(height: 8),

              DropdownButtonFormField<int>(
                value: selectedTemplateId,
                isExpanded: true,
                decoration: InputDecoration(
                  contentPadding:
                  const EdgeInsets.symmetric(
                    horizontal: 14,
                    vertical: 14,
                  ),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                items: widget.templates
                    .map<DropdownMenuItem<int>>((tpl) {
                  return DropdownMenuItem<int>(
                    value: tpl['id'],
                    child: Text(
                      (tpl['message'] ?? '').toString(),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  );
                }).toList(),
                onChanged: (val) {
                  setState(() {
                    selectedTemplateId = val;
                    final sel =
                    widget.templates.firstWhere(
                          (t) => t['id'] == val,
                      orElse: () => {},
                    );
                    selectedMessageText =
                        (sel['message'] ?? '').toString();
                  });

                  print(
                      'Template changed to ID: $val, text: $selectedMessageText');
                },
              ),

              const SizedBox(height: fixPadding * 3),

              Row(
                children: [
                  Expanded(
                    child: OutlinedButton(
                      onPressed: isSending
                          ? null
                          : () => Navigator.pop(context),
                      style: OutlinedButton.styleFrom(
                        padding:
                        const EdgeInsets.symmetric(
                          vertical: fixPadding * 1.2,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius:
                          BorderRadius.circular(12),
                        ),
                      ),
                      child: const Text(
                        'Cancel',
                        style: medium14Black33,
                      ),
                    ),
                  ),
                  const SizedBox(width: fixPadding),
                  Expanded(
                    child: ElevatedButton.icon(
                      onPressed: isSending
                          ? null
                          : sendCelebration,
                      icon: isSending
                          ? const SizedBox(
                        width: 18,
                        height: 18,
                        child:
                        CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor:
                          AlwaysStoppedAnimation<
                              Color>(whiteColor),
                        ),
                      )
                          : const Icon(
                        Icons.card_giftcard,
                        color: whiteColor,
                      ),
                      label: Text(
                        isSending
                            ? 'Sending...'
                            : 'Send',
                        style: semibold18White.copyWith(
                          fontSize: 16,
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _gradientPink1,
                        padding:
                        const EdgeInsets.symmetric(
                          vertical: fixPadding * 1.2,
                        ),
                        shape: RoundedRectangleBorder(
                          borderRadius:
                          BorderRadius.circular(12),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}
