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

import '../models/submodelos.dart';
import '../providers/submodelos_provider.dart';
import 'detalles_producto.dart';

class Comercial extends StatefulWidget {
  final String modelo;
  final List<String> modelos;

  const Comercial({Key? key, required this.modelo, required this.modelos}) : super(key: key);

  @override
  State<Comercial> createState() => _ComercialState();
}

class _ComercialState extends State<Comercial> {
  final _submodelosProvider = SubmodelosProvider();

  bool _isLoading = true;
  bool _searching = false;

  late Submodelos _submodelos;
  late List<String> _modelos;
  late String _modelo;

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

  void init() async{
    await fetchSubmodelos(widget.modelo);
    _modelos = widget.modelos;
    _modelo = widget.modelo;

    final index = _modelos.indexOf(_modelo);
    _modelos.removeAt(index);
    _modelos.insert(0, widget.modelo);

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

  Future<void> fetchSubmodelos(modelo) async{
    final submodelos = await _submodelosProvider.fetchSubmodelos('Comercial', modelo);
    _submodelos = submodelos;

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

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: AppBar(),
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : Column(
          children: [
            Container(
              width: _screenSize.width,
              alignment: Alignment.center,
              child: Stack(
                children: [
                  Image.asset(
                    'assets/comercial_header.jpg',
                    width: _screenSize.width,
                    fit: BoxFit.cover,
                  ),
                  Positioned(
                    bottom: 46.0,
                    left: 28.0,
                    child: Text(
                      'Producto',
                      style: GoogleFonts.roboto(
                        fontSize: 12.0,
                        color: Colors.white,
                        fontWeight: FontWeight.w300,
                        shadows: [
                          const Shadow(
                            offset: Offset(1.0, 1.0),
                            blurRadius: 3.0,
                            color: Colors.black87,
                          ),
                        ],
                      ),
                    ),
                  ),
                  Positioned(
                    bottom: 16.0,
                    left: 28.0,
                    child: Text(
                      'Comercial',
                      style: GoogleFonts.roboto(
                        fontSize: 22.0,
                        color: Colors.white,
                        fontWeight: FontWeight.w300,
                        shadows: [
                          const Shadow(
                            offset: Offset(1.0, 1.0),
                            blurRadius: 3.0,
                            color: Colors.black87,
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.all(8.0),
              width: _screenSize.width,
              height: 48.0,
              child: ListView.separated(
                scrollDirection: Axis.horizontal,
                itemCount: _modelos.length,
                itemBuilder: (context, index) => TextButton(
                  style: TextButton.styleFrom(
                    primary: _modelos[index] == _modelo ? const Color(0xFFB40404) : Colors.transparent,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(28.0),
                      side: BorderSide(
                        color: _modelos[index] == _modelo ? const Color(0xFFB40404) : Colors.black26,
                        width: 2.0,
                      ),
                    ),
                  ),
                  child: Text(
                    _modelos[index],
                    style: GoogleFonts.roboto(
                      color: _modelo == _modelos[index] ? const Color(0xFFB40404) : Colors.black,
                    ),
                  ),
                  onPressed: () async{
                    setState(() {
                      _modelo = _modelos[index];
                      _searching = true;
                    });

                    await fetchSubmodelos(_modelo);
                  },
                ),
                separatorBuilder: (context, index) => const SizedBox(width: 8.0),
              ),
            ),
            Expanded(
              child: _searching ? const Center(
                child: CircularProgressIndicator(),
              ) : GridView.count(
                crossAxisCount: 2,
                shrinkWrap: true,
                children: List.generate(_submodelos.result!.length, (index) => TextButton(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Expanded(
                        child: FadeInImage(
                          placeholder: const AssetImage('assets/progressbar.gif'),
                          image: NetworkImage('http://www.solerpalau.mx/ALP/${_submodelos.result![index].id}.jpg'),
                          fit: BoxFit.fitHeight,
                        ),
                      ),
                      Container(
                        padding: const EdgeInsets.all(4.0),
                        child: Text(
                          _submodelos.result![index].submodelo!,
                          textAlign: TextAlign.center,
                          style: GoogleFonts.roboto(
                            fontWeight: FontWeight.bold,
                            color: const Color.fromRGBO(102, 102, 102, 1),
                            fontSize: 16.0,
                          ),
                        ),
                      )
                    ],
                  ),
                  onPressed: () => Navigator.push(context, MaterialPageRoute(
                    builder: (context) => DetallesProducto(
                      linea: 'Comercial',
                      modelo: _modelo,
                      submodelo: _submodelos.result![index].submodelo!,
                    ),
                  )),
                  style: TextButton.styleFrom(
                    primary: Colors.black12,
                    padding: EdgeInsets.zero,
                    tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    minimumSize: const Size(0.0, 0.0),
                  ),
                )),
              ),
            )
          ],
        ),
      ),
    );
  }
}
