import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/conversations_controller.dart';
import '../services/whatsapp_service.dart';
import '../theme/app_theme.dart';
import '../widgets/conversation_tile.dart';
import 'qr_screen.dart';
import 'chat_screen.dart';
import '../models/conversation_model.dart';

class ConversationsScreen extends StatelessWidget {
  const ConversationsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    final svc  = Get.find<WhatsAppService>();
    final ctrl = Get.put(ConversationsController());

    return Scaffold(
      backgroundColor: AppTheme.background,
      appBar: _buildAppBar(ctrl),
      body: Obx(() {
        // Not connected
        if (svc.status.value == WsStatus.disconnected ||
            svc.status.value == WsStatus.connecting) {
          return _buildConnecting();
        }
        // QR Code needed
        if (svc.qrData.value != null) {
          return const QrView();
        }
        // Loading conversations
        if (ctrl.isLoading.value) {
          return const Center(
            child: CircularProgressIndicator(color: AppTheme.primary),
          );
        }
        // Error
        if (ctrl.errorMessage.value != null) {
          return _buildError(ctrl);
        }
        // Empty
        if (ctrl.conversations.isEmpty) {
          return _buildEmpty();
        }
        // List
        return _buildList(ctrl);
      }),
    );
  }

  AppBar _buildAppBar(ConversationsController ctrl) {
    final searching = false.obs;

    return AppBar(
      backgroundColor: AppTheme.surface,
      title: Obx(() => searching.value
          ? TextField(
              autofocus: true,
              style: const TextStyle(color: AppTheme.textPrimary),
              decoration: const InputDecoration(
                hintText: 'Search...',
                border: InputBorder.none,
                hintStyle: TextStyle(color: AppTheme.textSecondary),
              ),
              onChanged: ctrl.search,
            )
          : const Text('WhatsApp', style: TextStyle(color: AppTheme.textPrimary))),
      actions: [
        Obx(() => IconButton(
          icon: Icon(
            searching.value ? Icons.close : Icons.search,
            color: AppTheme.iconColor,
          ),
          onPressed: () {
            searching.value = !searching.value;
            if (!searching.value) ctrl.loadConversations();
          },
        )),
        PopupMenuButton<String>(
          icon: const Icon(Icons.more_vert, color: AppTheme.iconColor),
          color: AppTheme.surface,
          onSelected: (v) {
            if (v == 'refresh') ctrl.loadConversations();
          },
          itemBuilder: (_) => [
            const PopupMenuItem(
              value: 'refresh',
              child: Text('Refresh', style: TextStyle(color: AppTheme.textPrimary)),
            ),
          ],
        ),
      ],
    );
  }

  Widget _buildConnecting() => Center(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const CircularProgressIndicator(color: AppTheme.primary),
        const SizedBox(height: 16),
        Text(
          'Connecting to server...',
          style: TextStyle(color: AppTheme.textSecondary),
        ),
      ],
    ),
  );

  Widget _buildError(ConversationsController ctrl) => Center(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        const Icon(Icons.error_outline, color: Colors.redAccent, size: 48),
        const SizedBox(height: 12),
        Text(
          ctrl.errorMessage.value ?? 'Error',
          style: const TextStyle(color: AppTheme.textSecondary),
          textAlign: TextAlign.center,
        ),
        const SizedBox(height: 16),
        ElevatedButton(
          onPressed: ctrl.loadConversations,
          style: ElevatedButton.styleFrom(backgroundColor: AppTheme.primary),
          child: const Text('Retry'),
        ),
      ],
    ),
  );

  Widget _buildEmpty() => const Center(
    child: Text(
      'No conversations found',
      style: TextStyle(color: AppTheme.textSecondary),
    ),
  );

  Widget _buildList(ConversationsController ctrl) {
    return RefreshIndicator(
      color: AppTheme.primary,
      backgroundColor: AppTheme.surface,
      onRefresh: ctrl.loadConversations,
      child: ListView.builder(
        itemCount: ctrl.conversations.length,
        itemBuilder: (_, i) {
          final chat = ctrl.conversations[i];
          return ConversationTile(
            conversation: chat,
            onTap: () => _openChat(chat),
          );
        },
      ),
    );
  }

  void _openChat(ConversationModel chat) {
    Get.to(
      () => ChatScreen(conversation: chat),
      transition: Transition.rightToLeft,
    );
  }
}
