import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/features/master_data/providers/blocs/provider_form_cubit.dart';
import 'package:flux/features/master_data/providers/models/provider_location_model.dart';
import 'package:flux/features/master_data/providers/models/provider_model.dart';
import 'package:flux/features/master_data/providers/models/provider_role.dart';
import 'package:flux/features/master_data/providers/ui/provider_location_dialog.dart';

class ProviderFormScreen extends StatefulWidget {
  final ProviderModel? existingProvider;

  const ProviderFormScreen({super.key, this.existingProvider});

  @override
  State<ProviderFormScreen> createState() => _ProviderFormScreenState();
}

class _ProviderFormScreenState extends State<ProviderFormScreen> {
  final _formKey = GlobalKey<FormState>();

  // Controllers per i campi di testo
  late final TextEditingController _nameCtrl;
  late final TextEditingController _businessNameCtrl;
  late final TextEditingController _vatCtrl;
  late final TextEditingController _cfCtrl;
  late final TextEditingController _sdiCtrl;
  late final TextEditingController _pecCtrl;

  @override
  void initState() {
    super.initState();
    final p = widget.existingProvider;

    _nameCtrl = TextEditingController(text: p?.name);
    _businessNameCtrl = TextEditingController(text: p?.businessName);
    _vatCtrl = TextEditingController(text: p?.vatNumber);
    _cfCtrl = TextEditingController(text: p?.fiscalCode);
    _sdiCtrl = TextEditingController(text: p?.sdiCode);
    _pecCtrl = TextEditingController(text: p?.emailPec);

    // Inizializziamo il Cubit appena la schermata si apre
    WidgetsBinding.instance.addPostFrameCallback((_) {
      // Recupero il companyId dall'utente loggato (Vigile Urbano)
      final companyId = context
          .read<SessionCubit>()
          .state
          .currentStore!
          .companyId;

      context.read<ProviderFormCubit>().initForm(
        companyId: companyId,
        existingProvider: widget.existingProvider,
      );
    });
  }

  @override
  void dispose() {
    _nameCtrl.dispose();
    _businessNameCtrl.dispose();
    _vatCtrl.dispose();
    _cfCtrl.dispose();
    _sdiCtrl.dispose();
    _pecCtrl.dispose();
    super.dispose();
  }

  final List<String> _brandColors = [
    '#E60000', // Vodafone/Iliad (Rosso scuro)
    '#0047BB', // TIM (Blu)
    '#F4811F', // WINDTRE (Arancione)
    '#FFCC00', // Fastweb (Giallo)
    '#00A859', // Verde generico
    '#8E44AD', // Viola
    '#2C3E50', // Blu scuro/Nero
    '#607D8B', // BlueGrey (Default)
  ];

  void _flushControllers() {
    context.read<ProviderFormCubit>().updateFields(
      name: _nameCtrl.text.trim(),
      businessName: _businessNameCtrl.text.trim(),
      vatNumber: _vatCtrl.text.trim(),
      fiscalCode: _cfCtrl.text.trim(),
      sdiCode: _sdiCtrl.text.trim(),
      emailPec: _pecCtrl.text.trim(),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isEditing = widget.existingProvider != null;

    return BlocConsumer<ProviderFormCubit, ProviderFormState>(
      listenWhen: (previous, current) => previous.status != current.status,
      listener: (context, state) {
        if (state.status == ProviderFormStatus.success) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('Fornitore salvato con successo!')),
          );
          Navigator.of(context).pop(); // Torna alla lista
        } else if (state.status == ProviderFormStatus.failure) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(state.errorMessage ?? 'Errore di salvataggio'),
              backgroundColor: Colors.red,
            ),
          );
        }
      },
      builder: (context, state) {
        if (state.status == ProviderFormStatus.loading &&
            state.provider.id == null) {
          return const Scaffold(
            body: Center(child: CircularProgressIndicator()),
          );
        }

        return Scaffold(
          appBar: AppBar(
            title: Text(isEditing ? 'Modifica Fornitore' : 'Nuovo Fornitore'),
            actions: [
              FilledButton.icon(
                onPressed: () {
                  if (_formKey.currentState!.validate()) {
                    _flushControllers();
                    context.read<ProviderFormCubit>().save();
                  }
                },
                icon: const Icon(Icons.save),
                label: const Text('Salva'),
              ),
              const SizedBox(width: 16),
            ],
          ),
          body: Form(
            key: _formKey,
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  _buildGeneralCard(context, state),
                  const SizedBox(height: 24),
                  _buildColorPicker(),
                  const SizedBox(height: 24),
                  _buildRolesCard(context, state),
                  const SizedBox(height: 24),
                  _buildFiscalCard(context),
                  const SizedBox(height: 24),
                  _buildStoresCard(context, state),
                  const SizedBox(height: 24),
                  _buildLocationsCard(context, state),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // --- CARD 1: DATI GENERALI ---
  Widget _buildGeneralCard(BuildContext context, ProviderFormState state) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Dati Generali',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _nameCtrl,
              decoration: const InputDecoration(
                labelText: 'Nome Fornitore (Display Name) *',
                prefixIcon: Icon(Icons.storefront),
              ),
              validator: (val) =>
                  val == null || val.isEmpty ? 'Campo obbligatorio' : null,
            ),
            const SizedBox(height: 16),
            // Volendo qui puoi aggiungere lo Switch per "Attivo/Inattivo"
          ],
        ),
      ),
    );
  }

  // --- CARD 2: RUOLI (I CHIPS NINJA) ---
  Widget _buildRolesCard(BuildContext context, ProviderFormState state) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Ruoli e Servizi',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const Text(
              'Seleziona cosa fa questo fornitore (puoi sceglierne più di uno):',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            const SizedBox(height: 16),
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: ProviderRole.values.map((role) {
                final isSelected = state.provider.roles.contains(role);
                return FilterChip(
                  label: Text(role.displayValue),
                  selected: isSelected,
                  selectedColor: role.color.withValues(alpha: 0.2),
                  checkmarkColor: role.color,
                  side: BorderSide(color: role.color.withValues(alpha: 0.3)),
                  onSelected: (bool selected) {
                    context.read<ProviderFormCubit>().toggleRole(role);
                  },
                );
              }).toList(),
            ),
          ],
        ),
      ),
    );
  }

  // --- CARD 3: DATI FISCALI ---
  Widget _buildFiscalCard(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Dati Fiscali (Per DDT e Fatturazione)',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 16),
            TextFormField(
              controller: _businessNameCtrl,
              decoration: const InputDecoration(
                labelText: 'Ragione Sociale (es. Tech SpA)',
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _vatCtrl,
                    decoration: const InputDecoration(labelText: 'Partita IVA'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _cfCtrl,
                    decoration: const InputDecoration(
                      labelText: 'Codice Fiscale',
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: TextFormField(
                    controller: _sdiCtrl,
                    decoration: const InputDecoration(labelText: 'Codice SDI'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: TextFormField(
                    controller: _pecCtrl,
                    decoration: const InputDecoration(labelText: 'Email PEC'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // --- CARD 4: NEGOZI ABILITATI ---
  Widget _buildStoresCard(BuildContext context, ProviderFormState state) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Negozi Abilitati',
              style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
            ),
            const Text(
              'In quali punti vendita deve apparire questo fornitore?',
              style: TextStyle(fontSize: 12, color: Colors.grey),
            ),
            const SizedBox(height: 16),
            if (state.availableStores.isEmpty)
              const Center(
                child: Text(
                  'Nessun negozio trovato.',
                  style: TextStyle(fontStyle: FontStyle.italic),
                ),
              )
            else
              ...state.availableStores.map((storeMap) {
                final storeId = storeMap['id'] as String;
                final storeName = storeMap['name'] as String;
                final isEnabled = state.selectedStoreIds.contains(storeId);

                return SwitchListTile(
                  title: Text(storeName),
                  value: isEnabled,
                  onChanged: (bool val) {
                    context.read<ProviderFormCubit>().toggleStore(storeId);
                  },
                );
              }),
          ],
        ),
      ),
    );
  }

  Widget _buildLocationsCard(BuildContext context, ProviderFormState state) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  'Sedi e Laboratori',
                  style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                ),
                IconButton.filledTonal(
                  onPressed: () async {
                    ProviderFormCubit providerFormCubit = context
                        .read<ProviderFormCubit>();
                    final res = await showDialog<ProviderLocationModel?>(
                      context: context,
                      builder: (context) => const ProviderLocationDialog(),
                    );
                    if (res != null) {
                      // Chiama il cubit per aggiungere localmente
                      providerFormCubit.addLocationLocal(res);
                    }
                  },
                  icon: const Icon(Icons.add_location_alt),
                ),
              ],
            ),
            const SizedBox(height: 16),
            if (state.localLocations.isEmpty)
              const Text(
                'Nessun indirizzo di spedizione inserito.',
                style: TextStyle(fontStyle: FontStyle.italic),
              )
            else
              ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: state.localLocations.length,
                itemBuilder: (context, index) {
                  final loc = state.localLocations[index];
                  return ListTile(
                    leading: Icon(
                      loc.isMain ? Icons.star : Icons.location_on,
                      color: loc.isMain ? Colors.amber : null,
                    ),
                    title: Text(loc.name),
                    subtitle: Text(
                      '${loc.address}, ${loc.city} (${loc.province})',
                    ),
                    trailing: IconButton(
                      icon: const Icon(Icons.delete_outline, color: Colors.red),
                      onPressed: () => context
                          .read<ProviderFormCubit>()
                          .removeLocationLocal(index),
                    ),
                  );
                },
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildColorPicker() {
    return Column(
      children: [
        const Text(
          'Colore Riconoscitivo',
          style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
        ),
        const SizedBox(height: 12),
        BlocBuilder<ProviderFormCubit, ProviderFormState>(
          builder: (context, state) {
            // Se non ha un colore, usiamo il BlueGrey di default
            final currentColorHex = state.provider.colorHex ?? '#607D8B';

            return Wrap(
              spacing: 12,
              runSpacing: 12,
              children: _brandColors.map((hexCode) {
                final isSelected =
                    currentColorHex.toUpperCase() == hexCode.toUpperCase();

                // Conversione rapida per disegnare il cerchio
                final colorValue = Color(
                  int.parse('FF${hexCode.replaceAll('#', '')}', radix: 16),
                );

                return InkWell(
                  borderRadius: BorderRadius.circular(24),
                  onTap: () {
                    // Aggiorniamo il Cubit con il nuovo colore
                    context.read<ProviderFormCubit>().updateFields(
                      colorHex: () => hexCode,
                    );
                  },
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 200),
                    width: 42,
                    height: 42,
                    decoration: BoxDecoration(
                      color: colorValue,
                      shape: BoxShape.circle,
                      border: Border.all(
                        color: isSelected ? Colors.black : Colors.transparent,
                        width: isSelected ? 3 : 0,
                      ),
                      boxShadow: [
                        if (isSelected)
                          BoxShadow(
                            color: colorValue.withValues(alpha: 0.4),
                            blurRadius: 8,
                            spreadRadius: 2,
                          ),
                      ],
                    ),
                    child: isSelected
                        ? const Icon(Icons.check, color: Colors.white, size: 24)
                        : null,
                  ),
                );
              }).toList(),
            );
          },
        ),
      ],
    );
  }
}
