import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:memorias_calculo/src/back/scoped_models/user_info_model.dart';
import 'package:memorias_calculo/src/front/pages/calculadora_ambiental_page.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:http/http.dart' as http;
import 'dart:html' as html;

class VentilacionAmbientalPage extends StatefulWidget {
  final Object info;
  final bool errorConexion;

  const VentilacionAmbientalPage({
    Key? key,
    required this.info, required this.errorConexion
  }) : super(key: key);

  @override
  _VentilacionAmbientalPageState createState() => _VentilacionAmbientalPageState();
}

class _VentilacionAmbientalPageState extends State<VentilacionAmbientalPage> {
  final List<Map<String, String>> _projects = [];
  final Map<String, String> _estatusCodigos = {
    "C" : "Cálculo de caudal y equipos",
    "F" : "Finalizado"
  };

  @override
  Widget build(BuildContext context) {
    return ScopedModelDescendant<UserInfoModel>(
      builder: (context, child, model){
        return Scaffold(
          body: 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.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const SizedBox(height: 8.0),
                    Container(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 32.0,
                      ),
                      child: Row(
                        children: [
                          TextButton(
                            child: Text(
                              "Portal de memorias de cálculo >",
                              style: GoogleFonts.roboto(
                                fontSize: 16.0,
                                fontWeight: FontWeight.bold,
                                fontStyle: FontStyle.italic,
                              ),
                            ),
                            onPressed: () => Navigator.pop(context),
                            style: TextButton.styleFrom(
                              padding: const EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0),
                              minimumSize: const Size(0.0, 0.0),
                              tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            ),
                          ),
                          const SizedBox(width: 8.0),
                          Expanded(
                            child: Container(
                              padding: const EdgeInsets.fromLTRB(0.0, 0.0, 8.0, 0.0),
                              child: Text(
                                "Memoria de cálculo de ventilación ambiental",
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: GoogleFonts.roboto(
                                  fontSize: 16.0,
                                  color: Colors.black54,
                                  fontWeight: FontWeight.bold,
                                  fontStyle: FontStyle.italic,
                                ),
                              ),
                            ),
                          )
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 8.0,
                    ),
                    Row(
                      children: [
                        const SizedBox(width: 32.0),
                        Image.asset(
                          "logo.png",
                          width: 64.0,
                        ),
                        Expanded(
                            child: Container(
                              padding: const EdgeInsets.fromLTRB(208.0, 0.0, 16.0, 0.0),
                              child: Text(
                                "S&P MX  ${"MX".replaceAllMapped(RegExp(r'[A-Z]'), (match) => String.fromCharCode(match.group(0)!.codeUnitAt(0) + 127397))}",
                                textAlign: TextAlign.center,
                                style: const TextStyle(
                                  fontFamily: "Helvetica Neue Black Cond",
                                  fontSize: 20.0,
                                ),
                              ),
                            )
                        ),
                        Image.asset(
                          "logo_completo.png",
                          width: 256.0,
                        ),
                        const SizedBox(width: 32.0),
                      ],
                    ),
                    const SizedBox(
                      height: 32.0,
                    ),
                    Image.asset(
                      "1.png",
                      width: 120.0,
                    ),
                    const SizedBox(
                      height: 48.0,
                    ),
                    Container(
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(
                        horizontal: 32.0,
                      ),
                      child: const Text(
                        "MEMORIA DE CÁLCULO VENTILACIÓN AMBIENTAL",
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: "Helvetica Neue Black Cond",
                          fontSize: 28.0,
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 16.0,
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(
                          horizontal: 32.0
                      ),
                      child: Text(
                        "NUEVO PROYECTO",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.robotoSlab(
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 16.0,
                    ),
                    Container(
                      width: double.infinity,
                      margin: const EdgeInsets.symmetric(horizontal: 32.0),
                      padding: const EdgeInsets.all(32.0),
                      color: const Color(0x0F000000),
                      child: Row(
                        children: [
                          Expanded(
                            child: ElevatedButton(
                              style: ElevatedButton.styleFrom(
                                primary: Colors.white,
                                onPrimary: const Color.fromRGBO(180, 4, 4, 0.25),
                                padding: const EdgeInsets.all(16.0),
                              ),
                              child: Column(
                                children: [
                                  Image.asset(
                                    "nuevo2.png",
                                    width: 64.0,
                                  ),
                                  const SizedBox(height: 8.0),
                                  Text(
                                    "Crear nuevo proyecto",
                                    style: GoogleFonts.roboto(
                                      fontWeight: FontWeight.bold,
                                      fontSize: 16.0,
                                      color: const Color(0xFFB40404),
                                    ),
                                  )
                                ],
                              ),
                              onPressed: widget.errorConexion ? () => Navigator.push(context, MaterialPageRoute(
                                builder: (context) => CalculadoraAmbientalPage(
                                  errorConexion: widget.errorConexion,
                                ),
                              )) : () async{
                                final controller = TextEditingController();
                                final shouldCreate = await showDialog(
                                  context: context,
                                  barrierDismissible: false,
                                  builder: (context) => AlertDialog(
                                    title: Text(
                                      "Nombre del proyecto",
                                      textAlign: TextAlign.center,
                                      style: GoogleFonts.roboto(
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    content: TextField(
                                      controller: controller,
                                      decoration: InputDecoration(
                                        hintStyle: GoogleFonts.roboto(
                                          color: Colors.grey,
                                          fontStyle: FontStyle.italic,
                                        ),
                                        hintText: "Ingresa el nombre del proyecto.",
                                      ),
                                      style: GoogleFonts.roboto(),
                                      maxLines: 1,
                                      maxLength: 100,
                                      onSubmitted: (val){
                                        if(val.isNotEmpty){
                                          Navigator.pop(context, true);
                                        }
                                      },
                                    ),
                                    actions: [
                                      TextButton(
                                        child: const Text(
                                          "Cancelar",
                                        ),
                                        onPressed: () => Navigator.pop(context, false),
                                      ),
                                      TextButton(
                                        child: const Text(
                                          "Aceptar",
                                        ),
                                        onPressed: (){
                                          if(controller.text.isNotEmpty){
                                            Navigator.pop(context, true);
                                          }else{
                                            Fluttertoast.showToast(
                                              msg: "El nombre no debe estar vacío.",
                                              toastLength: Toast.LENGTH_SHORT,
                                              timeInSecForIosWeb: 4,
                                              gravity: ToastGravity.CENTER,
                                              webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                            );
                                          }
                                        },
                                      )
                                    ],
                                  ),
                                );

                                /*if(shouldCreate){
                                  final url = Uri.https("smart.solerpalau.mx", "QA/api/v1/quiosco/matrizMemoriasCalculo/nuevoProyectoVentilacion");
                                  final res = await http.post(url,
                                    headers: {
                                      "Authorization": "Bearer ${model.accessToken}"
                                    },
                                    body: {
                                      "NOMBREPROYECTO": controller.text,
                                      "MEMORIA": "estacionamientos",
                                      "FCREACION": DateTime.now().toIso8601String().substring(0, 19),
                                      "FMODIF": DateTime.now().toIso8601String().substring(0, 19),
                                      "IDUSUARIO": model.idUsuario,
                                      "ESTATUS": "C"
                                    },
                                  );

                                  final decoded = jsonDecode(res.body);
                                  if(!decoded['response']){
                                    Fluttertoast.showToast(
                                      msg: decoded['message'],
                                      toastLength: Toast.LENGTH_SHORT,
                                      timeInSecForIosWeb: 4,
                                      gravity: ToastGravity.CENTER,
                                      webBgColor: "linear-gradient(to right, #b40404, #ff0000)",
                                    );
                                  }else{
                                    String idProyecto = decoded['result']['idProyecto'];
                                    await Navigator.push(context, MaterialPageRoute(
                                      builder: (context) => CalculadoraEstacionamientoPage(
                                        ciudad: model.ciudad,
                                        estado: model.estado,
                                        pais: model.pais,
                                      ),
                                    ));

                                    setState(() => _isLoading = true);

                                    _projects.clear();
                                    await _fetchProjects();

                                    setState(() => _isLoading = false);
                                  }
                                }*/
                              },
                            ),
                            flex: 1,
                          ),
                        ],
                      ),
                    ),
                    const SizedBox(
                      height: 16.0,
                    ),
                    Container(
                      margin: const EdgeInsets.symmetric(
                        horizontal: 32.0,
                      ),
                      child: Text(
                        "HISTORIAL DE PROYECTOS",
                        textAlign: TextAlign.center,
                        style: GoogleFonts.robotoSlab(
                          fontWeight: FontWeight.bold,
                          fontSize: 18.0,
                        ),
                      ),
                    ),
                    const SizedBox(
                      height: 16.0,
                    ),
                    if(_projects.isEmpty)
                      Container(
                        width: double.infinity,
                        margin: const EdgeInsets.symmetric(
                          horizontal: 32.0,
                        ),
                        child: Text(
                          "Aún no has creado ningún proyecto.",
                          style: GoogleFonts.roboto(
                            fontWeight: FontWeight.bold,
                            fontSize: 18.0,
                          ),
                        ),
                      ),
                    if(_projects.isNotEmpty)
                      Expanded(
                        child: Container(
                          width: double.infinity,
                          margin: const EdgeInsets.symmetric(
                            horizontal: 32.0,
                          ),
                          child: Column(
                            children: [
                              Container(
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: Row(
                                        children: [
                                          IconButton(
                                            icon: const Icon(
                                              Icons.filter_alt_outlined,
                                            ),
                                            onPressed: () => true,
                                          ),
                                          Text(
                                            "Nombre",
                                            style: GoogleFonts.roboto(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 18.0,
                                            ),
                                          )
                                        ],
                                      ),
                                      flex: 5,
                                    ),
                                    Expanded(
                                      child: Row(
                                        children: [
                                          IconButton(
                                            icon: const Icon(
                                              Icons.filter_alt_outlined,
                                            ),
                                            onPressed: () => true,
                                          ),
                                          Text(
                                            "Estatus",
                                            style: GoogleFonts.roboto(
                                              fontWeight: FontWeight.bold,
                                              fontSize: 18.0,
                                            ),
                                          )
                                        ],
                                      ),
                                      flex: 5,
                                    ),
                                    Expanded(
                                      child: Text(
                                        "Última Modificación",
                                        style: GoogleFonts.roboto(
                                          fontSize: 18.0,
                                          fontWeight: FontWeight.bold,
                                        ),
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                      flex: 3,
                                    ),
                                    Expanded(
                                      child: Container(),
                                      flex: 1,
                                    ),
                                  ],
                                ),
                                padding: const EdgeInsets.only(
                                  right: 16.0,
                                ),
                                decoration: const BoxDecoration(
                                  border: Border(
                                    bottom: BorderSide(
                                      color: Colors.black54,
                                      width: 2.0,
                                    ),
                                  ),
                                ),
                              ),
                              Expanded(
                                child: ListView.separated(
                                  itemCount: _projects.length,
                                  itemBuilder: (context, index){
                                    return ListTile(
                                      title: Row(
                                        children: [
                                          Expanded(
                                            child: Text(
                                              _projects[index]["nombreProyecto"]!,
                                              style: GoogleFonts.roboto(
                                                fontSize: 16.0,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            flex: 5,
                                          ),
                                          Expanded(
                                            child: Text(
                                              _estatusCodigos[_projects[index]["estatus"]!]!,
                                              style: GoogleFonts.roboto(
                                                fontSize: 16.0,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            flex: 5,
                                          ),
                                          Expanded(
                                            child: Text(
                                              _buildDate(_projects[index]["ulModificacion"]!),
                                              style: GoogleFonts.roboto(
                                                fontSize: 16.0,
                                              ),
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                            flex: 3,
                                          ),
                                          Expanded(
                                            child: PopupMenuButton<String>(
                                              onSelected: (val) async{
                                                const auth = "smart.solerpalau.mx";
                                                if(val == "Eliminar"){
                                                  /*final url = Uri.https(auth, "QA/api/v1/quiosco/matrizMemoriasCalculo/borrarProyectos");
                                                  final res = await http.post(url,
                                                    headers: {
                                                      "Authorization": "Bearer ${model.accessToken}"
                                                    },
                                                    body: {
                                                      "IDUSUARIO": model.idUsuario,
                                                      "IDPROYECTO": _projects[index]["idProyecto"]
                                                    },
                                                  );

                                                  final decoded = jsonDecode(res.body);
                                                  if(!decoded['response']){
                                                    Fluttertoast.showToast(
                                                        msg: decoded['message'],
                                                        toastLength: Toast.LENGTH_SHORT,
                                                        timeInSecForIosWeb: 4,
                                                        gravity: ToastGravity.CENTER,
                                                        webBgColor: "linear-gradient(to right, #b40404, #ff0000)"
                                                    );
                                                  }else{
                                                    Fluttertoast.showToast(
                                                        msg: decoded['message'],
                                                        toastLength: Toast.LENGTH_SHORT,
                                                        timeInSecForIosWeb: 4,
                                                        gravity: ToastGravity.CENTER,
                                                        webBgColor: "linear-gradient(to right, #266B1F, #98F58F)"
                                                    );

                                                    setState(() => _isLoading = true);

                                                    _projects.clear();
                                                    await _fetchProjects();

                                                    setState(() => _isLoading = false);
                                                  }*/
                                                }else if(val == "Descargar PDF"){
                                                  html.AnchorElement anchorElement = html.AnchorElement(href: _projects[index]["archpdf"]!);
                                                  anchorElement.download = _projects[index]["archpdf"]!;
                                                  anchorElement.target = "_blank";
                                                  anchorElement.click();
                                                }
                                              },
                                              itemBuilder: (context) => ["Eliminar", if(_projects[index]["archpdf"]!.isNotEmpty)"Descargar PDF"].map((e) => PopupMenuItem(
                                                value: e,
                                                child: Row(
                                                  children: [
                                                    Text(
                                                      e,
                                                      style: GoogleFonts.roboto(
                                                        fontSize: 16.0,
                                                        color: Colors.black54,
                                                      ),
                                                    ),
                                                    const SizedBox(width: 8.0),
                                                    Icon(
                                                      e == "Eliminar" ? Icons.delete : Icons.file_download,
                                                      color: Colors.black54,
                                                    )
                                                  ],
                                                ),
                                              )).toList(),
                                            ),
                                            flex: 1,
                                          ),
                                        ],
                                      ),
                                      onTap: () async {
                                        /*await Navigator.push(context, MaterialPageRoute(
                                            builder: (context) => CalculadoraEstacionamientoPage(
                                              ciudad: model.ciudad,
                                              estado: model.estado,
                                              pais: model.pais,
                                            )
                                        ));

                                        setState(() => _isLoading = true);

                                        _projects.clear();
                                        await _fetchProjects();

                                        setState(() => _isLoading = false);*/
                                      },
                                    );
                                  },
                                  separatorBuilder: (context, index){
                                    return const Divider();
                                  },
                                ),
                              )
                            ],
                          ),
                        ),
                      ),
                    const SizedBox(
                      height: 32.0,
                    ),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  String _buildDate(String date){
    final parsed = DateTime.parse(date);
    final now = DateTime.now();

    final diff = now.difference(parsed).inDays;
    if(diff == 0){
      return "Hoy";
    }else if(diff == 1){
      return "Ayer";
    }else if(diff >= 2 && diff < 31){
      return "Hace $diff días";
    }else if(diff >= 31 && diff <= 359){
      final diffMes = diff~/30;
      return "Hace $diffMes mes(es)";
    }else if(diff > 359){
      final diffAnio = diff~/359;
      return "Hace $diffAnio año(s)";
    }else{
      return "Hace mucho tiempo";
    }
  }
}
