import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../profile_manager.dart';
import '../models/channel.dart'; 
import 'store_editor_screen.dart';

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

  @override
  State<ProfileScreen> createState() => _ProfileScreenState();
}

class _ProfileScreenState extends State<ProfileScreen> {
  final _pinController = TextEditingController();

  void _changePin() {
    _pinController.clear();
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Set New PIN'),
        content: TextField(
            controller: _pinController,
            keyboardType: TextInputType.number,
            maxLength: 4,
            obscureText: true,
            decoration: const InputDecoration(labelText: 'Enter 4-digit PIN'),
        ),
        actions: [
            TextButton(
                onPressed: () => Navigator.pop(ctx),
                child: const Text('Cancel')
            ),
            TextButton(
                onPressed: () {
                    if (_pinController.text.length == 4) {
                        Provider.of<ProfileManager>(context, listen: false).setPin(_pinController.text);
                        Navigator.pop(ctx);
                        ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('PIN Updated successfully')));
                    }
                },
                child: const Text('Save')
            ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final profile = Provider.of<ProfileManager>(context);
    
    return Scaffold(
        appBar: AppBar(title: const Text('Security & Profile')),
        body: ListView(
            padding: const EdgeInsets.all(16),
            children: [
                ListTile(
                    leading: const Icon(Icons.lock),
                    title: const Text('App Security'),
                    subtitle: Text(profile.hasPin ? 'PIN Protection: Enabled' : 'PIN Protection: Disabled'),
                    trailing: ElevatedButton(
                        onPressed: _changePin,
                        child: const Text('Change PIN'),
                    ),
                ),
                const Divider(),
                const Padding(
                    padding: EdgeInsets.symmetric(vertical: 8),
                    child: Text('Connected Sites', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold)),
                ),
                if (profile.stores.isEmpty)
                    const Text('No stores added'),
                ...profile.stores.map((store) {
                    // For now, assume 1 store = 1 woo channel. Show store name and url of first channel.
                    final channel = store.channels.firstWhere((c) => c is WooCommerceChannel) as WooCommerceChannel;
                    return ListTile(
                        leading: const Icon(Icons.store),
                        title: Text(store.name),
                        subtitle: Text(channel.url),
                        trailing: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                                IconButton(
                                    icon: const Icon(Icons.edit, color: Colors.blue),
                                    onPressed: () {
                                        Navigator.push(context, MaterialPageRoute(
                                            builder: (_) => StoreEditorScreen(store: store)
                                        ));
                                    },
                                ),
                                IconButton(
                                    icon: const Icon(Icons.delete, color: Colors.red),
                                    onPressed: () => profile.removeStore(store.id),
                                ),
                            ],
                        ),
                    );
                }),
                const Divider(),
                ListTile(
                    leading: const Icon(Icons.logout, color: Colors.orange),
                    title: const Text('Lock App'),
                    onTap: () {
                        profile.logout(); // Locks app
                        Navigator.of(context).pushNamedAndRemoveUntil('/', (route) => false);
                    },
                )
            ],
        ),
    );
  }
}
