import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../core/api_client.dart';
import '../../data/user_model.dart';
import '../chat/chat_repository.dart';
import '../chat/chat_screen.dart';
import '../../data/message_model.dart';

import '../../core/auth_storage.dart';

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

  @override
  ConsumerState<DiscoveryScreen> createState() => _DiscoveryScreenState();
}

class _DiscoveryScreenState extends ConsumerState<DiscoveryScreen> {
  List<User> _users = [];
  bool _loading = true;
  final TextEditingController _searchController = TextEditingController();
  Timer? _debounce;

  int _shuffleCount = 0;
  DateTime? _blockUntil;

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

  Future<void> _handleRefresh() async {
    if (_blockUntil != null && DateTime.now().isBefore(_blockUntil!)) {
      final waitSeconds = _blockUntil!.difference(DateTime.now()).inSeconds;
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
            content: Text(
                'Please wait $waitSeconds seconds before shuffling again.')),
      );
      return;
    }

    _shuffleCount++;
    if (_shuffleCount >= 5) {
      _blockUntil = DateTime.now().add(const Duration(seconds: 30));
      _shuffleCount = 0;
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
            content: Text('Shuffle limit reached. Please wait 30 seconds.')),
      );
      return;
    }

    await _loadUsers();
  }

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

  void _onSearchChanged(String query) {
    if (_debounce?.isActive ?? false) _debounce!.cancel();
    _debounce = Timer(const Duration(milliseconds: 300), () {
      if (mounted) _loadUsers(query: query);
    });
  }

  Future<void> _loadUsers({String? query}) async {
    // Only show loading indicator if it's the first load or explicit search
    // Pull-to-refresh handles its own spinner
    if (_users.isEmpty) setState(() => _loading = true);

    try {
      // Use query from controller if not provided (for refresh)
      final effectiveQuery = query ?? _searchController.text;

      final endpoint =
          effectiveQuery.isNotEmpty ? '/shuffle?q=$effectiveQuery' : '/shuffle';
      final response = await ref.read(apiClientProvider).client.get(endpoint);

      if (mounted) {
        setState(() {
          _users =
              (response.data as List).map((e) => User.fromJson(e)).toList();
          _loading = false;
        });
      }
    } catch (e) {
      if (mounted) {
         setState(() => _loading = false);
         ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Search Error: $e')));
      }
    }
  }

  Future<void> _startAnonChat(User user) async {
    try {
      String visitorHash;
      final userId = await ref.read(authStorageProvider).getUserId();
      
      if (userId != null) {
        // Logged in user: Use stable hash based on userId to persist chats across installs
        visitorHash = 'user_stable_$userId';
      } else {
        // Not logged in: Use device-based visitor hash
        visitorHash = await ref.read(authStorageProvider).getVisitorHash();
      }

      final result = await ref
          .read(chatRepositoryProvider)
          .startAnonChat(user.linkSlug, visitorHash);
      final conversationId = result['conversation_id'];
      final anonToken = result['token'];
      final visitorUserId = result['visitor_id'];

      // Construct conversation manually to avoid lookup race condition and auth issues
      final conversation = Conversation(
          id: conversationId != null
              ? int.parse(conversationId.toString())
              : -1,
          otherUser: {
            'id': user.id,
            'username': user.username,
            'display_name': user.displayName,
            'avatar_url': user.avatarUrl
          });

      if (mounted) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (_) => ChatScreen(
                    conversation: conversation,
                    anonToken: anonToken,
                    visitorUserId: visitorUserId?.toString())));
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context)
            .showSnackBar(SnackBar(content: Text('Error: $e')));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final scheme = Theme.of(context).colorScheme;
    return Scaffold(
      appBar: AppBar(
        title: const Text('Shuffle'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            tooltip: 'Shuffle',
            onPressed: _handleRefresh,
          ),
        ],
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(62),
          child: Padding(
            padding: const EdgeInsets.fromLTRB(16, 0, 16, 12),
            child: TextField(
              controller: _searchController,
              onChanged: _onSearchChanged,
              textInputAction: TextInputAction.search,
              decoration: const InputDecoration(
                hintText: 'Kullanıcı ara…',
                prefixIcon: Icon(Icons.search_rounded),
              ),
            ),
          ),
        ),
      ),
      body: RefreshIndicator(
        onRefresh: _handleRefresh,
        child: _loading
            ? const Center(child: CircularProgressIndicator())
            : _users.isEmpty
                ? Center(
                    child: Padding(
                      padding: const EdgeInsets.all(20),
                      child: Text(
                        'Kullanıcı bulunamadı.',
                        style: TextStyle(color: scheme.onSurfaceVariant),
                      ),
                    ),
                  )
                : ListView.separated(
                    padding: const EdgeInsets.fromLTRB(12, 12, 12, 20),
                    itemCount: _users.length,
                    separatorBuilder: (_, __) => const SizedBox(height: 10),
                    itemBuilder: (context, index) {
                      final user = _users[index];
                      final title = user.displayName ?? user.username;
                      final subtitle = (user.bio != null && user.bio!.isNotEmpty)
                          ? user.bio!
                          : (user.isSeed ? '[${user.seedLabel}]' : user.linkSlug);
                      return Card(
                        child: InkWell(
                          borderRadius: BorderRadius.circular(20),
                          onTap: () => _startAnonChat(user),
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundImage: user.avatarUrl != null
                                  ? NetworkImage(user.avatarUrl!)
                                  : null,
                              child: user.avatarUrl == null
                                  ? Text(user.username[0].toUpperCase(), style: const TextStyle(fontWeight: FontWeight.w800))
                                  : null,
                            ),
                            title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
                            subtitle: Text(
                              subtitle,
                              maxLines: 2,
                              overflow: TextOverflow.ellipsis,
                            ),
                            trailing: Icon(Icons.chat_bubble_rounded, color: scheme.primary),
                          ),
                        ),
                      );
                    },
                  ),
      ),
    );
  }
}
