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

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

/// Scelta della classe destinazione per riprogrammare una prenotazione.
/// Ritorna `true` (via Navigator.pop) se la riprogrammazione è avvenuta.
class TeacherReprogramPage extends StatefulWidget {
  final String token;
  final int bookingId;
  final String participantName;

  const TeacherReprogramPage({
    super.key,
    required this.token,
    required this.bookingId,
    required this.participantName,
  });

  @override
  State<TeacherReprogramPage> createState() => _TeacherReprogramPageState();
}

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

  bool _loading = true;
  String _error = '';
  List<TeacherClass> _classes = [];

  int? _selectedScheduleId;
  bool _countAsReprogram = true; // default: conta come riprogrammazione
  bool _submitting = false;

  @override
  void initState() {
    super.initState();
    _load();
  }

  Future<void> _load() async {
    setState(() {
      _loading = true;
      _error = '';
    });
    try {
      final data = await TeacherApi.availableClasses(
        token: widget.token,
        bookingId: widget.bookingId,
      );
      setState(() => _classes = data);
    } catch (e) {
      setState(() => _error = 'Errore: $e');
    } finally {
      if (mounted) setState(() => _loading = false);
    }
  }

  String _fmt(String iso) {
    final dt = DateTime.tryParse(iso);
    if (dt == null) return iso;
    final s = DateFormat("EEE d MMM yyyy, HH:mm", 'it_IT').format(dt);
    return s[0].toUpperCase() + s.substring(1);
  }

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

  Future<void> _confirm() async {
    if (_selectedScheduleId == null) {
      _snack('Seleziona una classe di destinazione.');
      return;
    }
    setState(() => _submitting = true);
    try {
      await TeacherApi.reprogram(
        token: widget.token,
        bookingId: widget.bookingId,
        scheduleId: _selectedScheduleId!,
        countAsReprogram: _countAsReprogram,
      );
      if (!mounted) return;
      Navigator.pop(context, true); // segnala successo al chiamante
    } catch (e) {
      _snack('$e');
      setState(() => _submitting = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        centerTitle: true,
        title: const Text(
          'Riprogramma',
          style: TextStyle(fontWeight: FontWeight.w800, fontSize: 18),
        ),
      ),
      body: YogibookBackground(
        child: SafeArea(
          top: false,
          child: _loading
              ? const Center(child: CircularProgressIndicator())
              : _error.isNotEmpty
              ? _errorBox()
              : Column(
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
                      child: _headerInfo(),
                    ),
                    Expanded(
                      child: _classes.isEmpty
                          ? _emptyBox()
                          : ListView.builder(
                              padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
                              itemCount: _classes.length,
                              itemBuilder: (_, i) => _classTile(_classes[i]),
                            ),
                    ),
                    _bottomBar(),
                  ],
                ),
        ),
      ),
    );
  }

  Widget _headerInfo() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(14),
        boxShadow: const [
          BoxShadow(
            blurRadius: 12,
            color: Color(0x0F000000),
            offset: Offset(0, 6),
          ),
        ],
      ),
      child: Row(
        children: [
          const Icon(Icons.person, size: 20, color: Colors.black45),
          const SizedBox(width: 10),
          Expanded(
            child: Text(
              'Sposta la lezione di ${widget.participantName}',
              style: const TextStyle(fontWeight: FontWeight.w700, fontSize: 14),
            ),
          ),
        ],
      ),
    );
  }

  Widget _classTile(TeacherClass c) {
    final selected = _selectedScheduleId == c.scheduleId;
    return GestureDetector(
      onTap: () => setState(() => _selectedScheduleId = c.scheduleId),
      child: 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: Border.all(
            color: selected ? kGreen : const Color(0x14000000),
            width: selected ? 2 : 1,
          ),
          boxShadow: const [
            BoxShadow(
              blurRadius: 10,
              color: Color(0x0A000000),
              offset: Offset(0, 4),
            ),
          ],
        ),
        child: Row(
          children: [
            Icon(
              selected
                  ? Icons.radio_button_checked
                  : Icons.radio_button_unchecked,
              color: selected ? kGreen : Colors.black26,
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    c.className,
                    style: const TextStyle(
                      fontWeight: FontWeight.w800,
                      fontSize: 15,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  const SizedBox(height: 4),
                  Text(
                    _fmt(c.dateTime),
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xFF606060),
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 8),
            Text(
              '${c.bookedCount}/${c.maxCapacity}',
              style: const TextStyle(
                fontSize: 12,
                fontWeight: FontWeight.w800,
                color: Color(0xFF1A7F52),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _bottomBar() {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 10, 16, 16),
      decoration: const BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            blurRadius: 16,
            color: Color(0x14000000),
            offset: Offset(0, -6),
          ),
        ],
      ),
      child: SafeArea(
        top: false,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SwitchListTile(
              contentPadding: EdgeInsets.zero,
              activeColor: kGreen,
              value: _countAsReprogram,
              onChanged: _submitting
                  ? null
                  : (v) => setState(() => _countAsReprogram = v),
              title: const Text(
                'Conta come riprogrammazione',
                style: TextStyle(fontWeight: FontWeight.w700, fontSize: 14),
              ),
              subtitle: const Text(
                'Se attivo, incrementa il contatore riprogrammazioni dell\'ordine.',
                style: TextStyle(fontSize: 12),
              ),
            ),
            const SizedBox(height: 8),
            SizedBox(
              width: double.infinity,
              height: 48,
              child: ElevatedButton(
                style: ElevatedButton.styleFrom(
                  backgroundColor: kGreen,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(14),
                  ),
                ),
                onPressed: _submitting ? null : _confirm,
                child: _submitting
                    ? const SizedBox(
                        height: 18,
                        width: 18,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          color: Colors.white,
                        ),
                      )
                    : const Text(
                        'Conferma riprogrammazione',
                        style: TextStyle(
                          fontWeight: FontWeight.w900,
                          color: Colors.white,
                        ),
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _emptyBox() {
    return const Center(
      child: Padding(
        padding: EdgeInsets.all(24),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.event_busy, size: 56, color: Colors.black26),
            SizedBox(height: 12),
            Text(
              'Nessuna classe disponibile',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w800,
                color: Colors.black54,
              ),
            ),
            SizedBox(height: 6),
            Text(
              'Non ci sono classi future con posti liberi\nper questo allievo.',
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.black45),
            ),
          ],
        ),
      ),
    );
  }

  Widget _errorBox() {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(18),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Icon(Icons.error_outline, size: 56, color: Colors.redAccent),
            const SizedBox(height: 10),
            Text(_error, textAlign: TextAlign.center),
            const SizedBox(height: 12),
            ElevatedButton(onPressed: _load, child: const Text('Riprova')),
          ],
        ),
      ),
    );
  }
}
