import 'package:flutter/material.dart';
import 'package:nfc_google_sheet/components/folder.dart';
import 'package:nfc_google_sheet/context/app_colors.dart';
import 'package:nfc_google_sheet/pages/subject_page.dart';
import 'package:nfc_google_sheet/pages/sheet_page.dart';
import 'package:nfc_google_sheet/services/program_service.dart';
import 'package:nfc_google_sheet/utils/icon_utils.dart';

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

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

class _ProgramPageState extends State<ProgramPage> {
  List<Map<String, dynamic>> _programs = [];

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

  Future<void> _loadPrograms() async {
    final programs = await ProgramService.instance.getPrograms();
    setState(() {
      _programs = programs;
    });
  }

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