import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../core/theme/app_colors.dart';
import '../../core/theme/app_typography.dart';
import '../../core/utils/time_utils.dart';
import '../../services/app_provider.dart';
import '../../widgets/glass_card.dart';

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

  @override
  State<BookmarksScreen> createState() => _BookmarksScreenState();
}

class _BookmarksScreenState extends State<BookmarksScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<AppProvider>().loadBookmarks();
    });
  }

  @override
  Widget build(BuildContext context) {
    final provider = context.watch<AppProvider>();

    return Scaffold(
      backgroundColor: AppColors.navy,
      appBar: AppBar(
        title: Text('Bookmarks', style: AppTypography.headingLg.copyWith(color: Colors.white)),
        backgroundColor: Colors.transparent,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: provider.bookmarks.isEmpty
          ? Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.bookmark_border_rounded, size: 56, color: AppColors.textMuted),
                  const SizedBox(height: 16),
                  Text('No bookmarks yet', style: AppTypography.bodyLg.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 8),
                  Text('Save important legal info during your chats',
                      style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                  const SizedBox(height: 20),
                  GestureDetector(
                    onTap: () => Navigator.of(context).popAndPushNamed('/home'),
                    child: Container(
                      padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                      decoration: BoxDecoration(
                        color: AppColors.royalBlue.withValues(alpha: 0.15),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(color: AppColors.royalBlue.withValues(alpha: 0.3)),
                      ),
                      child: Text('Start a Chat', style: AppTypography.bodySm.copyWith(color: AppColors.royalBlue, fontWeight: FontWeight.w600)),
                    ),
                  ),
                ],
              ),
            )
          : RefreshIndicator(
              color: AppColors.royalBlue,
              backgroundColor: AppColors.navy,
              onRefresh: () => provider.loadBookmarks(),
              child: ListView.builder(
              padding: const EdgeInsets.fromLTRB(16, 0, 16, 100),
              itemCount: provider.bookmarks.length,
              itemBuilder: (context, i) {
                final bk = provider.bookmarks[i];
                return Padding(
                  padding: const EdgeInsets.only(bottom: 10),
                  child: Dismissible(
                    key: Key(bk['id']?.toString() ?? '$i'),
                    direction: DismissDirection.endToStart,
                    background: Container(
                      alignment: Alignment.centerRight,
                      padding: const EdgeInsets.only(right: 20),
                      decoration: BoxDecoration(
                        color: AppColors.error.withValues(alpha: 0.2),
                        borderRadius: BorderRadius.circular(14),
                      ),
                      child: const Icon(Icons.delete_rounded, color: AppColors.error),
                    ),
                    onDismissed: (_) {
                      final id = bk['id']?.toString();
                      if (id != null) {
                        provider.removeBookmark(id);
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: const Text('Bookmark removed'),
                            backgroundColor: AppColors.glassSurface,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      }
                    },
                    child: GlassCard(
                      padding: const EdgeInsets.all(16),
                      child: Row(
                        children: [
                          Container(
                            width: 40,
                            height: 40,
                            decoration: BoxDecoration(
                              color: AppColors.gold.withValues(alpha: 0.12),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(Icons.bookmark_rounded, color: AppColors.gold, size: 20),
                          ),
                          const SizedBox(width: 14),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  bk['title']?.toString() ?? bk['content']?.toString() ?? 'Bookmark',
                                  style: AppTypography.bodyLg.copyWith(color: Colors.white),
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                if (bk['created_at'] != null)
                                  Text(timeAgo(bk['created_at'].toString()),
                                      style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                );
              },
              ),
            ),
    );
  }
}
