import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/theme/theme.dart';
import 'package:flux/core/widgets/flux_text_field.dart';

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

  @override
  State<CreateStoreScreen> createState() => _CreateStoreScreenState();
}

class _CreateStoreScreenState extends State<CreateStoreScreen> {
  final _formKey = GlobalKey<FormState>();

  final _nomeController = TextEditingController();
  final _indirizzoController = TextEditingController();
  final _capController = TextEditingController();
  final _comuneController = TextEditingController();
  final _provinciaController = TextEditingController();

  @override
  void dispose() {
    _nomeController.dispose();
    _indirizzoController.dispose();
    _capController.dispose();
    _comuneController.dispose();
    _provinciaController.dispose();
    super.dispose();
  }

  /// Funzione magica per copiare i dati dall'azienda salvata in GetIt
  void _useCompanyAddress() {
    final company = context.read<SessionCubit>().state.company;
    if (company != null) {
      setState(() {
        _indirizzoController.text = company.address;
        _capController.text = company.zipCode;
        _comuneController.text =
            company.city; // Nel DB company è 'citta', store è 'comune'
        _provinciaController.text = company.province;
        // Suggeriamo anche un nome se vuoto
        if (_nomeController.text.isEmpty) {
          _nomeController.text = '${company.name} - Sede';
        }
      });

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Dati indirizzo copiati dalla sede legale'),
        ),
      );
    }
  }

  void _onSave() {
    if (_formKey.currentState!.validate()) {
      final company = context.read<SessionCubit>().state.company;

      if (company == null) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(content: Text('Errore: Azienda non trovata')),
        );
        return;
      }

      final store = StoreModel(
        name: _nomeController.text.trim(),
        companyId: company.id!,
        address: _indirizzoController.text.trim(),
        zipCode: _capController.text.trim(),
        city: _comuneController.text.trim(),
        province: _provinciaController.text.trim().toUpperCase(),
      );

      context.read<StoreCubit>().saveStore(store);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Il tuo primo Negozio')),
      body: BlocBuilder<StoreCubit, StoreState>(
        /* listener: (context, state) {
          if (state.status == StoreStatus.success) {
            context.read<SessionCubit>().;
          }
          if (state.status == StoreStatus.failure) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.errorMessage ?? 'Errore salvataggio'),
              ),
            );
          }
        }, */
        builder: (context, state) {
          return SafeArea(
            child: SingleChildScrollView(
              padding: const EdgeInsets.all(24.0),
              child: Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _buildHeader(context),
                    const SizedBox(height: 32),

                    // Nome del Negozio (Icona obbligatoria)
                    FluxTextField(
                      label: 'Nome del Negozio',
                      icon: Icons.storefront_rounded,
                      controller: _nomeController,
                      keyboardType: TextInputType.name,
                    ),

                    const SizedBox(height: 24),

                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _SectionTitle(title: 'LOCALIZZAZIONE'),
                        TextButton.icon(
                          onPressed: _useCompanyAddress,
                          icon: const Icon(Icons.copy_rounded, size: 16),
                          label: const Text(
                            'Copia da Azienda',
                            style: TextStyle(fontSize: 12),
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 12),

                    // Indirizzo (Icona obbligatoria)
                    FluxTextField(
                      label: 'Indirizzo e n. civico',
                      icon: Icons.map_outlined,
                      controller: _indirizzoController,
                      keyboardType: TextInputType.streetAddress,
                    ),
                    const SizedBox(height: 16),

                    // RIGA TRIPLA: Comune, CAP, PR
                    Row(
                      crossAxisAlignment: CrossAxisAlignment
                          .start, // Allinea in alto in caso di errori
                      children: [
                        Expanded(
                          flex: 2,
                          child: FluxTextField(
                            label: 'CAP',
                            icon: Icons.post_add_rounded, // Icona aggiunta
                            controller: _capController,
                            keyboardType: TextInputType.number,
                            maxLength: 5,
                          ),
                        ),

                        const SizedBox(width: 12),
                        Expanded(
                          flex: 3,
                          child: FluxTextField(
                            label: 'Comune',
                            icon: Icons.location_city_rounded, // Icona aggiunta
                            controller: _comuneController,
                            keyboardType: TextInputType.name,
                          ),
                        ),
                        const SizedBox(width: 12),
                        Expanded(
                          flex: 2, // Aumentato leggermente per ospitare l'icona
                          child: FluxTextField(
                            label: 'PR',
                            icon: Icons.explore_outlined, // Icona aggiunta
                            controller: _provinciaController,
                            keyboardType: TextInputType.name,
                            onChanged: (value) => value.toUpperCase(),
                            maxLength: 2,
                          ),
                        ),
                      ],
                    ),

                    const SizedBox(height: 48),

                    _buildSubmitButton(context, state),
                  ],
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildSubmitButton(BuildContext context, StoreState state) {
    return SizedBox(
      width: double.infinity,
      height: 56,
      child: ElevatedButton(
        onPressed: state.status == StoreStatus.loading ? null : _onSave,
        child: state.status == StoreStatus.loading
            ? const CircularProgressIndicator(color: Colors.white)
            : const Text('ATTIVA NEGOZIO'),
      ),
    );
  }

  Widget _buildHeader(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Icon(Icons.add_location_alt_rounded, color: context.accent, size: 48),
        const SizedBox(height: 16),
        Text(
          'Dove si trova il tuo store?',
          style: Theme.of(context).textTheme.headlineMedium?.copyWith(
            fontWeight: FontWeight.bold,
            color: context.primaryText,
          ),
        ),
        const SizedBox(height: 8),
        Text(
          'Configura il primo punto vendita per iniziare a gestire i tuoi clienti e le operazioni.',
          style: TextStyle(color: context.secondaryText, fontSize: 15),
        ),
      ],
    );
  }
}

class _SectionTitle extends StatelessWidget {
  final String title;
  const _SectionTitle({required this.title});

  @override
  Widget build(BuildContext context) {
    return Text(
      title,
      style: TextStyle(
        color: context.accent,
        fontWeight: FontWeight.w800,
        letterSpacing: 1.2,
        fontSize: 12,
      ),
    );
  }
}
