import 'package:flutter/material.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/quiosco/models/db_categoria_model.dart';

import 'file_name_down.dart';

class GridViewCategories extends StatefulWidget {
  final List<DbCategorias> elements;
  final int ides;
  final int idse;

  const GridViewCategories({
    Key? key,
    required this.elements,
    required this.ides,
    required this.idse,
  }) : super(key: key);

  @override
  State<GridViewCategories> createState() => _GridViewCategoriesState();
}

class _GridViewCategoriesState extends State<GridViewCategories> {
  final _db = Localstore.instance;

  @override
  Widget build(BuildContext context) {
    return GridView.count(
      crossAxisCount: 3,
      childAspectRatio: (2/3.5),
      children: List.generate(widget.elements.length, (index) => TextButton(
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero,
          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
          minimumSize: const Size(0, 0),
        ),
        child: FileNameDown(
          name: widget.elements[index].cate!,
          image: widget.elements[index].idim!,
          date: 'Publicado el ${widget.elements[index].fecr}',
        ),
        onPressed: () async{
          final items = await _db.collection('quiosco').get();
          final keys = items!.keys;
          final key = keys.last;

          final info = items[key];
          final id = key.replaceAll('/quiosco/', '');

          info['cate'] = widget.elements[index].cate;
          info['idca'] = widget.elements[index].idse;

          _db.collection('quiosco').doc(id).set(info);

          final action = await Navigator.pushNamed(context, 'files');

          final infoAct = {
            'user':        info['user'],
            'accessToken': info['accessToken'],
            'dinum':       info['dinum'],
            'ides':        info['ides'],
            'esta':        info['esta'],
            'secc':        info['secc'],
            'idse':        info['idse'],
          };

          _db.collection('quiosco').doc(id).set(infoAct);

          if(action == 'home') Navigator.pop(context, 'home');
        },
      )),
    );
  }
}

