import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/widgets/flux_text_field.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart';
import 'package:flux/features/onboarding/blocs/onboarding_state.dart';

class StoreOnboardingForm extends StatefulWidget {
  final OnboardingState state;
  const StoreOnboardingForm({super.key, required this.state});

  @override
  State<StoreOnboardingForm> createState() => _StoreOnboardingFormState();
}

class _StoreOnboardingFormState extends State<StoreOnboardingForm> {
  final _formKey = GlobalKey<FormState>();
  final _nameCtrl = TextEditingController();
  final _addressCtrl = TextEditingController();
  final _cityCtrl = TextEditingController();
  final _zipCodeCtrl = TextEditingController();
  final _provinceCtrl = TextEditingController();

  @override
  void dispose() {
    _nameCtrl.dispose();
    _addressCtrl.dispose();
    _cityCtrl.dispose();
    _zipCodeCtrl.dispose();
    _provinceCtrl.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(32.0),
      child: Form(
        key: _formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              "Il tuo Negozio 🏪",
              style: TextStyle(fontSize: 32, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 8),
            const Text(
              "Dove si trova il tuo punto vendita principale? (Potrai aggiungerne altri in seguito).",
              style: TextStyle(fontSize: 16),
            ),
            const SizedBox(height: 32),

            FluxTextField(
              controller: _nameCtrl,
              label: "Nome del Negozio",
              keyboardType: TextInputType.name,
              validator: (value) =>
                  value == null || value.isEmpty ? "Obbligatorio" : null,
            ),
            const SizedBox(height: 16),

            FluxTextField(
              controller: _addressCtrl,
              keyboardType: TextInputType.streetAddress,
              label: "Indirizzo",
              validator: (value) =>
                  value == null || value.isEmpty ? "Obbligatorio" : null,
            ),
            const SizedBox(height: 16),

            // IL LAYOUT RESPONSIVO PREMIUM
            LayoutBuilder(
              builder: (context, constraints) {
                final isDesktop = constraints.maxWidth >= 600;

                if (isDesktop) {
                  // --- DESKTOP: Tutti su una riga ---
                  return Row(
                    crossAxisAlignment: CrossAxisAlignment
                        .start, // Allinea in alto se ci sono errori
                    children: [
                      Expanded(flex: 2, child: _buildZipField()),
                      const SizedBox(width: 16),
                      Expanded(flex: 5, child: _buildCityField()),
                      const SizedBox(width: 16),
                      Expanded(flex: 2, child: _buildProvField()),
                    ],
                  );
                } else {
                  // --- MOBILE: Comune sopra, CAP e Provincia sotto ---
                  return Column(
                    children: [
                      _buildCityField(),
                      const SizedBox(height: 16),
                      Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Expanded(flex: 3, child: _buildZipField()),
                          const SizedBox(width: 16),
                          Expanded(flex: 2, child: _buildProvField()),
                        ],
                      ),
                    ],
                  );
                }
              },
            ),

            const Spacer(),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              onPressed: () => _submit(),
              child: const Text(
                "Salva Negozio",
                style: TextStyle(fontSize: 16),
              ),
            ),
            const SizedBox(height: 16),
          ],
        ),
      ),
    );
  }

  void _submit() {
    if (_formKey.currentState!.validate()) {
      // MIRACOLO DELLA FACTORY EMPTY!
      final newStore = StoreModel.empty().copyWith(
        name: _nameCtrl.text.trim(),
        address: _addressCtrl.text.trim(),
        city: _cityCtrl.text.trim(),
        zipCode: _zipCodeCtrl.text.trim(),
        // Formattiamo in maiuscolo qui, al momento del salvataggio!
        province: _provinceCtrl.text.trim().toUpperCase(),
      );
      context.read<OnboardingCubit>().saveStore(newStore);
    }
  }

  // --- WIDGET ESTRATTI PER PULIZIA ---

  Widget _buildCityField() {
    return FluxTextField(
      label: 'Comune',
      controller: _cityCtrl,
      keyboardType: TextInputType.name,
    );
  }

  Widget _buildZipField() {
    return FluxTextField(
      label: 'CAP',
      controller: _zipCodeCtrl,
      keyboardType: TextInputType.number,
      // Trucchetto Premium: Limita i caratteri ma NASCONDE il contatore UI
      inputFormatters: [LengthLimitingTextInputFormatter(5)],
    );
  }

  Widget _buildProvField() {
    return FluxTextField(
      label: 'Prov.',
      controller: _provinceCtrl,
      keyboardType: TextInputType.text,
      // Rende la tastiera del telefono automaticamente maiuscola
      textCapitalization: TextCapitalization.characters,
      inputFormatters: [LengthLimitingTextInputFormatter(2)],
      onSubmitted: (_) => _submit(),
    );
  }
}
