import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:timeago/timeago.dart' as timeago;
import 'chat_repository.dart';
import 'chat_screen.dart';
import '../../data/message_model.dart';
import '../discovery/discovery_screen.dart';
import '../story/stories_screen.dart';
import '../profile/profile_screen.dart';

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

  @override
  State<ChatListScreen> createState() => _ChatListScreenState();
}

class _ChatListScreenState extends State<ChatListScreen> {
  int _currentIndex = 1; // Default to Chats

  final _pages = [
    const DiscoveryScreen(),
    const ConversationsList(),
    const StoriesScreen(),
    const ProfileScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _pages[_currentIndex],
      bottomNavigationBar: NavigationBar(
        selectedIndex: _currentIndex,
        onDestinationSelected: (index) => setState(() => _currentIndex = index),
        destinations: const [
          NavigationDestination(
            icon: Icon(Icons.shuffle_outlined),
            selectedIcon: Icon(Icons.shuffle),
            label: 'Shuffle',
          ),
          NavigationDestination(
            icon: Icon(Icons.chat_bubble_outline),
            selectedIcon: Icon(Icons.chat_bubble),
            label: 'Chats',
          ),
          NavigationDestination(
            icon: Icon(Icons.amp_stories_outlined),
            selectedIcon: Icon(Icons.amp_stories),
            label: 'Stories',
          ),
          NavigationDestination(
            icon: Icon(Icons.person_outline),
            selectedIcon: Icon(Icons.person),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

class ConversationsList extends ConsumerStatefulWidget {
  const ConversationsList({super.key});

  @override
  ConsumerState<ConversationsList> createState() => _ConversationsListState();
}

class _ConversationsListState extends ConsumerState<ConversationsList> {
  late Future<List<Conversation>> _future;
  final _searchController = TextEditingController();
  String _query = '';

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

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  void _refresh() {
    setState(() {
      _future = ref.read(chatRepositoryProvider).getConversations();
    });
  }

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Scaffold(
      body: DecoratedBox(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              scheme.primary.withAlpha(16),
              scheme.surface,
              scheme.tertiary.withAlpha(12),
            ],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: RefreshIndicator(
            onRefresh: () async => _refresh(),
            child: FutureBuilder<List<Conversation>>(
              future: _future,
              builder: (context, snapshot) {
                final loading = snapshot.connectionState == ConnectionState.waiting;

                final allChats = snapshot.data ?? <Conversation>[];
                final chats = _query.trim().isEmpty
                    ? allChats
                    : allChats.where((c) {
                        final other = c.otherUser;
                        final name = (other['display_name'] ?? other['username'] ?? '').toString().toLowerCase();
                        final last = (c.lastMessage ?? '').toLowerCase();
                        final q = _query.toLowerCase();
                        return name.contains(q) || last.contains(q);
                      }).toList();

                return CustomScrollView(
                  physics: const AlwaysScrollableScrollPhysics(),
                  slivers: [
                    SliverAppBar(
                      pinned: true,
                      floating: true,
                      expandedHeight: 128,
                      title: const Text('Chats'),
                      actions: [
                        IconButton(
                          icon: const Icon(Icons.refresh_rounded),
                          onPressed: _refresh,
                        ),
                      ],
                      flexibleSpace: FlexibleSpaceBar(
                        background: Padding(
                          padding: const EdgeInsets.fromLTRB(16, 56, 16, 8),
                          child: Align(
                            alignment: Alignment.bottomCenter,
                            child: TextField(
                              controller: _searchController,
                              onChanged: (v) => setState(() => _query = v),
                              textInputAction: TextInputAction.search,
                              decoration: const InputDecoration(
                                hintText: 'Konuşma ara…',
                                prefixIcon: Icon(Icons.search_rounded),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    if (snapshot.hasError)
                      SliverFillRemaining(
                        hasScrollBody: false,
                        child: Center(
                          child: Padding(
                            padding: const EdgeInsets.all(20),
                            child: Text(
                              'Bir şeyler ters gitti.\n${snapshot.error}',
                              textAlign: TextAlign.center,
                              style: TextStyle(color: scheme.onSurfaceVariant, fontWeight: FontWeight.w600),
                            ),
                          ),
                        ),
                      )
                    else if (loading)
                      const SliverFillRemaining(
                        hasScrollBody: false,
                        child: Center(child: CircularProgressIndicator()),
                      )
                    else if (chats.isEmpty)
                      SliverFillRemaining(
                        hasScrollBody: false,
                        child: Center(
                          child: Padding(
                            padding: const EdgeInsets.all(20),
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Icon(Icons.chat_bubble_outline_rounded, size: 42),
                                SizedBox(height: 12),
                                Text('Henüz konuşma yok.', style: TextStyle(fontWeight: FontWeight.w700)),
                              ],
                            ),
                          ),
                        ),
                      )
                    else
                      SliverPadding(
                        padding: const EdgeInsets.fromLTRB(12, 10, 12, 18),
                        sliver: SliverList.separated(
                          itemCount: chats.length,
                          separatorBuilder: (_, __) => const SizedBox(height: 10),
                          itemBuilder: (context, index) {
                            final chat = chats[index];
                            final otherUser = chat.otherUser;
                            final isAnonChat = chat.isAnonymous;
                            final displayName = (otherUser['display_name'] ?? otherUser['username'] ?? 'Chat').toString();
                            final avatarUrl = otherUser['avatar_url'] as String?;
                            final preview = (chat.lastMessage?.toString().trim().isNotEmpty ?? false)
                                ? chat.lastMessage!.toString()
                                : 'Mesaj yok';
                            final timeText = chat.lastMessageAt != null ? timeago.format(chat.lastMessageAt!) : '';

                            return Card(
                              child: InkWell(
                                borderRadius: BorderRadius.circular(20),
                                onTap: () async {
                                  await Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (_) => ChatScreen(
                                        conversation: chat,
                                        anonToken: chat.anonToken,
                            initialLastMessage: chat.lastMessage,
                            initialLastMessageAt: chat.lastMessageAt,
                                      ),
                                    ),
                                  );
                                  _refresh();
                                },
                                child: ListTile(
                                  leading: _Avatar(title: displayName, imageUrl: avatarUrl),
                                  title: Row(
                                    children: [
                                      Expanded(
                                        child: Text(
                                          displayName,
                                          maxLines: 1,
                                          overflow: TextOverflow.ellipsis,
                                        ),
                                      ),
                                      if (isAnonChat) _AnonChip(),
                                    ],
                                  ),
                                  subtitle: Text(
                                    preview,
                                    maxLines: 1,
                                    overflow: TextOverflow.ellipsis,
                                  ),
                                  trailing: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: [
                                      Text(
                                        timeText,
                                        style: TextStyle(
                                          fontSize: 11,
                                          color: scheme.onSurfaceVariant,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                      if (chat.unreadCount > 0) ...[
                                        const SizedBox(height: 6),
                                        _UnreadBadge(count: chat.unreadCount),
                                      ],
                                    ],
                                  ),
                                ),
                              ),
                            );
                          },
                        ),
                      ),
                  ],
                );
              },
            ),
          ),
        ),
      ),
    );
  }
}

class _Avatar extends StatelessWidget {
  final String title;
  final String? imageUrl;

  const _Avatar({required this.title, required this.imageUrl});

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    final letter = title.isNotEmpty ? title[0].toUpperCase() : '?';
    return Container(
      padding: const EdgeInsets.all(2),
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        gradient: LinearGradient(
          colors: [scheme.primary, scheme.tertiary],
        ),
      ),
      child: CircleAvatar(
        radius: 22,
        backgroundColor: scheme.surface,
        foregroundColor: scheme.onSurface,
        backgroundImage: imageUrl != null ? NetworkImage(imageUrl!) : null,
        child: imageUrl == null ? Text(letter, style: const TextStyle(fontWeight: FontWeight.w800)) : null,
      ),
    );
  }
}

class _AnonChip extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Container(
      margin: const EdgeInsets.only(left: 8),
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: scheme.tertiaryContainer,
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        'ANON',
        style: TextStyle(
          fontSize: 10,
          letterSpacing: 0.6,
          fontWeight: FontWeight.w800,
          color: scheme.onTertiaryContainer,
        ),
      ),
    );
  }
}

class _UnreadBadge extends StatelessWidget {
  final int count;
  const _UnreadBadge({required this.count});

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: scheme.primary,
        borderRadius: BorderRadius.circular(999),
      ),
      child: Text(
        '$count',
        style: TextStyle(
          color: scheme.onPrimary,
          fontSize: 11,
          fontWeight: FontWeight.w800,
        ),
      ),
    );
  }
}
