import 'package:flutter/material.dart';
import 'package:school_management_system/api/results_requests.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<bool> _checkToken;
late Future<Student> _returnData;
late Map<String, List<String>>? sessiondetails;
late Student apiData;
Future<Result>? _returnresult;
late List<Score> studentScores;

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

  @override
  State<ResultsScreen> createState() => _ResultsScreenState();
}

class _ResultsScreenState extends State<ResultsScreen> {
  String? _selectedKey;
  String? _selectedItem;
  Result? resultList;

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

  @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!;
          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(() {
                        _returnresult = getStudentResult(_selectedKey!, value);
                        // resultList = null;
                      });
                    },
                  );
                }).toList(),
              )
            : Container()
      ],
    );
  }

  FutureBuilder dataTableMenu() {
    resultList = null;
    return FutureBuilder<Result>(
      future: _returnresult,
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          resultList = snapshot.data!;
          studentScores = resultList!.scores!;
        } else if (snapshot.hasError) {
          resultList = snapshot.data;
        } else {
          resultList = null;
        }
        return SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: resultList != null
              ? Column(
                  children: [
                    DataTable(
                        columns: const [
                          //DataColumn(label: Text('Module Code')),
                          DataColumn(label: Text('Module Title')),
                          DataColumn(label: Text('Score'), numeric: true),
                          DataColumn(label: Text('Grade')),
                        ],
                        rows: resultList!.scores!.map((value) {
                          return DataRow(cells: [
                            // DataCell(Text(value.module!)),
                            DataCell(Text(value.module!)),
                            DataCell(Text(value.score!.toString())),
                            DataCell(Text(studentGrade(value.score!))),
                          ]);
                        }).toList()),
                  ],
                )
              : const Center(
                  child: Text(
                    'Nothing to Display',
                    style: TextStyle(fontWeight: FontWeight.w800),
                  ),
                ),
        );
      },
    );
  }
}
