import 'dart:io';
import 'package:http/http.dart' as http;

import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_html/style.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:quiosco_soler/productos/providers/archivos_provider.dart';
import 'package:quiosco_soler/productos/providers/producto_provider.dart';
import 'package:quiosco_soler/src/pages/pdf_viewer.dart';

class DetallesProducto extends StatefulWidget {
  final String linea;
  final String modelo;
  final String submodelo;

  const DetallesProducto({required this.linea, required this.modelo, required this.submodelo});

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

class _DetallesProductoState extends State<DetallesProducto> {
  final _productoProvider = ProductoProvider();
  final _archivosProvider = ArchivosProvider();
  late String _linea;
  late String _modelo;
  late String _submodelo;
  Widget _child = const Center(
    child: CircularProgressIndicator(),
  );
  final List<TableRow> _hilerasTabla = [];
  bool _existeFicha = false;

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

  Future<void> launchWithPermission(String document) async {
    final status = await Permission.storage.status;
    if (status != PermissionStatus.granted) {
      final result = await Permission.storage.request();
      if (result == PermissionStatus.granted) {
        showViewer(document);
      }
    } else {
      showViewer(document);
    }
  }

  void showViewer(String document) {
    Navigator.of(context).push(MaterialPageRoute(
      builder: (context) => PDFViewer(
        localFile: false,
        url: document,
      ),
    ));
  }

  bool granted(PermissionStatus status) {
    return status == PermissionStatus.granted;
  }

  Future<void> _changeChild(BuildContext context, String linea, String modelo, String submodelo) async{
    final producto = await _productoProvider.fetchSubmodelos(linea, modelo, submodelo);
    final archivos = await _archivosProvider.fetchArchivos(submodelo);
    String fichaTecnica = '';

    _hilerasTabla.add(TableRow(
        children: [
          Text(
            'VERSIONES',
            style: GoogleFonts.roboto(
                color: const Color.fromRGBO(51, 51, 51, 1),
                fontWeight: FontWeight.bold
            ),
            textAlign: TextAlign.center,
          ),
          Text(
            'ZIP',
            style: GoogleFonts.roboto(
                color: const Color.fromRGBO(51, 51, 51, 1),
                fontWeight: FontWeight.bold
            ),
            textAlign: TextAlign.center,
          ),
          Text(
            'OTROS FORMATOS',
            style: GoogleFonts.roboto(
              color: const Color.fromRGBO(51, 51, 51, 1),
              fontWeight: FontWeight.bold,
            ),
            textAlign: TextAlign.center,
          ),
        ]
    ));

    if(archivos.result.isNotEmpty){
      int i = 0;
      do{
        if(archivos.result[i].archFich != null){
          fichaTecnica = archivos.result[i].archFich;
        }

        if(archivos.result[i].archCad != null || archivos.result[i].archOtr != null || archivos.result[i].archZip != null){
          _hilerasTabla.add(TableRow(
              children: [
                Container(
                  child: Text(
                    archivos.result[i].modelo,
                    style: GoogleFonts.roboto(
                      color: Color.fromRGBO(102, 102, 102, 1),
                      fontWeight: FontWeight.bold,
                    ),
                    textAlign: TextAlign.center,
                  ),
                  padding: EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                ),
                if(archivos.result[i].archZip != null)
                  IconButton(
                    icon: Icon(Icons.insert_drive_file, color: Color.fromRGBO(255, 92, 100, 1)),
                    onPressed: (){
                      print(archivos.result[i].archZip);
                    },
                  ),
                if(archivos.result[i].archZip == null)
                  Container(),
                if(archivos.result[i].archOtr != null)
                  IconButton(
                    icon: Icon(Icons.insert_drive_file, color: Color.fromRGBO(255, 92, 100, 1)),
                    onPressed: (){
                      print(archivos.result[i].archOtr);
                    },
                  ),
                if(archivos.result[i].archOtr == null)
                  Container(),
              ]
          ));
        }
        i++;
      }while(i < archivos.result.length);
    }else{
      fichaTecnica = "sin-ficha";
    }

    fichaTecnica = 'https://www.solerpalau.mx/' + fichaTecnica;
    fichaTecnica = fichaTecnica.replaceAll(' ', '%20');
    print(fichaTecnica);

    final verificarFicha = await http.get(Uri.parse(fichaTecnica));
    _existeFicha = verificarFicha.statusCode == 200;
    print("===Existe ficha: $_existeFicha===");

    final _screenSize = MediaQuery.of(context).size;

    setState(() {
      if(producto.response){
        _child = Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: double.infinity,
              alignment: Alignment.center,
              child: Stack(
                children: <Widget>[
                  Image(
                    width: double.infinity,
                    image: linea == 'Hábitat' ? AssetImage('assets/habitat_header.jpg')
                        : linea == 'Comercial' ? AssetImage('assets/comercial_header.jpg')
                        : linea == 'Industrial' ? AssetImage('assets/industrial_header.jpg')
                        : AssetImage('assets/OEM_header.jpg'),
                    fit: BoxFit.cover,
                  ),
                  Positioned(
                    top: 24.0,
                    left: 28.0,
                    child: Text(
                      'Producto',
                      style: GoogleFonts.roboto(
                          fontSize: 10.0,
                          color: Colors.white,
                          fontWeight: FontWeight.w300,
                          shadows: <Shadow>[
                            Shadow(
                                offset: Offset(1.0, 1.0),
                                blurRadius: 3.0,
                                color: Colors.black87
                            )
                          ]
                      ),
                    ),
                  ),
                  Positioned(
                    top: 32.0,
                    left: 28.0,
                    child: Container(
                      width: _screenSize.width-56.0,
                      child: Text(
                        'Inicio > $_linea > $_modelo > $_submodelo',
                        style: GoogleFonts.robotoSlab(
                            fontSize: 18.0,
                            color: Colors.white,
                            shadows: <Shadow>[
                              Shadow(
                                  offset: Offset(1.0, 1.0),
                                  blurRadius: 3.0,
                                  color: Colors.black87
                              )
                            ]
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            SizedBox(height: 16.0),
            Image.asset(
              "assets/error.png",
              width: 64.0,
              height: 64.0,
            ),
            Container(
              margin: EdgeInsets.all(16.0),
              width: _screenSize.width,
              child: Text(
                  "Ocurrió el siguiente error:",
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                      color: Colors.black87
                  )
              ),
            ),
            Container(
              width: _screenSize.width,
              child: Text(
                producto.message,
                textAlign: TextAlign.center,
                style: GoogleFonts.roboto(
                    fontSize: 14.0,
                    fontStyle: FontStyle.italic,
                    color: Colors.black54
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.all(16.0),
              width: _screenSize.width,
              child: Text(
                  "Por favor contacta al departamento de TI de S&P México.",
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                      fontWeight: FontWeight.bold,
                      fontSize: 16.0,
                      color: Colors.black87
                  )
              ),
            ),
          ],
        );
      }else{
        _child = SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                width: double.infinity,
                alignment: Alignment.center,
                child: Stack(
                  children: <Widget>[
                    Image(
                      width: double.infinity,
                      image: linea == 'Hábitat' ? AssetImage('assets/habitat_header.jpg')
                          : linea == 'Comercial' ? AssetImage('assets/comercial_header.jpg')
                          : linea == 'Industrial' ? AssetImage('assets/industrial_header.jpg')
                          : AssetImage('assets/OEM_header.jpg'),
                      fit: BoxFit.cover,
                    ),
                    Positioned(
                      top: 24.0,
                      left: 28.0,
                      child: Text(
                        'Producto',
                        style: GoogleFonts.roboto(
                            fontSize: 10.0,
                            color: Colors.white,
                            fontWeight: FontWeight.w300,
                            shadows: <Shadow>[
                              Shadow(
                                  offset: Offset(1.0, 1.0),
                                  blurRadius: 3.0,
                                  color: Colors.black87
                              )
                            ]
                        ),
                      ),
                    ),
                    Positioned(
                      top: 32.0,
                      left: 28.0,
                      child: Container(
                        width: _screenSize.width-56.0,
                        child: Text(
                          'Inicio > $_linea > $_modelo > $_submodelo',
                          style: GoogleFonts.robotoSlab(
                              fontSize: 18.0,
                              color: Colors.white,
                              shadows: <Shadow>[
                                Shadow(
                                    offset: Offset(1.0, 1.0),
                                    blurRadius: 3.0,
                                    color: Colors.black87
                                )
                              ]
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 8.0),
              Container(
                width: _screenSize.width,
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: Text(
                  modelo,
                  textAlign: TextAlign.center,
                  style: GoogleFonts.robotoSlab(
                      color: Colors.black54,
                      fontSize: 22.0
                  ),
                ),
              ),
              Container(
                width: _screenSize.width,
                padding: EdgeInsets.symmetric(horizontal: 8.0),
                child: Text(
                  'Serie $submodelo',
                  textAlign: TextAlign.center,
                  style: GoogleFonts.robotoSlab(
                      color: Colors.black54,
                      fontSize: 32.0,
                      fontWeight: FontWeight.bold
                  ),
                ),
              ),
              FadeInImage(
                placeholder: AssetImage('assets/progressbar.gif'),
                image: NetworkImage('https://www.solerpalau.mx/ALP/${producto.result.id}.jpg'),
                width: _screenSize.width*0.5,
                fit: BoxFit.cover,
              ),
              SizedBox(height: 16.0),
              Container(
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            color: Color.fromRGBO(75, 75, 75, 1),
                            width: 3.0
                        )
                    )
                ),
                width: _screenSize.width*0.5,
                padding: EdgeInsets.only(bottom: 16.0),
                child: Text(
                  'DESCRIPCIÓN',
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                      fontWeight: FontWeight.w300,
                      fontSize: 22.0
                  ),
                ),
              ),
              SizedBox(height: 8.0),
              Container(
                decoration: BoxDecoration(
                    border: Border.all(
                        color: Color.fromRGBO(204, 204, 204, 1),
                        width: 1.0
                    )
                ),
                width: _screenSize.width*0.95,
                padding: EdgeInsets.all(16.0),
                child: Html(
                  data: """<p>${producto.result.descripcion}</p>""",
                  style: {
                    "p" : Style(
                        fontSize: FontSize(18.0),
                        color: Color.fromRGBO(102, 102, 102, 1)
                    )
                  },
                ),
              ),
              SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: fichaTecnica.isEmpty || !_existeFicha ? null : (){
                  if (Platform.isIOS) {
                    // Open the document for iOS, no need for permission
                    showViewer(fichaTecnica);
                  } else {
                    // Request for permissions for android before opening document
                    launchWithPermission(fichaTecnica);
                  }
                },
                style: ElevatedButton.styleFrom(
                  textStyle: TextStyle(
                      color: Colors.white
                  ),
                  primary: Color.fromRGBO(100, 149, 237, 1),
                  padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 8.0),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.mail,
                      color: Colors.white,
                      size: 32.0,
                    ),
                    SizedBox(width: 8.0),
                    Text(
                      'FICHA TÉCNICA',
                      style: GoogleFonts.roboto(
                          color: Colors.white,
                          fontSize: 24.0,
                          fontWeight: FontWeight.w300
                      ),
                    )
                  ],
                ),
              ),
              SizedBox(height: 32.0)
            ],
          ),
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if(_linea == null && _modelo == null && _submodelo == null){
      _linea = widget.linea;
      _modelo = widget.modelo;
      _submodelo = widget.submodelo;

      _changeChild(context, _linea, _modelo, _submodelo);
    }
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: _child,
      ),
    );
  }
}
