import 'package:flutter/material.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/quiosco/models/db_secciones_model.dart';
import 'package:quiosco_soler_2/quiosco/widgets/file_name_down.dart';

class GridViewSections extends StatefulWidget {
  final List<DbSecciones> elements;
  final int ides;

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

  @override
  State<GridViewSections> createState() => _GridViewSectionsState();
}

class _GridViewSectionsState extends State<GridViewSections> {
  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].secc!,
          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['secc'] = widget.elements[index].secc;
          info['idse'] = widget.elements[index].idse;

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

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

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

          _db.collection('quiosco').doc(id).set(infoAct);
          if(action == 'home') Navigator.pop(context);
        },
      )),
    );
  }
}
