// lib/features/admin/tabs/messages/status_panel.dart

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class StatusPanel extends StatefulWidget {
  final VoidCallback? onBack;
  final String? myEmail;
  final String? myName;
  final String? myPic;

  const StatusPanel({
    super.key,
    this.onBack,
    this.myEmail,
    this.myName,
    this.myPic,
  });

  @override
  State<StatusPanel> createState() => _StatusPanelState();
}

class _StatusPanelState extends State<StatusPanel> {
  static const String _statusCollection = 'status_updates';
  static const Color _brandGreen = Color.fromARGB(255, 2, 105, 48);
  static const Color _brandGold = Color.fromARGB(255, 204, 117, 4);
  static const Color _brandDark = Color(0xFF17231C);
  static const Color _muted = Color(0xFF66756C);
  static const Color _border = Color(0xFFE2E8E4);

  String _formatStatusTime(Timestamp? timestamp) {
    if (timestamp == null) return 'Just now';
    final date = timestamp.toDate();
    final now = DateTime.now();
    final diff = now.difference(date);
    final time = TimeOfDay.fromDateTime(date).format(context);

    if (diff.inDays == 0 && now.day == date.day) return 'Today at $time';
    if (diff.inDays <= 1) return 'Yesterday at $time';
    return '${date.day}/${date.month}/${date.year} at $time';
  }

  Future<void> _openCreateTextStatus() async {
    final controller = TextEditingController();

    final text = await showDialog<String>(
      context: context,
      builder: (ctx) {
        final width = MediaQuery.of(ctx).size.width;
        return Dialog(
          insetPadding: EdgeInsets.symmetric(
            horizontal: width < 520 ? 16 : 40,
            vertical: 24,
          ),
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
          child: ConstrainedBox(
            constraints: const BoxConstraints(maxWidth: 520),
            child: Padding(
              padding: const EdgeInsets.all(22),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 42,
                        height: 42,
                        decoration: BoxDecoration(
                          color: _brandGreen.withOpacity(.08),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: const Icon(Icons.edit_note_rounded, color: _brandGreen),
                      ),
                      const SizedBox(width: 12),
                      const Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Create status update',
                              style: TextStyle(
                                color: _brandDark,
                                fontSize: 18,
                                fontWeight: FontWeight.w800,
                              ),
                            ),
                            SizedBox(height: 2),
                            Text(
                              'Visible for 24 hours',
                              style: TextStyle(color: _muted, fontSize: 12),
                            ),
                          ],
                        ),
                      ),
                      IconButton(
                        onPressed: () => Navigator.pop(ctx),
                        icon: const Icon(Icons.close_rounded),
                      ),
                    ],
                  ),
                  const SizedBox(height: 18),
                  TextField(
                    controller: controller,
                    autofocus: true,
                    minLines: 4,
                    maxLines: 7,
                    maxLength: 150,
                    decoration: InputDecoration(
                      hintText: 'Share an update with your Rockview contacts...',
                      filled: true,
                      fillColor: const Color(0xFFF5F8F6),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(14),
                        borderSide: const BorderSide(color: _border),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(14),
                        borderSide: const BorderSide(color: _border),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(14),
                        borderSide: const BorderSide(color: _brandGreen, width: 1.4),
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  Row(
                    children: [
                      TextButton(
                        onPressed: () => Navigator.pop(ctx),
                        child: const Text('Cancel'),
                      ),
                      const Spacer(),
                      FilledButton.icon(
                        onPressed: () {
                          final value = controller.text.trim();
                          if (value.isNotEmpty) Navigator.pop(ctx, value);
                        },
                        style: FilledButton.styleFrom(
                          backgroundColor: _brandGreen,
                          foregroundColor: Colors.white,
                        ),
                        icon: const Icon(Icons.send_rounded, size: 18),
                        label: const Text('Post status'),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );

    controller.dispose();
    if (text == null || text.isEmpty) return;

    try {
      await FirebaseFirestore.instance.collection(_statusCollection).add({
        'text': text,
        'authorName': (widget.myName?.trim().isNotEmpty ?? false)
            ? widget.myName!.trim()
            : 'Rockview User',
        'authorEmail': widget.myEmail?.trim() ?? '',
        'authorPic': widget.myPic ?? '',
        'timestamp': FieldValue.serverTimestamp(),
        'expiresAt': Timestamp.fromDate(
          DateTime.now().add(const Duration(hours: 24)),
        ),
      });

      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Status updated successfully.'),
          backgroundColor: _brandGreen,
          behavior: SnackBarBehavior.floating,
        ),
      );
    } catch (_) {
      if (!mounted) return;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Failed to update status.'),
          backgroundColor: Colors.redAccent,
          behavior: SnackBarBehavior.floating,
        ),
      );
    }
  }

  Widget _statusAvatar({
    String? image,
    bool hasUpdate = true,
    IconData fallback = Icons.person,
    double radius = 23,
  }) {
    ImageProvider? provider;
    if (image != null && image.trim().startsWith('http')) {
      provider = NetworkImage(image.trim());
    }

    return Container(
      padding: const EdgeInsets.all(2.5),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(
          color: hasUpdate ? _brandGold : Colors.transparent,
          width: 2.4,
        ),
      ),
      child: CircleAvatar(
        radius: radius,
        backgroundColor: const Color(0xFFE7ECE9),
        backgroundImage: provider,
        child: provider == null
            ? Icon(fallback, color: _brandGreen, size: radius)
            : null,
      ),
    );
  }

  Widget _header() {
    return Container(
      height: 66,
      padding: const EdgeInsets.symmetric(horizontal: 14),
      decoration: const BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(color: _border)),
      ),
      child: Row(
        children: [
          if (widget.onBack != null)
            IconButton(
              tooltip: 'Back',
              onPressed: widget.onBack,
              icon: const Icon(Icons.arrow_back_rounded, color: _brandDark),
            ),
          if (widget.onBack != null) const SizedBox(width: 4),
          Container(
            width: 38,
            height: 38,
            decoration: BoxDecoration(
              color: _brandGreen.withOpacity(.08),
              borderRadius: BorderRadius.circular(11),
            ),
            child: const Icon(Icons.auto_awesome_motion_rounded, color: _brandGreen),
          ),
          const SizedBox(width: 12),
          const Expanded(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Status & Updates',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: _brandDark,
                    fontSize: 18,
                    fontWeight: FontWeight.w800,
                  ),
                ),
                SizedBox(height: 2),
                Text(
                  'Live updates from your Rockview contacts',
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: _muted, fontSize: 11.5),
                ),
              ],
            ),
          ),
          IconButton(
            tooltip: 'New status',
            onPressed: _openCreateTextStatus,
            icon: const Icon(Icons.add_circle_outline_rounded, color: _brandGreen),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final statusStream = FirebaseFirestore.instance
        .collection(_statusCollection)
        .where('expiresAt', isGreaterThan: Timestamp.now())
        .orderBy('expiresAt', descending: true)
        .snapshots();

    return Scaffold(
      backgroundColor: const Color(0xFFF5F7F6),
      floatingActionButton: FloatingActionButton.extended(
        heroTag: 'status_text_update',
        onPressed: _openCreateTextStatus,
        backgroundColor: _brandGreen,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.edit_rounded, size: 19),
        label: const Text('New status'),
      ),
      body: SafeArea(
        top: false,
        child: Column(
          children: [
            _header(),
            Expanded(
              child: LayoutBuilder(
                builder: (context, constraints) {
                  final horizontal = constraints.maxWidth > 860
                      ? (constraints.maxWidth - 760) / 2
                      : 12.0;

                  return StreamBuilder<QuerySnapshot>(
                    stream: statusStream,
                    builder: (context, snapshot) {
                      final docs = snapshot.data?.docs ?? const [];

                      return RefreshIndicator(
                        color: _brandGreen,
                        onRefresh: () async {
                          await FirebaseFirestore.instance
                              .collection(_statusCollection)
                              .where('expiresAt', isGreaterThan: Timestamp.now())
                              .limit(1)
                              .get();
                        },
                        child: ListView(
                          physics: const AlwaysScrollableScrollPhysics(
                            parent: BouncingScrollPhysics(),
                          ),
                          padding: EdgeInsets.fromLTRB(
                            horizontal,
                            16,
                            horizontal,
                            96,
                          ),
                          children: [
                            Container(
                              padding: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(16),
                                border: Border.all(color: _border),
                              ),
                              child: InkWell(
                                borderRadius: BorderRadius.circular(14),
                                onTap: _openCreateTextStatus,
                                child: Row(
                                  children: [
                                    Stack(
                                      clipBehavior: Clip.none,
                                      children: [
                                        _statusAvatar(
                                          image: widget.myPic,
                                          hasUpdate: false,
                                          radius: 24,
                                        ),
                                        const Positioned(
                                          right: -1,
                                          bottom: 0,
                                          child: CircleAvatar(
                                            radius: 9,
                                            backgroundColor: _brandGreen,
                                            child: Icon(
                                              Icons.add_rounded,
                                              size: 13,
                                              color: Colors.white,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                    const SizedBox(width: 14),
                                    const Expanded(
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Text(
                                            'My status',
                                            style: TextStyle(
                                              color: _brandDark,
                                              fontWeight: FontWeight.w800,
                                              fontSize: 15.5,
                                            ),
                                          ),
                                          SizedBox(height: 3),
                                          Text(
                                            'Share an update for the next 24 hours',
                                            style: TextStyle(
                                              color: _muted,
                                              fontSize: 12.5,
                                            ),
                                          ),
                                        ],
                                      ),
                                    ),
                                    const Icon(
                                      Icons.chevron_right_rounded,
                                      color: _muted,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            const SizedBox(height: 18),
                            const Text(
                              'RECENT UPDATES',
                              style: TextStyle(
                                color: _brandGreen,
                                fontSize: 11,
                                letterSpacing: .9,
                                fontWeight: FontWeight.w900,
                              ),
                            ),
                            const SizedBox(height: 10),
                            if (snapshot.connectionState == ConnectionState.waiting &&
                                !snapshot.hasData)
                              const Padding(
                                padding: EdgeInsets.symmetric(vertical: 80),
                                child: Center(
                                  child: CircularProgressIndicator(
                                    color: _brandGreen,
                                    strokeWidth: 2.2,
                                  ),
                                ),
                              )
                            else if (docs.isEmpty)
                              Container(
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 24,
                                  vertical: 54,
                                ),
                                decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(16),
                                  border: Border.all(color: _border),
                                ),
                                child: const Column(
                                  children: [
                                    Icon(
                                      Icons.notifications_none_rounded,
                                      size: 52,
                                      color: Color(0xFFB7C2BB),
                                    ),
                                    SizedBox(height: 14),
                                    Text(
                                      'No recent updates',
                                      style: TextStyle(
                                        color: _brandDark,
                                        fontWeight: FontWeight.w800,
                                        fontSize: 16,
                                      ),
                                    ),
                                    SizedBox(height: 6),
                                    Text(
                                      'Updates from your contacts will appear here.',
                                      textAlign: TextAlign.center,
                                      style: TextStyle(color: _muted, fontSize: 13),
                                    ),
                                  ],
                                ),
                              )
                            else
                              ...docs.map((doc) {
                                final data = doc.data() as Map<String, dynamic>;
                                final authorName =
                                    (data['authorName'] ?? 'Rockview User').toString();
                                final text = (data['text'] ?? '').toString();
                                final timestamp = data['timestamp'] as Timestamp?;
                                final image = data['authorPic']?.toString();

                                return Padding(
                                  padding: const EdgeInsets.only(bottom: 10),
                                  child: Material(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(15),
                                    child: InkWell(
                                      borderRadius: BorderRadius.circular(15),
                                      onTap: () {
                                        showDialog<void>(
                                          context: context,
                                          builder: (ctx) => AlertDialog(
                                            shape: RoundedRectangleBorder(
                                              borderRadius: BorderRadius.circular(18),
                                            ),
                                            title: Text(authorName),
                                            content: Text(
                                              text,
                                              style: const TextStyle(
                                                fontSize: 16,
                                                height: 1.45,
                                              ),
                                            ),
                                            actions: [
                                              TextButton(
                                                onPressed: () => Navigator.pop(ctx),
                                                child: const Text('Close'),
                                              ),
                                            ],
                                          ),
                                        );
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.all(14),
                                        decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(15),
                                          border: Border.all(color: _border),
                                        ),
                                        child: Row(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            _statusAvatar(image: image, radius: 22),
                                            const SizedBox(width: 13),
                                            Expanded(
                                              child: Column(
                                                crossAxisAlignment: CrossAxisAlignment.start,
                                                children: [
                                                  Row(
                                                    children: [
                                                      Expanded(
                                                        child: Text(
                                                          authorName,
                                                          maxLines: 1,
                                                          overflow: TextOverflow.ellipsis,
                                                          style: const TextStyle(
                                                            color: _brandDark,
                                                            fontWeight: FontWeight.w800,
                                                            fontSize: 14.5,
                                                          ),
                                                        ),
                                                      ),
                                                      const SizedBox(width: 8),
                                                      Text(
                                                        _formatStatusTime(timestamp),
                                                        style: const TextStyle(
                                                          color: _muted,
                                                          fontSize: 10.5,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                  const SizedBox(height: 5),
                                                  Text(
                                                    text,
                                                    maxLines: 3,
                                                    overflow: TextOverflow.ellipsis,
                                                    style: const TextStyle(
                                                      color: _muted,
                                                      height: 1.4,
                                                      fontSize: 13,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }),
                          ],
                        ),
                      );
                    },
                  );
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
