import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:quiosco_soler_2/catalogo/models/archivos.dart';
import 'package:quiosco_soler_2/catalogo/models/producto.dart';

import '../../src/pages/pdf_viewer.dart';
import '../providers/archivos_provider.dart';
import '../providers/producto_provider.dart';

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

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

  const DetallesProducto({
    Key? key,
    required this.linea,
    required this.modelo,
    required this.submodelo,
  }) : super(key: key);

  @override
  State<DetallesProducto> createState() => _DetallesProductoState();
}

class _DetallesProductoState extends State<DetallesProducto> {
  final _productoProvider = ProductoProvider();
  final _archivosProvider = ArchivosProvider();

  late String _linea;
  late String _modelo;
  late String _submodelo;
  late Archivos _archivos;
  late Producto _producto;

  bool _existeFicha = false;
  bool _isLoading = true;
  String _fichaTecnica = '';

  @override
  void initState() {
    super.initState();
    _linea = widget.linea;
    _modelo = widget.modelo;
    _submodelo = widget.submodelo;

    fetchInfo();
  }

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

  Future<void> fetchInfo() async{
    final producto = await _productoProvider.fetchSubmodelos(_linea, _modelo, _submodelo);
    final archivos = await _archivosProvider.fetchArchivos(_submodelo);

    _producto = producto;
    _archivos = archivos;

    String fichaTecnica = '';
    for(int i = 0; i < archivos.result!.length; i++){
      if(archivos.result![i].archFich != null){
        fichaTecnica = archivos.result![i].archFich!;
      }
    }

    if(fichaTecnica.isNotEmpty){
      fichaTecnica = 'https://www.solerpalau.mx/' + fichaTecnica;
      fichaTecnica = fichaTecnica.replaceAll(' ', '%20');
    }

    try{
      final verificarFicha = await http.get(Uri.parse(fichaTecnica));
      _existeFicha = verificarFicha.statusCode == 200;
      _fichaTecnica = fichaTecnica;
    }catch(e){
      _existeFicha = false;
    }

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

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(),
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : SafeArea(
        child: _producto.response! ? 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' ? const AssetImage('assets/habitat_header.jpg')
                        : _linea == 'Comercial' ? const AssetImage('assets/comercial_header.jpg')
                        : _linea == 'Industrial' ? const AssetImage('assets/industrial_header.jpg')
                        : const 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>[
                            const Shadow(
                                offset: Offset(1.0, 1.0),
                                blurRadius: 3.0,
                                color: Colors.black87
                            )
                          ]
                      ),
                    ),
                  ),
                  Positioned(
                    top: 32.0,
                    left: 28.0,
                    child: SizedBox(
                      width: _screenSize.width-56.0,
                      child: Text(
                        'Inicio > $_linea > $_modelo > $_submodelo',
                        style: GoogleFonts.robotoSlab(
                            fontSize: 18.0,
                            color: Colors.white,
                            shadows: <Shadow>[
                              const Shadow(
                                  offset: Offset(1.0, 1.0),
                                  blurRadius: 3.0,
                                  color: Colors.black87
                              )
                            ]
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            const SizedBox(height: 16.0),
            Container(
              margin: const 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
                  )
              ),
            ),
            SizedBox(
              width: _screenSize.width,
              child: Text(
                _producto.message!,
                textAlign: TextAlign.center,
                style: GoogleFonts.roboto(
                    fontSize: 14.0,
                    fontStyle: FontStyle.italic,
                    color: Colors.black54
                ),
              ),
            ),
            Container(
              margin: const 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
                  )
              ),
            ),
          ],
        ) : SingleChildScrollView(
          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' ? const AssetImage('assets/habitat_header.jpg')
                          : _linea == 'Comercial' ? const AssetImage('assets/comercial_header.jpg')
                          : _linea == 'Industrial' ? const AssetImage('assets/industrial_header.jpg')
                          : const 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>[
                              const Shadow(
                                  offset: Offset(1.0, 1.0),
                                  blurRadius: 3.0,
                                  color: Colors.black87
                              )
                            ]
                        ),
                      ),
                    ),
                    Positioned(
                      top: 32.0,
                      left: 28.0,
                      child: SizedBox(
                        width: _screenSize.width-56.0,
                        child: Text(
                          'Inicio > $_linea > $_modelo > $_submodelo',
                          style: GoogleFonts.robotoSlab(
                              fontSize: 18.0,
                              color: Colors.white,
                              shadows: <Shadow>[
                                const Shadow(
                                    offset: Offset(1.0, 1.0),
                                    blurRadius: 3.0,
                                    color: Colors.black87
                                )
                              ]
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(height: 8.0),
              Container(
                width: _screenSize.width,
                padding: const 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: const 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: const AssetImage('assets/progressbar.gif'),
                image: NetworkImage('https://www.solerpalau.mx/ALP/${_producto.result!.id}.jpg'),
                width: _screenSize.width*0.5,
                fit: BoxFit.cover,
              ),
              const SizedBox(height: 16.0),
              Container(
                decoration: const BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            color: Color.fromRGBO(75, 75, 75, 1),
                            width: 3.0
                        )
                    )
                ),
                width: _screenSize.width*0.5,
                padding: const EdgeInsets.only(bottom: 16.0),
                child: Text(
                  'DESCRIPCIÓN',
                  textAlign: TextAlign.center,
                  style: GoogleFonts.roboto(
                      fontWeight: FontWeight.w300,
                      fontSize: 22.0
                  ),
                ),
              ),
              const SizedBox(height: 8.0),
              Container(
                decoration: BoxDecoration(
                    border: Border.all(
                        color: const Color.fromRGBO(204, 204, 204, 1),
                        width: 1.0
                    )
                ),
                width: _screenSize.width*0.95,
                padding: const EdgeInsets.all(16.0),
                child: Html(
                  data: """<p>${_producto.result!.descripcion}</p>""",
                  style: {
                    "p" : Style(
                        fontSize: const FontSize(18.0),
                        color: const Color.fromRGBO(102, 102, 102, 1)
                    )
                  },
                ),
              ),
              const SizedBox(height: 8.0),
              ElevatedButton(
                onPressed: _fichaTecnica.isEmpty || !_existeFicha ? null : (){
                  showViewer(_fichaTecnica);
                },
                style: ElevatedButton.styleFrom(
                  textStyle: const TextStyle(
                      color: Colors.white
                  ),
                  primary: const Color.fromRGBO(100, 149, 237, 1),
                  padding: const EdgeInsets.symmetric(vertical: 16.0, horizontal: 8.0),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(
                      Icons.mail,
                      color: Colors.white,
                      size: 32.0,
                    ),
                    const SizedBox(width: 8.0),
                    Text(
                      'FICHA TÉCNICA',
                      style: GoogleFonts.roboto(
                          color: Colors.white,
                          fontSize: 24.0,
                          fontWeight: FontWeight.w300
                      ),
                    )
                  ],
                ),
              ),
              const SizedBox(height: 32.0),
            ],
          ),
        ),
      ),
    );
  }
}
