import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../widgets/contact_tile.dart';
import '/data/models/contact_model.dart';
import '../screens/settings_screen.dart';
import '../screens/new_chat_screen.dart';
import '../screens/chat_screen.dart';
import '/logic/contact_provider.dart';
import '/logic/auth_provider.dart';

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

  @override
  State<ContactsScreen> createState() => _ContactsScreenState();
}

class _ContactsScreenState extends State<ContactsScreen> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      final authProvider = context.read<AuthProvider>();
      final contactProvider = context.read<ContactProvider>();
      contactProvider.setCurrentUserId(authProvider.currentUserId);
      contactProvider.loadContacts();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "Chepuhagram",
          style: TextStyle(fontWeight: FontWeight.bold),
        ),
        centerTitle: false,
        elevation: 0,
        actions: [IconButton(icon: const Icon(Icons.search), onPressed: () {})],
      ),
      body: Consumer<ContactProvider>(
        builder: (context, contactProvider, child) {
          if (contactProvider.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          if (contactProvider.error != null) {
            return Center(child: Text('Error: ${contactProvider.error}'));
          }
          return ListView.separated(
            itemCount: contactProvider.contacts.length,
            separatorBuilder: (context, index) => Divider(
              height: 1,
              indent: 80,
              color: Theme.of(context).colorScheme.primaryContainer,
            ),
            itemBuilder: (context, index) {
              final contact = contactProvider.contacts[index];
              return ContactTile(
                contact: contact,
                onTap: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => ChatScreen(contact: contact),
                    ),
                  );
                },
              );
            },
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          Navigator.push(
            context,
            MaterialPageRoute(builder: (_) => const NewChatScreen()),
          );
        },
        child: Icon(Icons.edit, color: Theme.of(context).colorScheme.onSurface),
      ),
      drawer: Drawer(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            // Шапка меню с данными юзера
            UserAccountsDrawerHeader(
              accountName: Text("Artur Karasevich"),
              accountEmail: Text("@ArturKarasevich"),
              currentAccountPicture: CircleAvatar(
                backgroundColor: Theme.of(context).colorScheme.onSurface,
                child: Icon(Icons.person, size: 40, color: Theme.of(context).colorScheme.primaryContainer,),
              ),
              decoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primaryContainer,
              ),
            ),
            ListTile(
              leading: const Icon(Icons.settings),
              title: const Text("Настройки"),
              onTap: () {
                // Закрываем Drawer и переходим на экран настроек
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (_) => const SettingsScreen()),
                );
              },
            ),
            ListTile(
              leading: const Icon(Icons.info_outline),
              title: const Text("О приложении"),
              onTap: () {
                /* ... */
              },
            ),
          ],
        ),
      ),
    );
  }
}
