import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:memorias_calculo_web/src/widgets/encabezado_pais.dart';

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

  @override
  State<IndexPage> createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  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"
    ];

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

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

    _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(),
      ) : LayoutBuilder(
        builder: (context, constraints) {
          final parentHeight = constraints.maxHeight;
          final parentWidth = constraints.maxWidth;

          double containerHeight = parentHeight;
          double containerWidth = parentWidth > 1440
              ? parentWidth*0.5 : parentWidth > 1280 && parentWidth <= 1440
              ? parentWidth*0.6 : parentWidth > 1080 && parentWidth <= 1280
              ? parentWidth*0.75 : parentWidth > 900 && parentWidth <= 1080
              ? parentWidth*0.8 : parentWidth > 720 && parentWidth <= 900
              ? parentWidth*0.85 : parentWidth > 540 && parentWidth <= 720
              ? parentWidth*0.9 : parentWidth;
          double containerMargin = (parentWidth - containerWidth) / 2;

          return Container(
            height: containerHeight,
            width: containerWidth,
            margin: EdgeInsets.symmetric(horizontal: containerMargin),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  margin: const EdgeInsets.symmetric(horizontal: 32.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),
                      TextButton(
                        style: TextButton.styleFrom(
                          padding: EdgeInsets.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          minimumSize: const Size(0.0, 0.0),
                        ),
                        child: Row(
                          children: [
                            Text(
                              "Cerrar sesión",
                              style: GoogleFonts.roboto(),
                            ),
                            const SizedBox(width: 8.0),
                            const Icon(Icons.logout)
                          ],
                        ),
                        onPressed: () async{
                          Navigator.pop(context, 'logout');
                        },
                      )
                    ],
                  ),
                ),
                const SizedBox(height: 8.0),
                EncabezadoPais(
                  paisCode: _code,
                  paisName: _pais,
                ),
                const SizedBox(
                  height: 32.0,
                ),
                Image.asset(
                  "matriz.png",
                  width: 120.0,
                  fit: BoxFit.cover,
                ),
                const SizedBox(
                  height: 48.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: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: containerWidth > 720 ? 3 : 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(
                                _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: containerWidth > 720 ? 16.0 : 14.0,
                                  color: Colors.black,
                                ),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),
                              padding: const EdgeInsets.fromLTRB(16, 32, 16, 16),
                            ),
                          ),
                          onPressed: () => Navigator.pushNamed(context, _memoriasRutas[index]),
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
          );
        },
      ),
    );
  }
}
