import 'package:flutter/material.dart';

class QuickRenameDialog extends StatefulWidget {
  final String suggestedName;
  final Widget previewWidget; // Può essere Image.memory o un'icona PDF

  const QuickRenameDialog({
    super.key,
    required this.suggestedName,
    required this.previewWidget,
  });

  @override
  State<QuickRenameDialog> createState() => _QuickRenameDialogState();
}

class _QuickRenameDialogState extends State<QuickRenameDialog> {
  late TextEditingController _nameCtrl;
  final FocusNode _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _nameCtrl = TextEditingController(text: widget.suggestedName);

    // MAGIA UX: Selezioniamo tutto il testo di default appena si apre!
    _nameCtrl.selection = TextSelection(
      baseOffset: 0,
      extentOffset: widget.suggestedName.length,
    );

    // Richiediamo il focus appena il widget è costruito
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    _nameCtrl.dispose();
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('Rinomina per Export'),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // Anteprima del documento (limitiamo l'altezza)
          Container(
            height: 200,
            width: double.infinity,
            decoration: BoxDecoration(border: Border.all(color: Colors.grey)),
            child: widget.previewWidget,
          ),
          const SizedBox(height: 16),
          TextField(
            controller: _nameCtrl,
            focusNode: _focusNode,
            decoration: const InputDecoration(
              labelText: 'Nome del file',
              suffixText: '.pdf', // Facciamo capire che sarà un PDF
              border: OutlineInputBorder(),
            ),
            // MAGIA UX 2: Se preme invio sulla tastiera, salva e chiude!
            onSubmitted: (value) => Navigator.of(context).pop(value),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(), // Ritorna null
          child: const Text('Salta'),
        ),
        ElevatedButton(
          onPressed: () => Navigator.of(context).pop(_nameCtrl.text),
          child: const Text('Esporta (Invio)'),
        ),
      ],
    );
  }
}
