import 'package:flutter/material.dart';
import 'main.dart'; // per VanguardApi

class SelectSchoolPage extends StatefulWidget {
  final String token;

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

  @override
  State<SelectSchoolPage> createState() => _SelectSchoolPageState();
}

class _SelectSchoolPageState extends State<SelectSchoolPage> {
  bool loading = true;
  String error = '';
  List schools = [];

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

  Future<void> _loadSchools() async {
    try {
      final data = await VanguardApi.getUserSchools(token: widget.token);

      if (data['success'] != true) {
        throw Exception(data['message'] ?? 'Errore sconosciuto');
      }

      final List list = data['schools'] ?? [];

      // Auto select
      if (data['auto_select'] == true && list.length == 1) {
        _enterSchool(list.first);
        return;
      }

      setState(() {
        schools = list;
        loading = false;
      });
    } catch (e) {
      setState(() {
        error = e.toString();
        loading = false;
      });
    }
  }

  void _enterSchool(Map school) {
    // per ora debug
    Navigator.pushReplacement(
      context,
      MaterialPageRoute(builder: (_) => SuccessPage(token: widget.token)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Scegli la scuola')),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : error.isNotEmpty
          ? Center(child: Text(error))
          : ListView.builder(
              itemCount: schools.length,
              itemBuilder: (context, i) {
                final s = schools[i];
                return ListTile(
                  leading: s['logo'] != null
                      ? Image.network(s['logo'], width: 40)
                      : const Icon(Icons.school),
                  title: Text(s['name']),
                  subtitle: Text(s['address_full'] ?? ''),
                  onTap: () => _enterSchool(s),
                );
              },
            ),
    );
  }
}
