import 'package:flutter/material.dart';

import '../../../../core/services/campus_announcements_service.dart';
import 'announcement_feed_view.dart' show AnnouncementComposerDialog;

const Color _green = Color.fromARGB(255, 2, 105, 48);
const Color _gold = Color.fromARGB(255, 204, 117, 4);
const Color _border = Color(0xFFE3E8EE);
const Color _muted = Color(0xFF66727E);

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

  @override
  State<DraftAnnouncementsSubTab> createState() => _DraftAnnouncementsSubTabState();
}

class _DraftAnnouncementsSubTabState extends State<DraftAnnouncementsSubTab> {
  final List<CampusAnnouncement> _items = [];
  bool _loading = true;
  String? _error;
  int? _busyId;

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

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = null;
    });
    try {
      final page = await CampusAnnouncementsService.getAnnouncements(scope: 'mine', page: 1, limit: 100);
      if (!mounted) return;
      setState(() {
        _items
          ..clear()
          ..addAll(page.announcements.where((a) => a.status.toLowerCase() == 'draft' || a.status.toLowerCase() == 'scheduled'));
        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _loading = false;
        _error = _cleanError(e);
      });
    }
  }

  Future<void> _create() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const AnnouncementComposerDialog(),
    );
    if (result == true) await _load();
  }

  Future<void> _edit(CampusAnnouncement item) async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => AnnouncementComposerDialog(announcement: item),
    );
    if (result == true) await _load();
  }

  Future<void> _publish(CampusAnnouncement item) async {
    setState(() => _busyId = item.id);
    try {
      await CampusAnnouncementsService.updateAnnouncement(item.id, <String, dynamic>{
        'status': 'published',
        'scheduled_at': null,
      });
      if (!mounted) return;
      _show('Announcement published.');
      await _load();
    } catch (e) {
      _show(_cleanError(e), error: true);
    } finally {
      if (mounted) setState(() => _busyId = null);
    }
  }

  void _show(String text, {bool error = false}) {
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(text), backgroundColor: error ? Colors.red.shade700 : _green, behavior: SnackBarBehavior.floating));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF3F5F7),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: _create,
        backgroundColor: _gold,
        foregroundColor: Colors.white,
        icon: const Icon(Icons.add_rounded),
        label: const Text('NEW NOTICE', style: TextStyle(fontWeight: FontWeight.w900)),
      ),
      body: RefreshIndicator(
        onRefresh: _load,
        color: _green,
        child: ListView(
          physics: const AlwaysScrollableScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(0, 12, 0, 100),
          children: [
            Container(
              padding: const EdgeInsets.all(18),
              decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(24), border: Border.all(color: _border)),
              child: LayoutBuilder(builder: (context, constraints) {
                final compact = constraints.maxWidth < 650;
                final copy = const Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Text('Drafts & Scheduled', style: TextStyle(fontSize: 21, fontWeight: FontWeight.w900, color: Color(0xFF182632))),
                  SizedBox(height: 5),
                  Text('Prepare notices privately, schedule them for later, or publish when ready.', style: TextStyle(color: _muted, fontSize: 12, height: 1.5)),
                ]);
                final count = Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(color: _gold.withOpacity(.1), borderRadius: BorderRadius.circular(999)),
                  child: Text('${_items.length} SAVED', style: const TextStyle(color: _gold, fontSize: 10, fontWeight: FontWeight.w900)),
                );
                if (compact) return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [copy, const SizedBox(height: 14), count]);
                return Row(children: [Expanded(child: copy), count]);
              }),
            ),
            const SizedBox(height: 14),
            if (_loading)
              const Padding(padding: EdgeInsets.symmetric(vertical: 110), child: Center(child: CircularProgressIndicator(color: _green)))
            else if (_error != null)
              Container(
                padding: const EdgeInsets.all(28),
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: _border)),
                child: Column(children: [
                  Icon(Icons.cloud_off_rounded, size: 46, color: Colors.red.shade300),
                  const SizedBox(height: 10),
                  Text(_error!, textAlign: TextAlign.center),
                  const SizedBox(height: 12),
                  TextButton.icon(onPressed: _load, icon: const Icon(Icons.refresh), label: const Text('TRY AGAIN')),
                ]),
              )
            else if (_items.isEmpty)
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 22, vertical: 70),
                decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: _border)),
                child: Column(children: [
                  Icon(Icons.edit_note_rounded, size: 62, color: Colors.grey.shade300),
                  const SizedBox(height: 12),
                  const Text('No drafts or scheduled notices', style: TextStyle(fontSize: 18, fontWeight: FontWeight.w900)),
                  const SizedBox(height: 7),
                  const Text('Create an announcement and save it as a draft or schedule it for later.', textAlign: TextAlign.center, style: TextStyle(color: _muted)),
                  const SizedBox(height: 16),
                  FilledButton.icon(onPressed: _create, style: FilledButton.styleFrom(backgroundColor: _green), icon: const Icon(Icons.add), label: const Text('Create notice')),
                ]),
              )
            else
              LayoutBuilder(builder: (context, constraints) {
                final columns = constraints.maxWidth >= 1100 ? 3 : constraints.maxWidth >= 700 ? 2 : 1;
                return GridView.builder(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  itemCount: _items.length,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: columns, crossAxisSpacing: 14, mainAxisSpacing: 14, mainAxisExtent: 330),
                  itemBuilder: (_, index) {
                    final item = _items[index];
                    return _DraftCard(
                      item: item,
                      busy: _busyId == item.id,
                      onEdit: () => _edit(item),
                      onPublish: () => _publish(item),
                    );
                  },
                );
              }),
          ],
        ),
      ),
    );
  }
}

class _DraftCard extends StatelessWidget {
  final CampusAnnouncement item;
  final bool busy;
  final VoidCallback onEdit;
  final VoidCallback onPublish;
  const _DraftCard({required this.item, required this.busy, required this.onEdit, required this.onPublish});

  @override
  Widget build(BuildContext context) {
    final scheduled = item.status.toLowerCase() == 'scheduled';
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.circular(22), border: Border.all(color: scheduled ? _gold.withOpacity(.45) : _border)),
      child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Row(children: [
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
            decoration: BoxDecoration(color: scheduled ? _gold.withOpacity(.1) : _green.withOpacity(.08), borderRadius: BorderRadius.circular(999)),
            child: Text(scheduled ? 'SCHEDULED' : 'DRAFT', style: TextStyle(fontSize: 9, fontWeight: FontWeight.w900, color: scheduled ? _gold : _green)),
          ),
          const Spacer(),
          if (item.isPinned) const Icon(Icons.push_pin_rounded, color: _gold, size: 17),
        ]),
        const SizedBox(height: 12),
        Text(item.title, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w900, color: Color(0xFF182632), height: 1.25)),
        const SizedBox(height: 8),
        Text(item.body, maxLines: 4, overflow: TextOverflow.ellipsis, style: const TextStyle(color: _muted, fontSize: 11.5, height: 1.5)),
        const Spacer(),
        Wrap(spacing: 6, runSpacing: 6, children: [
          _Meta(icon: Icons.category_outlined, text: item.category),
          _Meta(icon: Icons.priority_high_rounded, text: item.priority),
          _Meta(icon: Icons.photo_library_outlined, text: '${item.images.length} photo${item.images.length == 1 ? '' : 's'}'),
        ]),
        if (scheduled && item.scheduledAt != null) ...[
          const SizedBox(height: 8),
          Text('Publishes ${_formatDateTime(item.scheduledAt!)}', style: const TextStyle(fontSize: 10.5, color: _gold, fontWeight: FontWeight.w800)),
        ],
        const SizedBox(height: 12),
        Wrap(spacing: 7, runSpacing: 7, children: [
          OutlinedButton.icon(onPressed: busy ? null : onEdit, icon: const Icon(Icons.edit_outlined, size: 16), label: const Text('Edit')),
          FilledButton.icon(onPressed: busy ? null : onPublish, style: FilledButton.styleFrom(backgroundColor: _green), icon: busy ? const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white)) : const Icon(Icons.publish_rounded, size: 16), label: const Text('Publish')),
        ]),
      ]),
    );
  }
}

class _Meta extends StatelessWidget {
  final IconData icon;
  final String text;
  const _Meta({required this.icon, required this.text});
  @override
  Widget build(BuildContext context) => Container(padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6), decoration: BoxDecoration(color: const Color(0xFFF5F7F9), borderRadius: BorderRadius.circular(999)), child: Row(mainAxisSize: MainAxisSize.min, children: [Icon(icon, size: 12, color: _muted), const SizedBox(width: 4), Text(text, style: const TextStyle(fontSize: 9.8, color: _muted, fontWeight: FontWeight.w700))]));
}

String _formatDateTime(DateTime value) {
  final d = value.toLocal();
  return '${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year} ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}

String _cleanError(Object error) {
  var text = error.toString();
  if (text.startsWith('Exception: ')) text = text.substring(11);
  return text;
}
