import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nfc_google_sheet/components/folder.dart';
import 'package:nfc_google_sheet/context/colories.dart';
import 'package:nfc_google_sheet/pages/matiere_page.dart';
import 'package:nfc_google_sheet/pages/sheet_page.dart';

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

  @override
  _FilierePageState createState() => _FilierePageState();
}

class _FilierePageState extends State<FilierePage> {
  List<dynamic> _filieres = [];
  int? _selectedFiliereIndex;

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

  Future<void> _loadFilieres() async {
    final String response = await rootBundle.loadString('assets/filieres.json');
    final data = await json.decode(response);
    setState(() {
      _filieres = data['filieres'];
    });
  }

  IconData _getIconData(String iconName) {
    switch (iconName) {
      case 'school': return Icons.school;
      case 'laptop_mac': return Icons.laptop_mac;
      case 'laptop_windows': return Icons.laptop_windows;
      case 'book': return Icons.book;
      default: return Icons.folder;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colories.background,
      appBar: AppBar(
        title: Text('Choisir une filière', style: TextStyle(color: Colories.selected)),
        backgroundColor: Colories.background,
        elevation: 0,
        centerTitle: true,
      ),
      body: _filieres.isEmpty
          ? Center(child: CircularProgressIndicator(color: Colories.selected))
          : Padding(
        padding: const EdgeInsets.all(16.0),
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            crossAxisSpacing: 16,
            mainAxisSpacing: 16,
            childAspectRatio: 1,
          ),
          itemCount: _filieres.length,
          itemBuilder: (context, index) {
            final filiere = _filieres[index];
            return Folder(
              nom: filiere['nom'],
              icon: _getIconData(filiere['icon']),
              isSelected: _selectedFiliereIndex == index,
              onTap: () {
                setState(() {
                  _selectedFiliereIndex = index;
                });
                SheetPage.selectedFiliere = filiere['nom'];
                SheetPage.selectedMatiere = null;
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => MatierePage(filiere: filiere),
                  ),
                );
              },
            );
          },
        ),
      ),
    );
  }
}