import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/settings/blocs/reminder_defaults_cubit.dart';

class ReminderSettingsScreen extends StatefulWidget {
  const ReminderSettingsScreen({super.key});

  @override
  State<ReminderSettingsScreen> createState() => _ReminderSettingsScreenState();
}

class _ReminderSettingsScreenState extends State<ReminderSettingsScreen> {
  @override
  void initState() {
    super.initState();
    // Carichiamo i dati all'avvio
    context.read<ReminderDefaultsCubit>().loadReminders();
  }

  void _showAddReminderBottomSheet(BuildContext context) {
    final cubit = context.read<ReminderDefaultsCubit>();
    // Valori preselezionati
    int selectedMinutes = 15;
    String selectedChannel = 'push';

    showModalBottomSheet(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      builder: (bottomSheetContext) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            return SafeArea(
              child: Padding(
                padding: const EdgeInsets.all(24.0),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    const Text(
                      'Nuova Regola di Avviso',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 24),

                    // --- SELEZIONE TEMPO ---
                    DropdownButtonFormField<int>(
                      decoration: const InputDecoration(
                        labelText: 'Quando vuoi essere avvisato?',
                        border: OutlineInputBorder(),
                      ),
                      initialValue: selectedMinutes,
                      items: const [
                        DropdownMenuItem(
                          value: 5,
                          child: Text('5 minuti prima'),
                        ),
                        DropdownMenuItem(
                          value: 15,
                          child: Text('15 minuti prima'),
                        ),
                        DropdownMenuItem(value: 60, child: Text('1 ora prima')),
                        DropdownMenuItem(
                          value: 120,
                          child: Text('2 ore prima'),
                        ),
                        DropdownMenuItem(
                          value: 1440,
                          child: Text('1 giorno prima'),
                        ),
                      ],
                      onChanged: (val) {
                        if (val != null) {
                          setModalState(() => selectedMinutes = val);
                        }
                      },
                    ),
                    const SizedBox(height: 16),

                    // --- SELEZIONE CANALE ---
                    DropdownButtonFormField<String>(
                      decoration: const InputDecoration(
                        labelText: 'Come vuoi essere avvisato?',
                        border: OutlineInputBorder(),
                      ),
                      initialValue: selectedChannel,
                      items: const [
                        DropdownMenuItem(
                          value: 'push',
                          child: Row(
                            children: [
                              Icon(
                                Icons.notifications_active,
                                size: 20,
                                color: Colors.orange,
                              ),
                              SizedBox(width: 8),
                              Text('Notifica App (Push)'),
                            ],
                          ),
                        ),
                        DropdownMenuItem(
                          value: 'email',
                          child: Row(
                            children: [
                              Icon(Icons.email, size: 20, color: Colors.blue),
                              SizedBox(width: 8),
                              Text('Email'),
                            ],
                          ),
                        ),
                      ],
                      onChanged: (val) {
                        if (val != null) {
                          setModalState(() => selectedChannel = val);
                        }
                      },
                    ),
                    const SizedBox(height: 32),

                    // --- SALVATAGGIO ---
                    FilledButton(
                      style: FilledButton.styleFrom(
                        padding: const EdgeInsets.symmetric(vertical: 16),
                      ),
                      onPressed: () {
                        cubit.addReminder(
                          minutesBefore: selectedMinutes,
                          channel: selectedChannel,
                        );
                        Navigator.pop(context);
                      },
                      child: const Text('Aggiungi Regola'),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Preferenze Promemoria')),
      floatingActionButton: FloatingActionButton.extended(
        onPressed: () => _showAddReminderBottomSheet(context),
        icon: const Icon(Icons.add_alert),
        label: const Text('Aggiungi'),
        backgroundColor: Colors.orange,
      ),
      body: BlocConsumer<ReminderDefaultsCubit, ReminderDefaultsState>(
        listener: (context, state) {
          if (state.status == ReminderDefaultsStatus.failure &&
              state.errorMessage != null) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text(state.errorMessage!),
                backgroundColor: Theme.of(context).colorScheme.error,
              ),
            );
          }
        },
        builder: (context, state) {
          if (state.status == ReminderDefaultsStatus.loading &&
              state.reminders.isEmpty) {
            return const Center(child: CircularProgressIndicator());
          }

          if (state.reminders.isEmpty) {
            return Center(
              child: Padding(
                padding: const EdgeInsets.all(32.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.notifications_off_outlined,
                      size: 64,
                      color: Theme.of(context).dividerColor,
                    ),
                    const SizedBox(height: 16),
                    const Text(
                      'Nessun promemoria predefinito.',
                      style: TextStyle(
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 8),
                    const Text(
                      'Aggiungi una regola per ricevere in automatico le notifiche quando ti viene assegnato un task.',
                      textAlign: TextAlign.center,
                      style: TextStyle(color: Colors.grey),
                    ),
                  ],
                ),
              ),
            );
          }

          return ListView.builder(
            padding: const EdgeInsets.only(
              top: 16,
              bottom: 80,
              left: 16,
              right: 16,
            ),
            itemCount: state.reminders.length,
            itemBuilder: (context, index) {
              final reminder = state.reminders[index];
              final isPush = reminder.channel == 'push';

              return Card(
                elevation: 0,
                margin: const EdgeInsets.only(bottom: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                  side: BorderSide(
                    color: Theme.of(
                      context,
                    ).dividerColor.withValues(alpha: 0.5),
                  ),
                ),
                child: ListTile(
                  contentPadding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 8,
                  ),
                  leading: CircleAvatar(
                    backgroundColor: isPush
                        ? Colors.orange.withValues(alpha: 0.1)
                        : Colors.blue.withValues(alpha: 0.1),
                    child: Icon(
                      isPush ? Icons.notifications_active : Icons.email,
                      color: isPush ? Colors.orange : Colors.blue,
                    ),
                  ),
                  title: Text(
                    reminder.friendlyTime, // Usiamo l'helper del Model!
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  subtitle: Text(
                    isPush ? 'Tramite Notifica App' : 'Tramite Email',
                  ),
                  trailing: IconButton(
                    icon: const Icon(
                      Icons.delete_outline,
                      color: Colors.redAccent,
                    ),
                    onPressed: () {
                      context.read<ReminderDefaultsCubit>().deleteReminder(
                        reminder.id!,
                      );
                    },
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}
