import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';

import '../widgets/encabezado_pais.dart';

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

  @override
  State<MemoriasIndex> createState() => _MemoriasIndexState();
}

class _MemoriasIndexState extends State<MemoriasIndex> {
  late List<String> _memoriasTitles;
  late List<String> _memoriasImg;
  late List<String> _memoriasRutas;

  bool _isLoading  = true;
  String _pais = "";
  String _code = "";
  String _nombreCompleto = "";

  final db = Localstore.instance;

  @override
  void initState() {
    super.initState();
    _memoriasTitles = [
      "MEMORIA DE CÁLCULO VENTILACIÓN LOCALIZADA",
      "MEMORIA DE CÁLCULO VENTILACIÓN ESTACIONAMIENTOS",
      "MEMORIA DE CÁLCULO VENTILACIÓN AMBIENTAL",
      "MEMORIA DE CÁLCULO ATENUADORES ACUSTICOS"
    ];

    _memoriasImg = [
      "campana.png",
      "estacionamientos.png",
      "1.png",
      '5.png'
    ];

    _memoriasRutas = [
      "ventilacionLocalizada",
      "ventilacionEstacionamientos",
      "ventilacionAmbiental",
      "atenuadoresAcusticos"
    ];

    _getInfo().then((value){
      if(mounted){
        _isLoading = false;
      }
    });
  }

  Future<void> _getInfo() async{
    final items = await db.collection('login').get();
    final lastID = items?.keys.last;
    final data = items?[lastID];

    _pais = data['pais'];
    _nombreCompleto = data['nombre'];

    final paisArr = data['pais'].split(" ");
    _code = paisArr.last.replaceAll("(", "").replaceAll(")", "");
    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : SafeArea(
        child: LayoutBuilder(
          builder: (context, constraints) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: const EdgeInsets.fromLTRB(32.0, 0.0, 16.0, 0.0),
                  padding: const EdgeInsets.fromLTRB(0.0, 8.0, 0.0, 0.0),
                  width: double.infinity,
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          "Portal de memorias de cálculo",
                          style: GoogleFonts.roboto(
                            fontSize: 16.0,
                            color: Colors.black54,
                            fontWeight: FontWeight.bold,
                            fontStyle: FontStyle.italic,
                          ),
                        ),
                      ),
                      const SizedBox(width: 8.0),
                      IconButton(
                        icon: const Icon(Icons.logout, color: Color(0xFFB40404)),
                        onPressed: () => Navigator.pop(context, 'logout'),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 8.0),
                EncabezadoPais(
                  paisCode: _code,
                  paisName: _pais,
                ),
                const SizedBox(
                  height: 32.0,
                ),
                Image.asset(
                  "assets/matriz.png",
                  width: 88.0,
                  fit: BoxFit.cover,
                ),
                const SizedBox(
                  height: 16.0,
                ),
                Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 32.0),
                  child: const Text(
                    "PORTAL DE MEMORIAS DE CÁLCULO",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      fontFamily: "Helvetica Neue Black Cond",
                      fontSize: 28.0,
                    ),
                  ),
                ),
                const SizedBox(
                  height: 8.0,
                ),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 32.0),
                  width: double.infinity,
                  child: Text(
                    "Bienvenido $_nombreCompleto, selecciona la memoria de cálculo a la que deseas acceder:",
                    textAlign: TextAlign.center,
                    style: const TextStyle(
                      fontFamily: "Helvetica Neue Light",
                      fontSize: 22.0,
                      fontWeight: FontWeight.w600,
                      color: Color.fromRGBO(104, 104, 104, 1),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 32.0,
                ),
                Expanded(
                  child: GridView.builder(
                    itemCount: _memoriasTitles.length,
                    gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2,
                    ),
                    itemBuilder: (context, index){
                      return Card(
                        elevation: 16,
                        shape: const BeveledRectangleBorder(
                          borderRadius: BorderRadius.zero,
                        ),
                        margin: const EdgeInsets.fromLTRB(16.0, 8.0, 16.0, 8.0),
                        child: TextButton(
                          style: TextButton.styleFrom(
                            minimumSize: const Size(0.0, 0.0),
                            padding: EdgeInsets.zero,
                            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          ),
                          child: GridTile(
                            child: Container(
                              margin: const EdgeInsets.only(
                                top: 16.0,
                                bottom: 80.0,
                              ),
                              child: Image.asset(
                                'assets/${_memoriasImg[index]}',
                              ),
                            ),
                            footer: Container(
                              width: double.infinity,
                              decoration: const BoxDecoration(
                                border: Border(
                                  bottom: BorderSide(
                                    width: 8.0,
                                    color: Color(0xFFFF0000),
                                  ),
                                ),
                              ),
                              child: Text(
                                _memoriasTitles[index],
                                textAlign: TextAlign.center,
                                style: GoogleFonts.roboto(
                                  fontSize: 14.0,
                                  color: Colors.black,
                                ),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),
                              padding: const EdgeInsets.fromLTRB(16, 32, 16, 16),
                            ),
                          ),
                          onPressed: () => Navigator.pushNamed(context, _memoriasRutas[index]),
                        ),
                      );
                    },
                  ),
                ),
              ],
            );
          },
        ),
      ),
    );
  }
}
