import 'package:flutter/material.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';

class LoanPhoneReturnDialog extends StatefulWidget {
  final List<TicketModel> ticketsWithLoans;

  const LoanPhoneReturnDialog({super.key, required this.ticketsWithLoans});

  @override
  State<LoanPhoneReturnDialog> createState() => _LoanPhoneReturnDialogState();
}

class _LoanPhoneReturnDialogState extends State<LoanPhoneReturnDialog> {
  // Mappa per tenere traccia delle scelte: { ticketId: true/false }
  final Map<String, bool> _returnStatuses = {};

  @override
  void initState() {
    super.initState();
    // Inizializziamo tutto a "true" (di default presumiamo che lo stia restituendo)
    for (var ticket in widget.ticketsWithLoans) {
      _returnStatuses[ticket.id!] = true;
    }
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Row(
        children: [
          Icon(Icons.warning_amber_rounded, color: Colors.orange),
          SizedBox(width: 8),
          Text('Telefoni di cortesia'),
        ],
      ),
      content: SizedBox(
        width: double.maxFinite,
        // Usiamo ListView.builder in caso ce ne siano tanti
        child: ListView.separated(
          shrinkWrap: true,
          itemCount: widget.ticketsWithLoans.length,
          separatorBuilder: (context, index) => const Divider(),
          itemBuilder: (context, index) {
            final ticket = widget.ticketsWithLoans[index];

            final customerName = ticket.customer?.name ?? 'Cliente';

            return SwitchListTile(
              title: Text(
                '$customerName ha un telefono di cortesia in prestito.',
              ),
              subtitle: const Text('Confermi la riconsegna?'),
              value: _returnStatuses[ticket.id!] ?? true,
              activeThumbColor: Theme.of(context).colorScheme.primary,
              onChanged: (bool value) {
                setState(() {
                  _returnStatuses[ticket.id!] = value;
                });
              },
            );
          },
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(null), // Annulla tutto
          child: const Text('Annulla'),
        ),
        FilledButton(
          onPressed: () =>
              Navigator.of(context).pop(_returnStatuses), // Passa la mappa
          child: const Text('Conferma'),
        ),
      ],
    );
  }
}
