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

import '../services/teacher_api.dart';
import '../widgets/yogibook_background.dart';
import 'teacher_reprogram_page.dart';
import 'teacher_add_participant_page.dart';

/// Dettaglio di una classe (vista insegnante).
/// Fase 2a: elenco iscritti + segna persa / ripristina.
class TeacherClassDetailPage extends StatefulWidget {
  final String token;
  final TeacherClass cls;

  const TeacherClassDetailPage({
    super.key,
    required this.token,
    required this.cls,
  });

  @override
  State<TeacherClassDetailPage> createState() => _TeacherClassDetailPageState();
}

class _TeacherClassDetailPageState extends State<TeacherClassDetailPage> {
  static const Color kGreen = Color(0xFF10B981);

  // copia locale modificabile dei partecipanti (per aggiornare la UI)
  late List<TeacherParticipant> _participants;
  int _busyBookingId =
      0; // booking in aggiornamento (per disabilitare il tasto)

  @override
  void initState() {
    super.initState();
    _participants = List.of(widget.cls.participants);
  }

  String _fmtDate(String iso) {
    final dt = DateTime.tryParse(iso);
    if (dt == null) return iso;
    final s = DateFormat("EEEE d MMMM yyyy", 'it_IT').format(dt);
    return s[0].toUpperCase() + s.substring(1);
  }

  String _fmtTime(String iso) {
    final dt = DateTime.tryParse(iso);
    if (dt == null) return '';
    return DateFormat('HH:mm').format(dt);
  }

  void _snack(String msg) {
    if (!mounted) return;
    ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
  }

  Future<void> _toggleLost(TeacherParticipant p) async {
    final markLost = !p.isLost;

    // conferma solo quando si segna persa (azione visibile all'allievo)
    if (markLost) {
      final ok = await showDialog<bool>(
        context: context,
        builder: (ctx) => AlertDialog(
          title: const Text('Segnare come persa?'),
          content: Text(
            'Vuoi segnare la lezione di ${p.fullName} come persa? '
            'Resterà registrata e non tornerà disponibile all\'allievo.',
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(ctx, false),
              child: const Text('Annulla'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(ctx, true),
              child: const Text('Segna persa'),
            ),
          ],
        ),
      );
      if (ok != true) return;
    }

    setState(() => _busyBookingId = p.bookingId);
    try {
      await TeacherApi.setLost(
        token: widget.token,
        bookingId: p.bookingId,
        lost: markLost,
      );
      // aggiorna la copia locale sostituendo il partecipante
      final idx = _participants.indexWhere((x) => x.bookingId == p.bookingId);
      if (idx != -1) {
        setState(() {
          _participants[idx] = TeacherParticipant(
            bookingId: p.bookingId,
            fullName: p.fullName,
            isLost: markLost,
          );
        });
      }
      _snack(markLost ? 'Segnata come persa.' : 'Ripristinata.');
    } catch (e) {
      _snack('$e');
    } finally {
      if (mounted) setState(() => _busyBookingId = 0);
    }
  }

  Future<void> _deleteBooking(TeacherParticipant p) async {
    final ok = await showDialog<bool>(
      context: context,
      builder: (ctx) => AlertDialog(
        title: const Text('Eliminare la prenotazione?'),
        content: Text(
          'Vuoi rimuovere ${p.fullName} da questa classe? '
          'Il posto tornerà disponibile all\'allievo. L\'azione non è reversibile.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(ctx, false),
            child: const Text('Annulla'),
          ),
          ElevatedButton(
            style: ElevatedButton.styleFrom(
              backgroundColor: const Color(0xFFC0392B),
            ),
            onPressed: () => Navigator.pop(ctx, true),
            child: const Text('Elimina'),
          ),
        ],
      ),
    );
    if (ok != true) return;

    setState(() => _busyBookingId = p.bookingId);
    try {
      await TeacherApi.deleteBooking(
        token: widget.token,
        bookingId: p.bookingId,
      );
      setState(() {
        _participants.removeWhere((x) => x.bookingId == p.bookingId);
      });
      _snack('Prenotazione eliminata.');
    } catch (e) {
      _snack('$e');
    } finally {
      if (mounted) setState(() => _busyBookingId = 0);
    }
  }

  Future<void> _reprogram(TeacherParticipant p) async {
    final done = await Navigator.push<bool>(
      context,
      MaterialPageRoute(
        builder: (_) => TeacherReprogramPage(
          token: widget.token,
          bookingId: p.bookingId,
          participantName: p.fullName,
        ),
      ),
    );
    // Se riprogrammata, la prenotazione non è più in questa classe: rimuovila.
    if (done == true && mounted) {
      setState(() {
        _participants.removeWhere((x) => x.bookingId == p.bookingId);
      });
      _snack('${p.fullName} riprogrammata.');
    }
  }

  @override
  Widget build(BuildContext context) {
    final active = _participants.where((p) => !p.isLost).toList();
    final lost = _participants.where((p) => p.isLost).toList();
    final cls = widget.cls;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        title: const Text(
          'Dettaglio classe',
          style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18),
        ),
      ),
      body: YogibookBackground(
        child: SafeArea(
          top: false,
          child: ListView(
            padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
            children: [
              _headerCard(),
              const SizedBox(height: 18),
              _sectionLabel('Iscritti (${active.length})'),
              const SizedBox(height: 8),
              if (active.isEmpty)
                _emptyRow('Nessun iscritto attivo.')
              else
                ...active.map((p) => _tile(p)),
              if (lost.isNotEmpty) ...[
                const SizedBox(height: 18),
                _sectionLabel('Lezioni perse (${lost.length})'),
                const SizedBox(height: 8),
                ...lost.map((p) => _tile(p)),
              ],
              const SizedBox(height: 20),
              SizedBox(
                width: double.infinity,
                height: 50,
                child: ElevatedButton.icon(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: kGreen,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(14),
                    ),
                  ),
                  icon: const Icon(Icons.person_add_alt_1, color: Colors.white),
                  label: const Text(
                    'Aggiungi partecipante',
                    style: TextStyle(
                      fontWeight: FontWeight.w900,
                      color: Colors.white,
                    ),
                  ),
                  onPressed: _openAddParticipant,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _openAddParticipant() async {
    final added = await Navigator.push<bool>(
      context,
      MaterialPageRoute(
        builder: (_) =>
            TeacherAddParticipantPage(token: widget.token, cls: widget.cls),
      ),
    );
    if (added == true && mounted) {
      _snack(
        'Partecipante aggiunto. Aggiorna il pannello per vedere la lista.',
      );
      // torna al pannello classi, che ricaricando mostrerà i dati aggiornati
      Navigator.pop(context, true);
    }
  }

  Widget _headerCard() {
    final cls = widget.cls;
    final isFull = cls.isFull;
    final fillColor = isFull
        ? const Color(0xFFC0392B)
        : (cls.maxCapacity > 0 && cls.bookedCount >= cls.maxCapacity - 1)
        ? const Color(0xFFE67E22)
        : const Color(0xFF1A7F52);

    return Container(
      padding: const EdgeInsets.all(18),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(18),
        boxShadow: const [
          BoxShadow(
            blurRadius: 18,
            color: Color(0x12000000),
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            cls.className,
            style: const TextStyle(fontSize: 20, fontWeight: FontWeight.w900),
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              const Icon(Icons.event, size: 18, color: Colors.black45),
              const SizedBox(width: 8),
              Expanded(
                child: Text(
                  _fmtDate(cls.dateTime),
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Color(0xFF404040),
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: 6),
          Row(
            children: [
              const Icon(Icons.schedule, size: 18, color: Colors.black45),
              const SizedBox(width: 8),
              Text(
                _fmtTime(cls.dateTime),
                style: const TextStyle(
                  fontSize: 13,
                  fontWeight: FontWeight.w700,
                  color: Color(0xFF404040),
                ),
              ),
            ],
          ),
          const SizedBox(height: 14),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
            decoration: BoxDecoration(
              color: fillColor.withOpacity(0.12),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.group, size: 16, color: fillColor),
                const SizedBox(width: 6),
                Text(
                  '${cls.bookedCount} / ${cls.maxCapacity} posti',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w800,
                    color: fillColor,
                  ),
                ),
                if (isFull) ...[
                  const SizedBox(width: 8),
                  Text(
                    '· AL COMPLETO',
                    style: TextStyle(
                      fontSize: 12,
                      fontWeight: FontWeight.w900,
                      color: fillColor,
                    ),
                  ),
                ],
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _sectionLabel(String t) => Text(
    t.toUpperCase(),
    style: const TextStyle(
      fontSize: 12,
      fontWeight: FontWeight.w900,
      color: Colors.black54,
      letterSpacing: 0.5,
    ),
  );

  Widget _emptyRow(String msg) => Container(
    padding: const EdgeInsets.symmetric(vertical: 18, horizontal: 14),
    decoration: BoxDecoration(
      color: Colors.white,
      borderRadius: BorderRadius.circular(14),
    ),
    child: Text(msg, style: const TextStyle(color: Colors.black45)),
  );

  Color _avatarColor(String seed) {
    const palette = [
      Color(0xFF1EBF73),
      Color(0xFF2980B9),
      Color(0xFF8E44AD),
      Color(0xFFE67E22),
      Color(0xFF16A085),
      Color(0xFFC0392B),
      Color(0xFF2C3E50),
      Color(0xFFD35400),
    ];
    int h = 0;
    for (final c in seed.codeUnits) {
      h = (h + c) % palette.length;
    }
    return palette[h];
  }

  String _initials(String fullName) {
    final parts = fullName.trim().split(RegExp(r'\s+'));
    if (parts.isEmpty || parts.first.isEmpty) return '?';
    final a = parts.first[0];
    final b = parts.length > 1 ? parts.last[0] : '';
    return (a + b).toUpperCase();
  }

  Widget _tile(TeacherParticipant p) {
    final lost = p.isLost;
    final busy = _busyBookingId == p.bookingId;

    return Container(
      margin: const EdgeInsets.only(bottom: 8),
      padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        border: lost ? Border.all(color: const Color(0xFFF3D6D2)) : null,
        boxShadow: const [
          BoxShadow(
            blurRadius: 10,
            color: Color(0x0A000000),
            offset: Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 42,
            height: 42,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: lost ? const Color(0xFF9AA5A6) : _avatarColor(p.fullName),
              shape: BoxShape.circle,
            ),
            child: Text(
              _initials(p.fullName),
              style: const TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.w800,
                fontSize: 15,
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: Text(
              p.fullName,
              style: TextStyle(
                fontWeight: FontWeight.w700,
                fontSize: 15,
                color: lost ? Colors.black54 : Colors.black87,
                decoration: lost ? TextDecoration.lineThrough : null,
              ),
            ),
          ),
          // chip stato
          Container(
            margin: const EdgeInsets.only(right: 8),
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
            decoration: BoxDecoration(
              color: lost ? const Color(0xFF1F2937) : const Color(0xFFE3F2EC),
              borderRadius: BorderRadius.circular(20),
            ),
            child: Text(
              lost ? 'Persa' : 'Presente',
              style: TextStyle(
                fontSize: 11,
                fontWeight: FontWeight.w800,
                color: lost ? Colors.white : const Color(0xFF1A7F52),
              ),
            ),
          ),
          // pulsanti azione
          busy
              ? const SizedBox(
                  width: 36,
                  height: 36,
                  child: Padding(
                    padding: EdgeInsets.all(8),
                    child: CircularProgressIndicator(strokeWidth: 2),
                  ),
                )
              : Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    IconButton(
                      onPressed: () => _toggleLost(p),
                      tooltip: lost ? 'Ripristina' : 'Segna persa',
                      icon: Icon(
                        lost ? Icons.undo_rounded : Icons.person_off_rounded,
                        color: lost
                            ? const Color(0xFF1A7F52)
                            : const Color(0xFFC0392B),
                      ),
                    ),
                    if (!lost)
                      IconButton(
                        onPressed: () => _reprogram(p),
                        tooltip: 'Riprogramma',
                        icon: const Icon(
                          Icons.event_repeat_rounded,
                          color: Color(0xFF2980B9),
                        ),
                      ),
                    IconButton(
                      onPressed: () => _deleteBooking(p),
                      tooltip: 'Elimina prenotazione',
                      icon: const Icon(
                        Icons.delete_outline_rounded,
                        color: Colors.black45,
                      ),
                    ),
                  ],
                ),
        ],
      ),
    );
  }
}
