import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/quiosco/models/db_archivos_model.dart';
import 'package:quiosco_soler_2/quiosco/models/db_secciones_model.dart';
import 'package:quiosco_soler_2/quiosco/widgets/gridview_files.dart';
import 'package:quiosco_soler_2/quiosco/widgets/gridview_sections.dart';
import 'package:quiosco_soler_2/quiosco/widgets/lateral_menu.dart';
import 'package:quiosco_soler_2/src/providers/db_provider.dart';

class SectionsPage extends StatefulWidget {
  const SectionsPage({Key? key}) : super(key: key);

  @override
  State<SectionsPage> createState() => _SectionsPageState();
}

class _SectionsPageState extends State<SectionsPage> {
  final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
  final List<DbSecciones> _secc = [];
  final List<DbArchivos> _arch = [];
  final _db = Localstore.instance;

  dynamic _dbInfo;

  bool _isLoading = true;
  bool _sectionOrFile = true;

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

  void init() async{
    final items = await _db.collection('quiosco').get();
    final keys = items!.keys;
    final key = keys.last;

    final info = items[key];

    final sections = await DBProvider.db.getSections(info['ides']);
    sections.forEach((element) => _secc.add(element));

    final files = await DBProvider.db.getFiles(info['ides'], 0, 0);
    files.forEach((element) => _arch.add(element));

    _dbInfo = info;

    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldKey,
      drawer: LateralMenu(page: const [0,1,0,0,0], level: 'est', onOptionSelected: _optionHandler),
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Row(
          children: [
            Image.asset(
              'assets/logo.png',
              width: 32.0,
            ),
            const SizedBox(width: 8.0),
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                minimumSize: const Size(0, 0)
              ),
              child: const Icon(
                Icons.menu,
                color: Color(0xFFFF0000),
              ),
              onPressed: () => _scaffoldKey.currentState!.openDrawer(),
            ),
            const Expanded(
              child: Text(
                'QUIOSCO',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.red,
                  fontFamily: 'Helvetica Neue Black Cond',
                ),
              ),
            ),
            TextButton(
              style: TextButton.styleFrom(
                  padding: EdgeInsets.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minimumSize: const Size(0, 0)
              ),
              child: const Icon(
                Icons.menu,
                color: Colors.transparent,
              ),
              onPressed: null,
            ),
            const SizedBox(width: 16.0),
            TextButton(
              style: TextButton.styleFrom(
                  padding: EdgeInsets.zero,
                  tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                  minimumSize: const Size(0, 0)
              ),
              child: const Icon(
                Icons.menu,
                color: Colors.transparent,
              ),
              onPressed: null,
            ),
          ],
        ),
      ),
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : Column(
          children: [
            Container(
              height: 44.0,
              color: Colors.grey,
              padding: const EdgeInsets.symmetric(horizontal: 8.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      minimumSize: const Size(0, 0),
                    ),
                    child: const Icon(
                      Icons.arrow_back,
                      color: Colors.white,
                    ),
                    onPressed: () => Navigator.pop(context),
                  ),
                  Expanded(
                    child: Text(
                      'BIENVENIDO: ${_dbInfo['user']}',
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                        fontSize: 14.0,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  TextButton(
                    style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      minimumSize: const Size(0, 0),
                    ),
                    child: const Icon(
                      Icons.home,
                      color: Colors.white,
                    ),
                    onPressed: () => Navigator.pop(context, 'home'),
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 8.0),
              width: _screenSize.width,
              child: RichText(
                textAlign: TextAlign.center,
                text: TextSpan(
                  style: GoogleFonts.roboto(
                    fontWeight: FontWeight.bold,
                    fontSize: 18.0,
                  ),
                  children: [
                    TextSpan(
                      text: 'SECCIONES EN ',
                      style: GoogleFonts.roboto(
                        color: Colors.black,
                      ),
                    ),
                    TextSpan(
                      text: '${_dbInfo['esta'].toUpperCase()}',
                      style: GoogleFonts.roboto(
                        color: Colors.red,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 8.0, bottom: 16.0),
              alignment: Alignment.center,
              height: 4.0,
              width: 28.0,
              decoration: BoxDecoration(
                color: Colors.red,
                borderRadius: BorderRadius.circular(8.0),
              ),
            ),
            Expanded(
              child: _sectionOrFile ? SizedBox(
                child: _secc.isNotEmpty ? GridViewSections(
                  elements: _secc,
                  ides: _dbInfo['ides'],
                ) : Text(
                  'No se encontraron secciones para este estante.',
                  style: GoogleFonts.roboto(
                    fontWeight: FontWeight.w300,
                    fontSize: 16.0,
                  ),
                ),
              ) : SizedBox(
                child: _arch.isNotEmpty ? GridViewArchivos(
                  elements: _arch,
                ) : Center(
                  child: Image.asset(
                    'assets/no_files.png',
                    width: _screenSize.width * 0.75,
                  ),
                ),
              ),
            ),
            SizedBox(
              width: _screenSize.width,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Expanded(
                    child: Container(
                      decoration: const BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            color: Colors.black54,
                            width: 0.5,
                          ),
                        ),
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(bottom: 4.0),
                    decoration: BoxDecoration(
                      border: Border(
                        top: _sectionOrFile ? const BorderSide(color: Colors.transparent, width: 0) : const BorderSide(color: Colors.black54, width: 0.5),
                        left: _sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                        right: _sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                        bottom: _sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                      )
                    ),
                    child: TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(8.0),
                        minimumSize: const Size(0, 0),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      onPressed: () => setState(() {
                        if(!_sectionOrFile) _sectionOrFile = true;
                      }),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            'Secciones',
                            style: GoogleFonts.roboto(
                              fontSize: 14.0,
                              color: _sectionOrFile ? const Color(0xFFFF0000) : Colors.black,
                            ),
                          ),
                          const SizedBox(width: 4.0),
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 4.0),
                            decoration: BoxDecoration(
                              color: const Color(0xFFFF0000),
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            child: Text(
                              '${_secc.length}',
                              style: GoogleFonts.roboto(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 14.0,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Container(
                    margin: const EdgeInsets.only(bottom: 4.0),
                    decoration: BoxDecoration(
                        border: Border(
                          top: !_sectionOrFile ? const BorderSide(color: Colors.transparent, width: 0) : const BorderSide(color: Colors.black54, width: 0.5),
                          left: !_sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                          right: !_sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                          bottom: !_sectionOrFile ? const BorderSide(color: Colors.black54, width: 0.5) : const BorderSide(color: Colors.transparent, width: 0),
                        )
                    ),
                    child: TextButton(
                      style: TextButton.styleFrom(
                        padding: const EdgeInsets.all(8.0),
                        minimumSize: const Size(0, 0),
                        tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                      ),
                      onPressed: () => setState(() {
                        if(_sectionOrFile) _sectionOrFile = false;
                      }),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Text(
                            'Archivos',
                            style: GoogleFonts.roboto(
                              fontSize: 14.0,
                              color: !_sectionOrFile ? const Color(0xFFFF0000) : Colors.black,
                            ),
                          ),
                          const SizedBox(width: 4.0),
                          Container(
                            padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 4.0),
                            decoration: BoxDecoration(
                              color: const Color(0xFFFF0000),
                              borderRadius: BorderRadius.circular(8.0),
                            ),
                            child: Text(
                              '${_arch.length}',
                              style: GoogleFonts.roboto(
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                                fontSize: 14.0,
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  Expanded(
                    child: Container(
                      decoration: const BoxDecoration(
                        border: Border(
                          top: BorderSide(
                            color: Colors.black54,
                            width: 0.5,
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void _optionHandler(String a, String? b){
    if(a == 'pop'){
      if(b == 'home'){
        Navigator.pop(context);
        Navigator.pop(context, b);
      }
    }
  }
}
