import 'package:flutter/material.dart';
import '../models/provider_location_model.dart';

class ProviderLocationDialog extends StatefulWidget {
  final ProviderLocationModel? initialLocation;

  const ProviderLocationDialog({super.key, this.initialLocation});

  @override
  State<ProviderLocationDialog> createState() => _ProviderLocationDialogState();
}

class _ProviderLocationDialogState extends State<ProviderLocationDialog> {
  final _formKey = GlobalKey<FormState>();
  late final TextEditingController _nameCtrl;
  late final TextEditingController _addressCtrl;
  late final TextEditingController _cityCtrl;
  late final TextEditingController _zipCtrl;
  late final TextEditingController _provCtrl;
  late final TextEditingController _contactCtrl;
  bool _isMain = false;

  @override
  void initState() {
    super.initState();
    final l = widget.initialLocation;
    _nameCtrl = TextEditingController(text: l?.name);
    _addressCtrl = TextEditingController(text: l?.address);
    _cityCtrl = TextEditingController(text: l?.city);
    _zipCtrl = TextEditingController(text: l?.zipCode);
    _provCtrl = TextEditingController(text: l?.province);
    _contactCtrl = TextEditingController(text: l?.contactPerson);
    _isMain = l?.isMain ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(
        widget.initialLocation == null
            ? 'Aggiungi Sede/Laboratorio'
            : 'Modifica Sede',
      ),
      content: SingleChildScrollView(
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextFormField(
                controller: _nameCtrl,
                decoration: const InputDecoration(
                  labelText: 'Nome Sede (es. Laboratorio Sud) *',
                ),
                validator: (v) => v!.isEmpty ? 'Obbligatorio' : null,
              ),
              TextFormField(
                controller: _addressCtrl,
                decoration: const InputDecoration(labelText: 'Indirizzo *'),
                validator: (v) => v!.isEmpty ? 'Obbligatorio' : null,
              ),
              Row(
                children: [
                  Expanded(
                    flex: 2,
                    child: TextFormField(
                      controller: _cityCtrl,
                      decoration: const InputDecoration(labelText: 'Città *'),
                      validator: (v) => v!.isEmpty ? 'Obbligatorio' : null,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: TextFormField(
                      controller: _provCtrl,
                      decoration: const InputDecoration(labelText: 'Prov.'),
                      maxLength: 2,
                    ),
                  ),
                ],
              ),
              TextFormField(
                controller: _zipCtrl,
                decoration: const InputDecoration(labelText: 'CAP *'),
                keyboardType: TextInputType.number,
                validator: (v) => v!.isEmpty ? 'Obbligatorio' : null,
              ),
              TextFormField(
                controller: _contactCtrl,
                decoration: const InputDecoration(
                  labelText: 'Referente (opzionale)',
                ),
              ),
              SwitchListTile(
                title: const Text('Sede Principale'),
                value: _isMain,
                onChanged: (v) => setState(() => _isMain = v),
              ),
            ],
          ),
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('Annulla'),
        ),
        FilledButton(
          onPressed: () {
            if (_formKey.currentState!.validate()) {
              ProviderLocationModel newLocation = ProviderLocationModel(
                id: widget.initialLocation?.id,
                name: _nameCtrl.text.trim(),
                address: _addressCtrl.text.trim(),
                city: _cityCtrl.text.trim(),
                zipCode: _zipCtrl.text.trim(),
                province: _provCtrl.text.trim().toUpperCase(),
                contactPerson: _contactCtrl.text.trim(),
                isMain: _isMain,
                companyId: widget.initialLocation?.companyId ?? '',
                providerId: widget.initialLocation?.providerId ?? '',
              );
              // Restituiamo una mappa o un modello parziale (senza ID e FK che gestirà il Cubit)
              Navigator.pop(context, newLocation);
            }
          },
          child: const Text('Conferma'),
        ),
      ],
    );
  }
}
