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 ChatListScreen extends StatelessWidget {
  const ChatListScreen({super.key});

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

    return SafeArea(
      bottom: false,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.fromLTRB(20, 16, 20, 0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('Conversations', style: AppTypography.displayLg.copyWith(color: Colors.white)),
                GestureDetector(
                  onTap: () async {
                    try {
                      final id = await provider.createConversation();
                      if (context.mounted) {
                        Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': id});
                      }
                    } catch (_) {
                      if (context.mounted) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: const Text('Failed to create conversation'),
                            backgroundColor: AppColors.error,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                          ),
                        );
                      }
                    }
                  },
                  child: Container(
                    width: 40,
                    height: 40,
                    decoration: BoxDecoration(
                      color: AppColors.royalBlue,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: const Icon(Icons.add_rounded, color: Colors.white, size: 22),
                  ),
                ),
              ],
            ),
          ),
          const SizedBox(height: 16),
          Expanded(
            child: provider.conversations.isEmpty
                ? Center(
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(Icons.chat_bubble_outline_rounded, size: 56, color: AppColors.glassBorder),
                        const SizedBox(height: 16),
                        Text('No conversations yet', style: AppTypography.bodyLg.copyWith(color: AppColors.textMuted)),
                        const SizedBox(height: 8),
                        Text('Start your first legal consultation', style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                        const SizedBox(height: 20),
                        GestureDetector(
                          onTap: () async {
                            try {
                              final id = await provider.createConversation();
                              if (context.mounted) {
                                Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': id});
                              }
                            } catch (_) {
                              if (context.mounted) {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: const Text('Failed to create conversation'),
                                    backgroundColor: AppColors.error,
                                    behavior: SnackBarBehavior.floating,
                                    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                  ),
                                );
                              }
                            }
                          },
                          child: Container(
                            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                            decoration: BoxDecoration(
                              gradient: LinearGradient(colors: [AppColors.royalBlue, AppColors.royalBlue.withValues(alpha: 0.8)]),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: Text('Start a Chat', style: AppTypography.button.copyWith(color: Colors.white)),
                          ),
                        ),
                      ],
                    ),
                  )
                : RefreshIndicator(
                    color: AppColors.royalBlue,
                    backgroundColor: AppColors.navy,
                    onRefresh: () => provider.loadConversations(),
                    child: ListView.builder(
                    padding: const EdgeInsets.fromLTRB(20, 0, 20, 100),
                    itemCount: provider.conversations.length,
                    itemBuilder: (context, i) {
                      final conv = provider.conversations[i];
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 10),
                        child: Dismissible(
                          key: Key(conv['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 = conv['id']?.toString();
                            if (id != null) {
                              provider.deleteConversation(id);
                              ScaffoldMessenger.of(context).showSnackBar(
                                SnackBar(
                                  content: const Text('Conversation deleted'),
                                  backgroundColor: AppColors.glassSurface,
                                  behavior: SnackBarBehavior.floating,
                                  shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
                                ),
                              );
                            }
                          },
                          child: GlassCard(
                          onTap: () => Navigator.of(context).pushNamed('/chat', arguments: {'conversationId': conv['id']?.toString()}),
                          padding: const EdgeInsets.all(16),
                          child: Row(
                            children: [
                              Container(
                                width: 44,
                                height: 44,
                                decoration: BoxDecoration(
                                  color: AppColors.royalBlue.withValues(alpha: 0.15),
                                  borderRadius: BorderRadius.circular(14),
                                ),
                                child: const Icon(Icons.chat_rounded, color: AppColors.royalBlue, size: 22),
                              ),
                              const SizedBox(width: 14),
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(conv['title']?.toString() ?? 'Conversation', style: AppTypography.bodyLg.copyWith(color: Colors.white), maxLines: 1, overflow: TextOverflow.ellipsis),
                                    const SizedBox(height: 2),
                                    Text(timeAgo(conv['updated_at']?.toString()), style: AppTypography.bodySm.copyWith(color: AppColors.textMuted)),
                                  ],
                                ),
                              ),
                              Icon(Icons.chevron_right_rounded, color: AppColors.textMuted),
                            ],
                          ),
                        ),
                        ),
                      );
                    },
                  ),
                  ),
          ),
        ],
      ),
    );
  }
}
