import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:localstore/localstore.dart';
import 'package:quiosco_soler_2/quiosco/widgets/gridview.dart';
import 'package:quiosco_soler_2/quiosco/widgets/horizontal_listview.dart';
import 'package:quiosco_soler_2/quiosco/widgets/lateral_menu.dart';
import 'package:quiosco_soler_2/src/providers/db_provider.dart';

import '../models/db_estante_model.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
  final db = Localstore.instance;
  late List<DbEstantes> _dbEstantes;
  late List<DbEstantes> _dbEstantesByDate;
  dynamic _logInfo;
  bool _isLoading = true;
  String _dbKey = "";

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

  void _getInfo() async{
    final estantes = await DBProvider.db.getAllEstantes();
    final estantesByDate = await DBProvider.db.getAllEstantesOrderedByDate();
    final items = await db.collection('quiosco').get();
    final key = items!.keys.last;

    final info = items[key];
    _logInfo = info;
    _dbKey = key;

    _dbEstantes = estantes;
    _dbEstantesByDate = estantesByDate;

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

  @override
  Widget build(BuildContext context) {
    final _screenSize = MediaQuery.of(context).size;
    return Scaffold(
      key: _scaffoldkey,
      drawer: LateralMenu(page: const [1,0,0,0,0], level: '', onOptionSelected: _optionHandler),
      appBar: AppBar(
        automaticallyImplyLeading: false,
        backgroundColor: Colors.white,
        centerTitle: true,
        title: Row(
          children: [
            Image.asset(
              'assets/logo.png',
              width: 32.0,
            ),
            const SizedBox(width: 8.0),
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                minimumSize: const Size(0, 0),
              ),
              child: const Icon(
                Icons.menu,
                color: Color(0xFFFF0000),
              ),
              onPressed: () => _scaffoldkey.currentState?.openDrawer(),
            ),
            const Expanded(
              child: Text(
                'QUIOSCO',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.red,
                  fontFamily: 'Helvetica Neue Black Cond',
                ),
              ),
            ),
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                minimumSize: const Size(0, 0),
              ),
              child: const Icon(
                Icons.refresh,
                color: Colors.red,
              ),
              onPressed: () {
                setState(() => _isLoading = true);
                _getInfo();
              },
            ),
            const SizedBox(width: 16.0),
            TextButton(
              style: TextButton.styleFrom(
                padding: EdgeInsets.zero,
                tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                minimumSize: const Size(0, 0),
              ),
              child: const Icon(
                Icons.logout,
                color: Color(0xFFFF0000),
              ),
              onPressed: () {
                DBProvider.db.deleteAllArchivos();
                DBProvider.db.deleteAllCategorias();
                DBProvider.db.deleteAllSecciones();
                DBProvider.db.deleteAllEstantes();
                DBProvider.db.deleteAllLogs();

                final id = _dbKey.replaceAll('/quiosco/', "");
                db.collection('quiosco').doc(id).delete();

                Navigator.pop(context, 'logout');
              },
            )
          ],
        ),
      ),
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : Column(
        children: [
          Container(
            height: 44.0,
            width: _screenSize.width,
            alignment: Alignment.center,
            color: Colors.grey,
            child: Text(
              'BIENVENIDO: ${_logInfo['user']}',
              textAlign: TextAlign.center,
              style: const TextStyle(
                fontSize: 14.0,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
          ),
          SizedBox(
            height: 168.0,
            child: _dbEstantesByDate.isEmpty ? Center(
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 8.0),
                child: const Text('No se encontraron modificaciones recientes'),
              ),
            ) : HorizontalListview(
              files: _dbEstantesByDate,
              nextPage: 'secc',
              infoKey: _dbKey,
              info: _logInfo,
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 24.0),
            child: RichText(
              textAlign: TextAlign.center,
              text: TextSpan(
                style: GoogleFonts.roboto(
                  fontWeight: FontWeight.bold,
                  fontSize: 18.0,
                ),
                children: [
                  TextSpan(
                    text: "TODOS LOS ",
                    style: GoogleFonts.roboto(color: Colors.black),
                  ),
                  TextSpan(
                    text: "ESTANTES ",
                    style: GoogleFonts.roboto(color: Colors.red),
                  ),
                ]
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 8.0),
            alignment: Alignment.center,
            height: 4.0,
            width: 28.0,
            decoration: BoxDecoration(
              color: Colors.red,
              borderRadius: BorderRadius.circular(16.0),
            ),
          ),
          const SizedBox(height: 8.0),
          Expanded(
            child: _dbEstantes.isEmpty ? Container(
              margin: const EdgeInsets.symmetric(horizontal: 8.0),
              child: const Text('No se encontraron estantes'),
            ) : GridViewAfter(
              elements: _dbEstantes,
              infoKey: _dbKey,
              info: _logInfo,
            ),
          ),
          Container(
            height: 48.0,
            width: _screenSize.width,
            color: const Color(0xFFB40404),
            child: Row(
              children: [
                MaterialButton(
                  minWidth: _screenSize.width * 0.5,
                  height: 48.0,
                  child: const Icon(Icons.search, size: 36.0, color: Colors.white),
                  onPressed: () => Navigator.pushNamed(context, 'search'),
                ),
                MaterialButton(
                  minWidth: _screenSize.width * 0.5,
                  height: 48.0,
                  child: const Icon(Icons.date_range, size: 36.0, color: Colors.white),
                  onPressed: () => Navigator.pushNamed(context, 'order'),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  void _optionHandler(String a, String? b){
    if(a == 'pop'){
      if(b == 'home'){
        Navigator.pop(context);
        Navigator.pop(context, b);
      }
    }
  }
}
