import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '/logic/contact_provider.dart';
import '/logic/auth_provider.dart';
import 'chat_screen.dart';

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

  @override
  State<NewChatScreen> createState() => _NewChatScreenState();
}

class _NewChatScreenState extends State<NewChatScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final authProvider = context.read<AuthProvider>();
      final contactProvider = context.read<ContactProvider>();
      
      // Установить текущего пользователя и загрузить все контакты
      contactProvider.setCurrentUserId(authProvider.currentUserId);
      contactProvider.loadAllContactsForNewChat();
    });
  }

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

    return Scaffold(
      appBar: AppBar(
        title: const Text('Новый чат'),
      ),
      body: contactProvider.isLoading
          ? const Center(child: CircularProgressIndicator())
          : contactProvider.error != null
              ? Center(child: Text('Error: ${contactProvider.error}'))
              : ListView.builder(
                  itemCount: contactProvider.allContacts.length,
                  itemBuilder: (context, index) {
                    final contact = contactProvider.allContacts[index];
                    return ListTile(
                      leading: CircleAvatar(
                        child: Text(contact.name[0]),
                      ),
                      title: Text(contact.name),
                      onTap: () {
                        // Создать чат с этим контактом
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (_) => ChatScreen(contact: contact),
                          ),
                        );
                      },
                    );
                  },
                ),
    );
  }
}