import 'package:flutter/material.dart';

import '../../../../core/services/news_offline_service.dart';
import 'news_offline_widgets.dart';
import 'published_news_sub_tab.dart' show CampusNewsComposerDialog;

const Color _gold = Color.fromARGB(255, 204, 117, 4);

const Color _green = Color.fromARGB(255, 2, 105, 48);

const Color _border = Color(0xFFE4E8EE);

const Color _muted = Color(0xFF66727E);

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

  @override
  State<DraftNewsSubTab> createState() => _DraftNewsSubTabState();
}

class _DraftNewsSubTabState extends State<DraftNewsSubTab> {
  final List<CampusNewsArticle> _drafts = [];

  bool _loading = true;
  bool _reading=false;

  String? _error;

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

    _loadDrafts();
    NewsOfflineService.revision.addListener(_loadDrafts);
  }

  // ==============================================================
  // LOAD DRAFTS
  // ==============================================================

  @override void dispose(){NewsOfflineService.revision.removeListener(_loadDrafts);super.dispose();}
  Future<void> _refreshNow() async {await NewsOfflineService.sync(force:true);await _loadDrafts();}
  Future<void> _loadDrafts() async {
    if(!mounted||_reading)return;_reading=true;
    setState(() {
      _loading = _drafts.isEmpty;
      _error = null;
    });

    try {
      final page = await NewsOfflineService.getNews(
        status: 'draft',
        mine: true,
        limit: 50,
      );

      if (!mounted) return;

      setState(() {
        _drafts
          ..clear()
          ..addAll(page.articles);

        _loading = false;
      });
    } catch (e) {
      if (!mounted) return;

      setState(() {
        _loading = false;

        _error = _drafts.isEmpty?_cleanError(e):null;
      });
    }finally{_reading=false;}
  }

  // ==============================================================
  // CREATE
  // ==============================================================

  Future<void> _createDraft() async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => const NewsAccountGuard(child:CampusNewsComposerDialog()),
    );

    if (result == true) {
      await _loadDrafts();
    }
  }

  // ==============================================================
  // EDIT
  // ==============================================================

  Future<void> _edit(CampusNewsArticle article) async {
    final result = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (_) => NewsAccountGuard(child:CampusNewsComposerDialog(article: article)),
    );

    if (result == true) {
      await _loadDrafts();
    }
  }

  // ==============================================================
  // PUBLISH
  // ==============================================================

  Future<void> _publish(CampusNewsArticle article) async {
    try {
      await NewsOfflineService.queueAction('update',article.id, {'status': 'published'});

      if (!mounted) return;

      _showSnack('Publication saved to outbox; waiting for confirmation.');

      await _loadDrafts();
    } catch (e) {
      _showSnack(_cleanError(e), error: true);
    }
  }

  // ==============================================================
  // DELETE
  // ==============================================================

  Future<void> _delete(CampusNewsArticle article) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (_) => AlertDialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        title: const Text('Delete Draft?'),
        content: Text('Delete "${article.title}" permanently?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('Cancel'),
          ),

          FilledButton(
            onPressed: () => Navigator.pop(context, true),
            style: FilledButton.styleFrom(backgroundColor: Colors.red.shade700),
            child: const Text('Delete'),
          ),
        ],
      ),
    );

    if (confirmed != true) {
      return;
    }

    try {
      await NewsOfflineService.deleteNews(article.id);

      if (!mounted) return;

      setState(() {
        _drafts.removeWhere((item) => item.id == article.id);
      });

      _showSnack('Draft deleted.');
    } catch (e) {
      _showSnack(_cleanError(e), error: true);
    }
  }

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

  // ==============================================================
  // BUILD
  // ==============================================================

  @override
  Widget build(BuildContext context) {
    final compact = MediaQuery.sizeOf(context).width < 720;
    return Scaffold(
      backgroundColor: Colors.transparent,
      floatingActionButton: compact
          ? FloatingActionButton(
              onPressed: _createDraft,
              backgroundColor: _gold,
              foregroundColor: Colors.white,
              child: const Icon(Icons.add_rounded),
            )
          : FloatingActionButton.extended(
              onPressed: _createDraft,
              backgroundColor: _gold,
              foregroundColor: Colors.white,
              icon: const Icon(Icons.add_rounded),
              label: const Text(
                'NEW DRAFT',
                style: TextStyle(fontWeight: FontWeight.w900),
              ),
            ),
      body: LayoutBuilder(
        builder: (context, constraints) {
          final horizontal = constraints.maxWidth > 760
              ? (constraints.maxWidth - 760) / 2
              : 10.0;
          return RefreshIndicator(
            color: _green,
            onRefresh: _refreshNow,
            child: ListView(
              physics: const AlwaysScrollableScrollPhysics(),
              padding: EdgeInsets.fromLTRB(horizontal, 14, horizontal, 100),
              children: [
                const NewsSyncBar(),const SizedBox(height:10),
                Container(
                  padding: const EdgeInsets.all(15),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(14),
                    border: Border.all(color: _border),
                  ),
                  child: Row(
                    children: [
                      Container(
                        width: 42,
                        height: 42,
                        decoration: BoxDecoration(
                          color: _green.withOpacity(0.07),
                          borderRadius: BorderRadius.circular(11),
                        ),
                        child: const Icon(
                          Icons.edit_note_rounded,
                          color: _green,
                          size: 23,
                        ),
                      ),
                      const SizedBox(width: 11),
                      const Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Draft Workspace',
                              style: TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.w900,
                                color: Color(0xFF182632),
                              ),
                            ),
                            SizedBox(height: 3),
                            Text(
                              'Prepare, review and publish campus stories when they are ready.',
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: _muted,
                                fontSize: 10.5,
                                height: 1.4,
                              ),
                            ),
                          ],
                        ),
                      ),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(
                          horizontal: 9,
                          vertical: 6,
                        ),
                        decoration: BoxDecoration(
                          color: _gold.withOpacity(0.1),
                          borderRadius: BorderRadius.circular(999),
                        ),
                        child: Text(
                          '${_drafts.length}',
                          style: const TextStyle(
                            color: _gold,
                            fontSize: 10,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 12),
                if (_loading)
                  const Padding(
                    padding: EdgeInsets.symmetric(vertical: 100),
                    child: Center(
                      child: CircularProgressIndicator(color: _green),
                    ),
                  )
                else if (_error != null)
                  Container(
                    padding: const EdgeInsets.all(24),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(14),
                      border: Border.all(color: _border),
                    ),
                    child: Column(
                      children: [
                        Icon(
                          Icons.error_outline,
                          color: Colors.red.shade400,
                          size: 42,
                        ),
                        const SizedBox(height: 10),
                        const Text(
                          'Unable to load drafts',
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        const SizedBox(height: 7),
                        Text(
                          _error!,
                          textAlign: TextAlign.center,
                          style: const TextStyle(color: _muted, fontSize: 11.5),
                        ),
                        const SizedBox(height: 13),
                        FilledButton.icon(
                          onPressed: _refreshNow,
                          style: FilledButton.styleFrom(
                            backgroundColor: _green,
                          ),
                          icon: const Icon(Icons.refresh),
                          label: const Text('Retry'),
                        ),
                      ],
                    ),
                  )
                else if (_drafts.isEmpty)
                  Container(
                    padding: const EdgeInsets.symmetric(
                      vertical: 54,
                      horizontal: 20,
                    ),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(14),
                      border: Border.all(color: _border),
                    ),
                    child: Column(
                      children: [
                        Icon(
                          Icons.edit_note_outlined,
                          size: 54,
                          color: Colors.grey.shade300,
                        ),
                        const SizedBox(height: 12),
                        const Text(
                          'No drafts yet',
                          style: TextStyle(
                            fontSize: 17,
                            fontWeight: FontWeight.w900,
                          ),
                        ),
                        const SizedBox(height: 7),
                        const Text(
                          'Start writing an announcement, event story, campus update or achievement.',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            color: _muted,
                            fontSize: 11.5,
                            height: 1.45,
                          ),
                        ),
                        const SizedBox(height: 16),
                        FilledButton.icon(
                          onPressed: _createDraft,
                          style: FilledButton.styleFrom(
                            backgroundColor: _green,
                          ),
                          icon: const Icon(Icons.add),
                          label: const Text('Create Draft'),
                        ),
                      ],
                    ),
                  )
                else
                  ..._drafts.map(
                    (draft) => Padding(
                      padding: const EdgeInsets.only(bottom: 11),
                      child: _DraftCard(
                        article: draft,
                        onEdit: () => _edit(draft),
                        onPublish: () => _publish(draft),
                        onDelete: () => _delete(draft),
                      ),
                    ),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }
}

// =================================================================
// DRAFT CARD
// =================================================================

class _DraftCard extends StatelessWidget {
  final CampusNewsArticle article;

  final VoidCallback onEdit;
  final VoidCallback onPublish;
  final VoidCallback onDelete;

  const _DraftCard({
    required this.article,
    required this.onEdit,
    required this.onPublish,
    required this.onDelete,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: Border.all(color: _border),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // ------------------------------------------------------
          // TITLE
          // ------------------------------------------------------
          Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Expanded(
                child: Text(
                  article.title,
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                  style: const TextStyle(
                    fontSize: 17,
                    height: 1.3,
                    fontWeight: FontWeight.w900,
                    color: Color(0xFF182632),
                  ),
                ),
              ),

              const SizedBox(width: 10),

              Container(
                padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 5),
                decoration: BoxDecoration(
                  color: _gold.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(999),
                ),
                child: Text(
                  article.category.toUpperCase(),
                  style: const TextStyle(
                    color: _gold,
                    fontSize: 8.5,
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ),
            ],
          ),

          const SizedBox(height: 9),

          // ------------------------------------------------------
          // BODY
          // ------------------------------------------------------
          Text(
            article.body,
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(
              color: Color(0xFF596674),
              height: 1.5,
              fontSize: 12,
            ),
          ),

          const SizedBox(height: 13),

          // ------------------------------------------------------
          // META
          // ------------------------------------------------------
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              _MetaPill(
                icon: Icons.location_on_outlined,
                text: article.campus.isEmpty
                    ? 'University Wide'
                    : article.campus,
              ),

              _MetaPill(
                icon: Icons.photo_library_outlined,
                text: '${article.images.length} image(s)',
              ),

              if (article.video != null)
                _MetaPill(
                  icon: Icons.videocam_outlined,
                  text: 'Video ${article.video!.formattedSize}',
                ),

              _MetaPill(
                icon: Icons.schedule_outlined,
                text: _date(article.updatedAt ?? article.createdAt),
              ),
            ],
          ),

          const SizedBox(height: 15),

          // ------------------------------------------------------
          // ACTIONS
          // ------------------------------------------------------
          Wrap(
            spacing: 8,
            runSpacing: 8,
            children: [
              OutlinedButton.icon(
                onPressed: onEdit,
                style: OutlinedButton.styleFrom(foregroundColor: _green),
                icon: const Icon(Icons.edit_outlined),
                label: const Text('Edit'),
              ),

              FilledButton.icon(
                onPressed: onPublish,
                style: FilledButton.styleFrom(
                  backgroundColor: _green,
                  foregroundColor: Colors.white,
                ),
                icon: const Icon(Icons.publish_rounded),
                label: const Text('Publish'),
              ),

              OutlinedButton.icon(
                onPressed: onDelete,
                style: OutlinedButton.styleFrom(
                  foregroundColor: Colors.red.shade700,
                ),
                icon: const Icon(Icons.delete_outline),
                label: const Text('Delete'),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

// =================================================================
// META PILL
// =================================================================

class _MetaPill extends StatelessWidget {
  final IconData icon;
  final String text;

  const _MetaPill({required this.icon, required this.text});

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 7),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F7F9),
        borderRadius: BorderRadius.circular(999),
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, size: 13, color: _muted),

          const SizedBox(width: 5),

          Text(
            text,
            style: const TextStyle(
              fontSize: 10.5,
              color: _muted,
              fontWeight: FontWeight.w700,
            ),
          ),
        ],
      ),
    );
  }
}

// =================================================================
// HELPERS
// =================================================================

String _date(DateTime value) {
  final date = value.toLocal();

  return '${date.day.toString().padLeft(2, '0')}/'
      '${date.month.toString().padLeft(2, '0')}/'
      '${date.year}';
}

String _cleanError(Object error) {
  var value = error.toString();

  if (value.startsWith('Exception: ')) {
    value = value.substring(11);
  }

  return value;
}
