import 'package:flutter/material.dart';
import 'package:school_management_system/api/student_requests.dart';
import 'package:school_management_system/components/default_values.dart';
import 'package:school_management_system/screens/welcome/welcome_screen.dart';

late Future<Student> _returnData;
late Student apiData;
late Map<String, List<String>>? sessiondetails;
late Map<String, List<ModuleDetail>> moduleDetail;
late Future<bool> _checkToken;

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

  @override
  State<ModulesScreen> createState() => _ModulesScreenState();
}

class _ModulesScreenState extends State<ModulesScreen> {
  String? _selectedKey;
  String? _selectedItem;
  List<ModuleDetail>? indivModule;

  @override
  void initState() {
    _checkToken = checkTokenValidity();
    super.initState();
    _returnData = getStudentDetail(loginId);
  }

  @override
  Widget build(BuildContext context) {
    _checkToken.then(
      (value) {
        if (!value) {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) {
                return const WelcomeScreen();
              },
            ),
          );
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('Session Time Out / Sign Back In'),
            ),
          );
        }
      },
    );

    return FutureBuilder<Student>(
      future: _returnData,
      builder: (context, snapshot) {
        List<Widget> children;
        if (snapshot.hasData) {
          apiData = snapshot.data!;
          moduleDetail = apiData.moduledetails!;
          sessiondetails = apiData.sessiondetails!;
          children = [
            const SizedBox(height: 20),
            dropDownMenu(),
            const SizedBox(height: 50),
            dataTableMenu(),
          ];
        } else if (snapshot.hasError) {
          children = [
            const Icon(
              Icons.error_outline,
              color: Colors.red,
              size: 60,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 16),
              child: Text('Error: ${snapshot.error}'),
            ),
          ];
        } else {
          children = const [
            SizedBox(
              width: 60,
              height: 60,
              child: CircularProgressIndicator(),
            ),
            Padding(
              padding: EdgeInsets.only(top: 16),
              child: Text('Loading Data...'),
            ),
          ];
        }

        return Container(
          color: Colors.white,
          child: Padding(
            padding: const EdgeInsets.only(left: 20, right: 20),
            child: ListView(
              scrollDirection: Axis.vertical,
              children: children,
            ),
          ),
        );
      },
    );
  }

  Row dropDownMenu() {
    return Row(
      children: [
        DropdownButton(
          value: _selectedKey,
          icon: const Icon(Icons.arrow_drop_down),
          iconSize: 30,
          elevation: 16,
          style: const TextStyle(fontSize: 20, color: Colors.black),
          underline: Container(
            height: 2,
            color: Colors.grey,
          ),
          onChanged: (newValue) {
            setState(() {
              _selectedKey = newValue;
              _selectedItem = null;
            });
          },
          items: sessiondetails?.keys.map((String value) {
            return DropdownMenuItem(
              value: value,
              child: Text(value),
            );
          }).toList(),
        ),
        const SizedBox(width: 30),
        _selectedKey != null
            ? DropdownButton(
                value: _selectedItem,
                icon: const Icon(Icons.arrow_drop_down),
                iconSize: 30,
                elevation: 16,
                style: const TextStyle(fontSize: 20, color: Colors.black),
                underline: Container(
                  height: 2,
                  color: Colors.grey,
                ),
                onChanged: (newValue) {
                  setState(() {
                    _selectedItem = newValue;
                  });
                },
                items: sessiondetails![_selectedKey]!.map((String value) {
                  return DropdownMenuItem(
                    value: value,
                    child: Text(value),
                    onTap: () {
                      setState(() {
                        indivModule = moduleDetail["$_selectedKey~$value"];
                      });
                    },
                  );
                }).toList(),
              )
            : Container()
      ],
    );
  }

  SingleChildScrollView dataTableMenu() {
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      child: indivModule != null
          ? Column(
              children: indivModule!.map((value) {
                return Card(
                  elevation: 20,
                  color: const Color.fromARGB(255, 224, 208, 159),
                  child: InkWell(
                    onTap: () {
                      
                    },
                    splashColor: primaryLightColor,
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Image.asset(
                          getImage(),
                          width: 120,
                          height: 120,
                          fit: BoxFit.cover,
                        ),
                        const SizedBox(width: 10),
                        Padding(
                          padding: const EdgeInsets.only(left: 5, top: 5),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                value.modulecode!,
                                style: const TextStyle(
                                  fontWeight: FontWeight.w800,
                                ),
                              ),
                              Text(value.modulename!),
                              const Column(
                                children: [
                                  Text('CLOSE'),
                                ],
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            )
          : const Center(
              child: Text(
                'Nothing to Display',
                style: TextStyle(fontWeight: FontWeight.w800),
              ),
            ),
    );
  }
}
