// lib/screens/announcements_screen.dart
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';

/// Model used consistently
class AnnouncementModel {
  final int id;
  final int ridNo;
  final String fullName;
  final String title;
  final String message;
  final DateTime createdAt;

  AnnouncementModel({
    required this.id,
    required this.ridNo,
    required this.fullName,
    required this.title,
    required this.message,
    required this.createdAt,
  });

  factory AnnouncementModel.fromJson(Map<String, dynamic> json) {
    // helper to extract string from several possible keys
    String extractString(List<String> keys, String fallback) {
      for (final k in keys) {
        if (json.containsKey(k) && json[k] != null && json[k].toString().trim().isNotEmpty) {
          return json[k].toString();
        }
      }
      return fallback;
    }

    DateTime parseDate(dynamic value) {
      if (value == null) return DateTime.now();
      try {
        return DateTime.parse(value.toString());
      } catch (_) {
        return DateTime.now();
      }
    }

    final id = int.tryParse(extractString(['id', 'ID'], '0')) ?? 0;
    final ridNo = int.tryParse(extractString(['rid_no', 'ridNo', 'rid'], '0')) ?? 0;
    final fullName = extractString(['full_name', 'fullName', 'name'], 'Unknown');
    final title = extractString(['title', 'Title', 'announcement_title', 'ann_title', 'titile'], '');
    final message = extractString(['message', 'msg', 'description'], '');
    final createdAt = parseDate(json['created_at'] ?? json['createdAt']);

    return AnnouncementModel(
      id: id,
      ridNo: ridNo,
      fullName: fullName,
      title: title,
      message: message,
      createdAt: createdAt,
    );
  }
}

class AnnouncementsScreen extends StatefulWidget {
  const AnnouncementsScreen({Key? key}) : super(key: key);

  @override
  State<AnnouncementsScreen> createState() => _AnnouncementsScreenState();
}

class _AnnouncementsScreenState extends State<AnnouncementsScreen> {
  // Change to your server
  final String baseUrl = 'https://rmbferodeunited.in/api';

  List<AnnouncementModel> announcements = [];
  bool loading = false;

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

  Future<void> fetchAnnouncements() async {
    setState(() => loading = true);
    final uri = Uri.parse('$baseUrl/announcement.php');

    try {
      final res = await http.get(uri);
      // Debug print
      print('GET ${uri.toString()} -> ${res.statusCode} : ${res.body}');

      if (res.statusCode == 200) {
        final body = json.decode(res.body);
        if (body is Map && body['success'] == true && body['data'] is List) {
          final List<dynamic> data = body['data'];
          final parsed = data.map<AnnouncementModel>((dynamic item) {
            final Map<String, dynamic> map = (item is Map) ? Map<String,
                dynamic>.from(item as Map) : <String, dynamic>{};
            return AnnouncementModel.fromJson(map);
          }).toList();
          setState(() => announcements = parsed);
        } else {
          setState(() => announcements = []);
        }
      } else {
        setState(() => announcements = []);
      }
    } catch (e, st) {
      print('fetchAnnouncements error: $e\n$st');
      setState(() => announcements = []);
    } finally {
      setState(() => loading = false);
    }
  }

  /// Robust retrieval for rid_no from SharedPreferences.
  /// Accepts int or String (or missing) and returns 0 fallback.
  Future<int> _getRidNoFromShared() async {
    final prefs = await SharedPreferences.getInstance();

    // Use prefs.get to get the raw dynamic value (works for any type)
    final dynamic raw = prefs.get('rid_no');

    if (raw == null) {
      return 0;
    }

    if (raw is int) {
      return raw;
    }

    if (raw is String) {
      final parsed = int.tryParse(raw);
      return parsed ?? 0;
    }

    // If stored in another numeric type (double), convert
    if (raw is double) {
      return raw.toInt();
    }

    // Fallback
    return 0;
  }

  Future<void> _showAddDialog() async {
    final titleCtrl = TextEditingController();
    final msgCtrl = TextEditingController();
    final formKey = GlobalKey<FormState>();
    bool submitting = false;

    await showDialog(
      context: context,
      builder: (context) {
        return StatefulBuilder(builder: (context, setDialogState) {
          return AlertDialog(
            title: const Text('New Broadcast'),
            content: Form(
              key: formKey,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextFormField(
                    controller: titleCtrl,
                    decoration: const InputDecoration(labelText: 'Title'),
                    validator: (v) =>
                    (v == null || v
                        .trim()
                        .isEmpty) ? 'Enter title' : null,
                  ),
                  const SizedBox(height: 8),
                  TextFormField(
                    controller: msgCtrl,
                    decoration: const InputDecoration(labelText: 'Message'),
                    maxLines: 4,
                    validator: (v) =>
                    (v == null || v
                        .trim()
                        .isEmpty) ? 'Enter message' : null,
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: submitting ? null : () =>
                    Navigator.of(context).pop(),
                child: const Text('Cancel'),
              ),
              ElevatedButton(
                onPressed: submitting
                    ? null
                    : () async {
                  if (!formKey.currentState!.validate()) return;
                  setDialogState(() => submitting = true);

                  final ridNo = await _getRidNoFromShared();
                  final uri = Uri.parse('$baseUrl/announcement.php');

                  try {
                    final res = await http.post(uri, body: {
                      'rid_no': ridNo.toString(),
                      'title': titleCtrl.text.trim(),
                      'message': msgCtrl.text.trim(),
                    });

                    print('POST ${uri.toString()} -> ${res.statusCode} : ${res
                        .body}');

                    if (res.statusCode == 200) {
                      final body = json.decode(res.body);
                      if (body is Map && body['success'] == true) {
                        // If server returned created announcement object, we could parse and insert locally.
                        // Simpler: refresh entire list.
                        await fetchAnnouncements();
                        Navigator.of(context).pop();
                        return;
                      } else {
                        final msg = (body is Map && body['message'] != null)
                            ? body['message'].toString()
                            : 'Server error';
                        ScaffoldMessenger.of(context).showSnackBar(
                            SnackBar(content: Text(msg)));
                      }
                    } else {
                      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                          content: Text('Server error')));
                    }
                  } catch (e) {
                    print('POST error: $e');
                    ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
                        content: Text('Network error')));
                  } finally {
                    setDialogState(() => submitting = false);
                  }
                },
                child: submitting
                    ? const SizedBox(width: 18,
                    height: 18,
                    child: CircularProgressIndicator(strokeWidth: 2))
                    : const Text('Submit'),
              ),
            ],
          );
        });
      },
    );
  }

  String _monthShort(int m) {
    const months = [
      'Jan',
      'Feb',
      'Mar',
      'Apr',
      'May',
      'Jun',
      'Jul',
      'Aug',
      'Sep',
      'Oct',
      'Nov',
      'Dec'
    ];
    return months[m - 1];
  }

  String _formatDate(DateTime dt) {
    final day = dt.day.toString().padLeft(2, '0');
    final month = _monthShort(dt.month);
    final year = (dt.year % 100).toString().padLeft(2, '0');
    final hour = dt.hour.toString().padLeft(2, '0');
    final minute = dt.minute.toString().padLeft(2, '0');
    return "$day $month $year : $hour : $minute";
  }

  Widget _buildCard(AnnouncementModel a) {
    final timeStr = _formatDate(a.createdAt);
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0),
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: const [
                BoxShadow(color: Color.fromARGB(70, 0, 0, 0),
                    blurRadius: 8,
                    offset: Offset(0, 3)),
              ],
            ),
            padding: const EdgeInsets.fromLTRB(16, 12, 12, 12),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Show title, fallback to "(no title)" if empty
                Text(
                  a.title.isNotEmpty ? a.title : '(no title)',
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 6),
                Text(
                  a.message,
                  // No maxLines, no overflow → show full content
                  style: const TextStyle(
                    fontSize: 13,
                    color: Colors.black54,
                  ),
                ),
                const SizedBox(height: 12),
                Container(height: 1, color: Colors.grey.shade300),
                const SizedBox(height: 8),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text("Post by : ${a.fullName}", style: const TextStyle(
                        fontSize: 12, color: Colors.black87)),
                    Text(timeStr, style: const TextStyle(
                        fontSize: 12, color: Colors.black87)),
                  ],
                ),
              ],
            ),
          ),
          Positioned(left: 4,
              top: 12,
              bottom: 12,
              child: Container(width: 8,
                  decoration: BoxDecoration(color: const Color(0xFF0C3C56),
                      borderRadius: BorderRadius.circular(4)))),
          if (DateTime
              .now()
              .difference(a.createdAt)
              .inDays <= 7)
            Positioned(
              right: 12,
              top: 6,
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(color: const Color(0xFF0C3C56),
                    borderRadius: BorderRadius.circular(12)),
                child: const Text(
                    'New', style: TextStyle(color: Colors.white, fontSize: 12)),
              ),
            ),
        ],
      ),
    );
  }

  Widget _bottomSubmitButton() {
    return SafeArea(
      child: Container(
        width: double.infinity,
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: const Color(0xFF0E3A53),
            foregroundColor: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 16),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12)),
            elevation: 4,
          ),
          onPressed: _showAddDialog,
          child: const Text('New Broadcast', style: TextStyle(fontSize: 16)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'Broadcast Messages',
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w600,
            color: Colors.white,
          ),
        ),
        backgroundColor: const Color(0xFF0C3C56),
        foregroundColor: Colors.white,
        elevation: 0,
      ),
      body: loading
          ? const Center(child: CircularProgressIndicator(color: Color(0xFF0C3C56)))
          : RefreshIndicator(
        color: const Color(0xFF0C3C56),
        onRefresh: fetchAnnouncements,
        child: announcements.isEmpty
            ? ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          children: const [
            SizedBox(height: 120),
            Center(child: Text('No announcements')),
          ],
        )
            : ListView.builder(
          padding: const EdgeInsets.only(bottom: 120),
          itemCount: announcements.length,
          itemBuilder: (context, index) =>
              _buildCard(announcements[index]),
        ),
      ),
      bottomNavigationBar: _bottomSubmitButton(),
    );
  }
}
