import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../profile_manager.dart';
import '../api_service.dart';
import 'store_editor_screen.dart';
import 'product_list_screen.dart';
import '../models/channel.dart'; // Import for WooCommerceChannel cast

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

  @override
  Widget build(BuildContext context) {
    final profile = Provider.of<ProfileManager>(context);
    final api = Provider.of<ApiService>(context);

    return Scaffold(
      appBar: AppBar(
        title: const Text('My Stores'),
        actions: [
            IconButton(
                icon: const Icon(Icons.person),
                onPressed: () => Navigator.pushNamed(context, '/profile'),
                tooltip: 'Profile & Security',
            ),
            IconButton(
                icon: const Icon(Icons.lock),
                onPressed: () => profile.logout(),
                tooltip: 'Lock App',
            )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
            Navigator.push(context, MaterialPageRoute(builder: (_) => const StoreEditorScreen()));
        },
        child: const Icon(Icons.add),
      ),
      body: profile.stores.isEmpty
          ? const Center(child: Text('No stores added. Tap + to add one.'))
          : ListView.separated(
              padding: const EdgeInsets.all(16),
              itemCount: profile.stores.length,
              separatorBuilder: (_, __) => const SizedBox(height: 12),
              itemBuilder: (context, index) {
                final store = profile.stores[index];
                // Assume single channel for now
                final channel = store.channels.firstWhere((c) => c is WooCommerceChannel) as WooCommerceChannel; // Safe cast if migrated correctly

                return Card(
                  color: const Color(0xFF1F2937),
                  child: ListTile(
                    contentPadding: const EdgeInsets.all(16),
                    leading: Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                            color: Colors.blue.withOpacity(0.2),
                            shape: BoxShape.circle,
                        ),
                        child: const Icon(Icons.store, color: Colors.blue),
                    ),
                    title: Text(store.name, style: const TextStyle(fontWeight: FontWeight.bold)),
                    subtitle: Text(channel.url, style: const TextStyle(color: Colors.grey)),
                    trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                    onTap: () {
                        // Connect API Directly using channel creds
                        api.connect(channel.url, channel.consumerKey, channel.consumerSecret);
                        
                        Navigator.push(
                            context, 
                            MaterialPageRoute(builder: (_) => const ProductListWrapper()),
                        );
                    },
                    onLongPress: () {
                        // Option to delete
                        showDialog(context: context, builder: (_) => AlertDialog(
                            title: const Text('Delete Store'),
                            content: Text('Remove ${store.name}?'),
                            actions: [
                                TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')),
                                TextButton(onPressed: () {
                                    profile.removeStore(store.id);
                                    Navigator.pop(context);
                                }, child: const Text('Delete', style: TextStyle(color: Colors.red))),
                            ],
                        ));
                    },
                  ),
                );
              },
            ),
    );
  }
}

// Wrapper to listen to API changes (like logout from within ProductList)

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

    @override
    Widget build(BuildContext context) {
         return Consumer<ApiService>(
            builder: (context, api, _) {
                if (!api.isLoggedIn) {
                    // If we logged out (disconnected), pop back to selection
                    // We need to do this carefully during build... 
                    // Better: The logout button in ProductList should just api.disconnect() AND Navigator.pop().
                    // So here we likely just show ProductList.
                    return const ProductListScreen();
                }
                return const ProductListScreen();
            },
         );
    }
}
