import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/user_provider.dart';
import '../services/auth_service.dart';
import '../services/order_service.dart';
import '../models/address.dart';
import '../models/order.dart';
import '../utils/error_handler.dart';
import '../widgets/loading_widget.dart';
import 'orders_screen.dart';
import 'login_screen.dart';

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

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

class _ProfileScreenState extends State<ProfileScreen> {
  final AuthService _authService = AuthService();
  final OrderService _orderService = OrderService();
  Address? _billingAddress;
  Address? _shippingAddress;
  bool _isLoadingAddresses = false;

  @override
  void initState() {
    super.initState();
    _loadAddresses();
  }

  Address? _convertBillingAddress(BillingAddress? billing) {
    if (billing == null) return null;
    return Address(
      firstName: billing.firstName,
      lastName: billing.lastName,
      company: billing.company,
      address1: billing.address1,
      address2: billing.address2,
      city: billing.city,
      state: billing.state,
      postcode: billing.postcode,
      country: billing.country,
      email: billing.email,
      phone: billing.phone,
    );
  }

  Address? _convertShippingAddress(ShippingAddress? shipping) {
    if (shipping == null) return null;
    return Address(
      firstName: shipping.firstName,
      lastName: shipping.lastName,
      company: shipping.company,
      address1: shipping.address1,
      address2: shipping.address2,
      city: shipping.city,
      state: shipping.state,
      postcode: shipping.postcode,
      country: shipping.country,
    );
  }

  Future<void> _loadAddresses() async {
    setState(() {
      _isLoadingAddresses = true;
    });

    try {
      // Hole letzte Bestellung für Adressen
      final orders = await _orderService.getOrders(perPage: 1);
      if (orders.isNotEmpty) {
        setState(() {
          _billingAddress = _convertBillingAddress(orders[0].billing);
          _shippingAddress = _convertShippingAddress(orders[0].shipping);
        });
      }
    } catch (e) {
      // Fehler ignorieren - Adressen sind optional
    } finally {
      setState(() {
        _isLoadingAddresses = false;
      });
    }
  }

  Future<void> _updateProfile() async {
    final userProvider = Provider.of<UserProvider>(context, listen: false);
    if (userProvider.user == null) return;

    final firstName = userProvider.user!.firstName ?? '';
    final lastName = userProvider.user!.lastName ?? '';

    showDialog(
      context: context,
      builder: (context) => _ProfileEditDialog(
        firstName: firstName,
        lastName: lastName,
        email: userProvider.user!.email,
        onSave: (firstName, lastName, email) async {
          final updatedUser = await _authService.updateProfile(
            firstName: firstName,
            lastName: lastName,
            email: email,
          );

          if (updatedUser != null && mounted) {
            await userProvider.refreshUser();
            Navigator.pop(context);
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Text('Profil erfolgreich aktualisiert'),
                backgroundColor: Colors.green,
              ),
            );
          } else {
            if (mounted) {
              Navigator.pop(context);
              ErrorHandler.showError(context, 'Fehler beim Aktualisieren des Profils');
            }
          }
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mein Profil'),
        actions: [
          IconButton(
            icon: const Icon(Icons.edit),
            onPressed: _updateProfile,
          ),
        ],
      ),
      body: Consumer<UserProvider>(
        builder: (context, userProvider, child) {
          if (userProvider.user == null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Icon(Icons.account_circle, size: 64, color: Colors.grey),
                  const SizedBox(height: 16),
                  const Text('Bitte melde dich an'),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(
                          builder: (context) => const LoginScreen(),
                        ),
                      );
                    },
                    child: const Text('Anmelden'),
                  ),
                ],
              ),
            );
          }

          final user = userProvider.user!;

          return SingleChildScrollView(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Profil-Header
                Card(
                  child: Padding(
                    padding: const EdgeInsets.all(16),
                    child: Row(
                      children: [
                        CircleAvatar(
                          radius: 40,
                          backgroundColor: const Color(0xFF8B6F47),
                          child: Text(
                            user.fullName[0].toUpperCase(),
                            style: const TextStyle(
                              fontSize: 32,
                              color: Colors.white,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        const SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                user.fullName,
                                style: Theme.of(context).textTheme.titleLarge?.copyWith(
                                      fontWeight: FontWeight.bold,
                                    ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                user.email,
                                style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                                      color: Colors.grey[600],
                                    ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                const SizedBox(height: 24),

                // Menü-Optionen
                Text(
                  'Konto',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
                const SizedBox(height: 12),
                Card(
                  child: Column(
                    children: [
                      ListTile(
                        leading: const Icon(Icons.shopping_bag),
                        title: const Text('Meine Bestellungen'),
                        trailing: const Icon(Icons.chevron_right),
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (context) => const OrdersScreen(),
                            ),
                          );
                        },
                      ),
                      const Divider(height: 1),
                      ListTile(
                        leading: const Icon(Icons.person),
                        title: const Text('Profil bearbeiten'),
                        trailing: const Icon(Icons.chevron_right),
                        onTap: _updateProfile,
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),

                // Adressen
                Text(
                  'Adressen',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                ),
                const SizedBox(height: 12),
                if (_isLoadingAddresses)
                  const LoadingWidget()
                else ...[
                  if (_billingAddress != null && !_billingAddress!.isEmpty)
                    Card(
                      child: ListTile(
                        leading: const Icon(Icons.home),
                        title: const Text('Rechnungsadresse'),
                        subtitle: Text(_billingAddress!.fullAddress),
                        trailing: const Icon(Icons.chevron_right),
                        onTap: () {
                          _showAddressDialog('Rechnungsadresse', _billingAddress!);
                        },
                      ),
                    ),
                  if (_shippingAddress != null && !_shippingAddress!.isEmpty)
                    Card(
                      margin: const EdgeInsets.only(top: 8),
                      child: ListTile(
                        leading: const Icon(Icons.local_shipping),
                        title: const Text('Lieferadresse'),
                        subtitle: Text(_shippingAddress!.fullAddress),
                        trailing: const Icon(Icons.chevron_right),
                        onTap: () {
                          _showAddressDialog('Lieferadresse', _shippingAddress!);
                        },
                      ),
                    ),
                  if ((_billingAddress == null || _billingAddress!.isEmpty) &&
                      (_shippingAddress == null || _shippingAddress!.isEmpty))
                    Card(
                      child: const Padding(
                        padding: EdgeInsets.all(16),
                        child: Text('Keine Adressen gespeichert'),
                      ),
                    ),
                ],
                const SizedBox(height: 24),

                // Abmelden
                SizedBox(
                  width: double.infinity,
                  child: OutlinedButton.icon(
                    onPressed: () async {
                      await userProvider.logout();
                      if (mounted) {
                        Navigator.of(context).pushAndRemoveUntil(
                          MaterialPageRoute(
                            builder: (context) => const LoginScreen(),
                          ),
                          (route) => false,
                        );
                      }
                    },
                    icon: const Icon(Icons.logout, color: Colors.red),
                    label: const Text(
                      'Abmelden',
                      style: TextStyle(color: Colors.red),
                    ),
                    style: OutlinedButton.styleFrom(
                      padding: const EdgeInsets.symmetric(vertical: 16),
                    ),
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }

  void _showAddressDialog(String title, Address address) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(title),
        content: SingleChildScrollView(
          child: Text(address.fullAddress),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Schließen'),
          ),
        ],
      ),
    );
  }
}

class _ProfileEditDialog extends StatefulWidget {
  final String firstName;
  final String lastName;
  final String email;
  final Function(String, String, String) onSave;

  const _ProfileEditDialog({
    required this.firstName,
    required this.lastName,
    required this.email,
    required this.onSave,
  });

  @override
  State<_ProfileEditDialog> createState() => _ProfileEditDialogState();
}

class _ProfileEditDialogState extends State<_ProfileEditDialog> {
  late TextEditingController _firstNameController;
  late TextEditingController _lastNameController;
  late TextEditingController _emailController;

  @override
  void initState() {
    super.initState();
    _firstNameController = TextEditingController(text: widget.firstName);
    _lastNameController = TextEditingController(text: widget.lastName);
    _emailController = TextEditingController(text: widget.email);
  }

  @override
  void dispose() {
    _firstNameController.dispose();
    _lastNameController.dispose();
    _emailController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Profil bearbeiten'),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: _firstNameController,
              decoration: const InputDecoration(
                labelText: 'Vorname',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _lastNameController,
              decoration: const InputDecoration(
                labelText: 'Nachname',
                border: OutlineInputBorder(),
              ),
            ),
            const SizedBox(height: 12),
            TextField(
              controller: _emailController,
              decoration: const InputDecoration(
                labelText: 'E-Mail',
                border: OutlineInputBorder(),
              ),
              keyboardType: TextInputType.emailAddress,
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Abbrechen'),
        ),
        ElevatedButton(
          onPressed: () {
            widget.onSave(
              _firstNameController.text.trim(),
              _lastNameController.text.trim(),
              _emailController.text.trim(),
            );
          },
          child: const Text('Speichern'),
        ),
      ],
    );
  }
}

