import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/routes/routes.dart';
import 'package:flux/features/customers/blocs/customer_form_cubit.dart';
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
import 'package:flux/features/customers/models/customer_model.dart';
import 'package:flux/features/customers/ui/quick_customer_dialog.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart';

class SharedCustomerSection extends StatelessWidget {
  final CustomerModel? customer;
  final ValueChanged<CustomerModel> onCustomerSelected;

  const SharedCustomerSection({
    super.key,
    this.customer,
    required this.onCustomerSelected,
  });

  @override
  Widget build(BuildContext context) {
    final hasCustomer = customer != null && customer!.id!.isNotEmpty;
    final theme = Theme.of(context);
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(bottom: 12.0),
          child: Text(
            'Cliente',
            style: theme.textTheme.titleLarge?.copyWith(
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        InkWell(
          onTap: () => _showCustomerModal(context), // Passiamo il context!
          child: Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
              border: Border.all(color: theme.colorScheme.primary),
              borderRadius: BorderRadius.circular(8),
              color: theme.colorScheme.primaryContainer.withValues(alpha: 0.2),
            ),
            child: Row(
              children: [
                const Icon(Icons.person),
                const SizedBox(width: 12),
                Expanded(
                  child: Text(
                    hasCustomer ? customer!.name : 'Seleziona Cliente *',
                    style: TextStyle(
                      fontWeight: hasCustomer
                          ? FontWeight.bold
                          : FontWeight.normal,
                      color: hasCustomer ? null : Colors.grey,
                    ),
                  ),
                ),
                const Icon(Icons.search),

                if (hasCustomer) ...[
                  const SizedBox(width: 12),
                  IconButton(
                    onPressed: () async {
                      final updatedCustomer = await context.pushNamed(
                        Routes.customerForm,
                        pathParameters: {'id': customer!.id!},
                        extra: customer,
                      );
                      if (updatedCustomer != null &&
                          updatedCustomer is CustomerModel) {
                        onCustomerSelected(updatedCustomer);
                      }
                    },
                    icon: const Icon(Icons.edit),
                  ),
                ],
              ],
            ),
          ),
        ),
        if (hasCustomer &&
            (customer!.phoneNumber.isNotEmpty ||
                customer!.email.isNotEmpty)) ...[
          const SizedBox(height: 12), // Un po' più di respiro dal box sopra
          // Mettiamo i contatti in un Container con un po' di stile per farli sembrare una "Contact Card" integrata
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            decoration: BoxDecoration(
              color: Colors.grey.withValues(alpha: 0.05), // Sfondo leggerissimo
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: Colors.grey.withValues(alpha: 0.2)),
            ),
            child: Column(
              children: [
                // --- RIGA TELEFONO ---
                if (customer!.phoneNumber.isNotEmpty)
                  Row(
                    children: [
                      // Usiamo i pulsanti "Small" per non occupare troppo spazio verticale
                      IconButton(
                        visualDensity: VisualDensity.compact,
                        onPressed: () => launchUrl(
                          Uri.parse('https://wa.me/39${customer!.phoneNumber}'),
                        ),
                        icon: const FaIcon(
                          FontAwesomeIcons.whatsapp,
                          color: Colors.green,
                          size: 20,
                        ),
                        tooltip: 'Invia WhatsApp',
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        // Expanded evita l'overflow se il numero è assurdamente lungo
                        child: SelectableText(
                          customer!.phoneNumber,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      IconButton(
                        visualDensity: VisualDensity.compact,
                        onPressed: () {
                          Clipboard.setData(
                            ClipboardData(text: customer!.phoneNumber),
                          );
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('Telefono copiato!'),
                              duration: Duration(seconds: 2),
                            ),
                          );
                        },
                        icon: const Icon(
                          Icons.copy,
                          size: 18,
                          color: Colors.grey,
                        ),
                        tooltip: 'Copia',
                      ),
                    ],
                  ),

                // Sezione divisoria se ci sono entrambi
                if (customer!.phoneNumber.isNotEmpty &&
                    customer!.email.isNotEmpty)
                  const Divider(height: 8, thickness: 0.5),

                // --- RIGA EMAIL ---
                if (customer!.email.isNotEmpty)
                  Row(
                    children: [
                      IconButton(
                        visualDensity: VisualDensity.compact,
                        onPressed: () => launchUrl(
                          Uri.parse('mailto:${customer!.email}'),
                        ), // Rimosso il // dopo mailto:, è più sicuro
                        icon: const FaIcon(
                          FontAwesomeIcons.envelope,
                          color: Colors.blue,
                          size: 20,
                        ),
                        tooltip: 'Invia Email',
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        // L'Expanded è vitale per le email che possono essere lunghissime
                        child: SelectableText(
                          customer!.email,
                          style: const TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),
                      IconButton(
                        visualDensity: VisualDensity.compact,
                        onPressed: () {
                          Clipboard.setData(
                            ClipboardData(text: customer!.email),
                          );
                          ScaffoldMessenger.of(context).showSnackBar(
                            const SnackBar(
                              content: Text('Email copiata!'),
                              duration: Duration(seconds: 2),
                            ),
                          );
                        },
                        icon: const Icon(
                          Icons.copy,
                          size: 18,
                          color: Colors.grey,
                        ),
                        tooltip: 'Copia',
                      ),
                    ],
                  ),
              ],
            ),
          ),
        ],
      ],
    );
  }

  // --- MODALE SELEZIONE CLIENTE ---
  void _showCustomerModal(BuildContext context) {
    String currentSearchQuery = '';

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
      ),
      builder: (modalContext) {
        return DraggableScrollableSheet(
          initialChildSize: 0.8,
          minChildSize: 0.5,
          maxChildSize: 0.95,
          expand: false,
          builder: (_, scrollController) {
            return Column(
              children: [
                // Header
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Seleziona Cliente',
                        style: Theme.of(context).textTheme.titleLarge,
                      ),
                      IconButton(
                        icon: const Icon(Icons.close),
                        onPressed: () => Navigator.pop(modalContext),
                      ),
                    ],
                  ),
                ),
                // Barra di Ricerca
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16.0),
                  child: TextField(
                    autofocus: true,
                    decoration: InputDecoration(
                      hintText: 'Cerca per nome, telefono o email...',
                      prefixIcon: const Icon(Icons.search),
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    onChanged: (query) {
                      currentSearchQuery = query;
                      context.read<CustomersListCubit>().searchCustomers(query);
                    },
                  ),
                ),
                // Pulsante Nuovo Cliente
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: ElevatedButton.icon(
                    style: ElevatedButton.styleFrom(
                      minimumSize: const Size.fromHeight(48),
                    ),
                    icon: const Icon(Icons.person_add),
                    label: const Text('Crea Nuovo Cliente'),
                    onPressed: () async {
                      // APRIAMO LA DIALOG RAPIDA CON LA MAGIA DEL BLOC PROVIDER
                      final newCustomer = await showDialog(
                        context: context,
                        builder: (dialogContext) {
                          return BlocProvider.value(
                            value: context.read<CustomersListCubit>(),
                            child: BlocProvider<CustomerFormCubit>(
                              create: (context) => CustomerFormCubit(),
                              child: QuickCustomerDialog(
                                initialQuery:
                                    currentSearchQuery, // <-- Passiamo quello che ha digitato!
                              ),
                            ),
                          );
                        },
                      );

                      // Se l'ha creato davvero (e non ha premuto annulla)...
                      if (newCustomer != null) {
                        // 1. Aggiorniamo il form delle operazioni
                        onCustomerSelected(newCustomer);

                        // 2. Chiudiamo la BottomSheet dei clienti per tornare alla form!
                        if (context.mounted) {
                          Navigator.pop(modalContext);
                        }
                      }
                    },
                  ),
                ),
                const Divider(),
                // Lista Clienti dal Bloc
                Expanded(
                  child: BlocBuilder<CustomersListCubit, CustomersListState>(
                    builder: (context, state) {
                      if (state.status == CustomersListStatus.loading) {
                        return const Center(child: CircularProgressIndicator());
                      }
                      if (state.customers.isEmpty) {
                        return const Center(
                          child: Text(
                            'Nessun cliente trovato.',
                            style: TextStyle(color: Colors.grey),
                          ),
                        );
                      }

                      return ListView.builder(
                        controller: scrollController,
                        itemCount: state.customers.length,
                        itemBuilder: (context, index) {
                          final customer = state.customers[index];
                          return ListTile(
                            leading: CircleAvatar(
                              child: Text(
                                customer.name.substring(0, 1).toUpperCase(),
                              ),
                            ),
                            title: Text(
                              customer.name,
                              style: const TextStyle(
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            subtitle: Text(
                              '${customer.phoneNumber} • ${customer.email}',
                            ),
                            onTap: () {
                              onCustomerSelected(customer);
                              Navigator.pop(modalContext);
                            },
                          );
                        },
                      );
                    },
                  ),
                ),
              ],
            );
          },
        );
      },
    );
  }
}
