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

import '../../models/device_model.dart';
import '../../providers/device_provider.dart';

class RenameDialog extends StatefulWidget {
  final LasertagDevice device;
  const RenameDialog({super.key, required this.device});

  @override
  State<RenameDialog> createState() => _RenameDialogState();
}

class _RenameDialogState extends State<RenameDialog> {
  late TextEditingController _controller;
  bool _isSaving = false;
  late bool _isReading; // Nicht mehr direkt auf true setzen

  @override
  void initState() {
    super.initState();
    _controller = TextEditingController(text: widget.device.name);
    
    // Wenn der Name schon verifiziert ist, müssen wir nicht blockierend laden
    _isReading = !widget.device.isNameVerified;
    
    _fetchHardwareName();
  }

  Future<void> _fetchHardwareName() async {
    try {
      String hName = await context
          .read<DeviceProvider>()
          .readDeviceNameFromHardware(widget.device);
      if (mounted) {
        setState(() {
          _controller.text = hName;
          _isReading = false;
        });
      }
    } catch (e) {
      if (mounted) setState(() => _isReading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text("${widget.device.name} umbenennen"), // Titel bleibt gleich
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          if (_isReading)
            const Padding(
              padding: EdgeInsets.only(bottom: 10),
              child:
                  LinearProgressIndicator(), // Zeigt, dass wir die Hardware abfragen
            ),
          TextField(
            controller: _controller,
            decoration: InputDecoration(
              labelText: _isReading ? "Lese Hardware..." : "Neuer Name",
              border: const OutlineInputBorder(),
            ),
            enabled: !_isSaving && !_isReading,
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: (_isSaving || _isReading)
              ? null
              : () => Navigator.pop(context),
          child: const Text("Abbrechen"),
        ),
        ElevatedButton(
          onPressed: (_isSaving || _isReading) ? null : _save,
          child: _isSaving
              ? const SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(strokeWidth: 2),
                )
              : const Text("Speichern"),
        ),
      ],
    );
  }

  Future<void> _save() async {
    setState(() => _isSaving = true);
    try {
      await context.read<DeviceProvider>().updateDeviceNameOnHardware(
        widget.device,
        _controller.text.trim(),
      );
      if (mounted) Navigator.pop(context);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text("Fehler: $e"), backgroundColor: Colors.red),
        );
      }
    } finally {
      if (mounted) setState(() => _isSaving = false);
    }
  }
}
