import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:quiosco_soler_2/quiosco/widgets/generate_items.dart';

import '../../src/providers/db_provider.dart';
import '../models/db_estante_model.dart';

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

  @override
  State<OrderPage> createState() => _OrderPageState();
}

class _OrderPageState extends State<OrderPage> {
  List<DbEstantes> _items = [];
  List<DbEstantes> _itemsClon = [];

  bool _isLoading = true;
  bool _setDates = false;
  String _startDate = "YYYY-MM-DD";
  String _finishDate = "YYYY-MM-DD";

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

  void _init() async{
    _items = await DBProvider.db.getAllEstantesOrderedByDate();
    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        iconTheme: const IconThemeData(color:  Color(0xFFFF0000)),
      ),
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : Column(
        children: [
          const SizedBox(height: 16.0),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const SizedBox(width: 32.0),
              Expanded(
                child: Column(
                  children: [
                    const Text(
                      'DESDE:',
                      style: TextStyle(fontSize: 18.0),
                    ),
                    const SizedBox(height: 4.0),
                    TextButton(
                      style: TextButton.styleFrom(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16.0),
                          side: const BorderSide(
                            color: Colors.black54,
                            width: 2.0,
                          ),
                        ),
                      ),
                      child: Text(
                        _startDate == 'YYYY-MM-DD' ? _startDate : _startDate.substring(0, 10),
                        style: const TextStyle(
                          fontSize: 18.0,
                          color: Colors.black87,
                        ),
                      ),
                      onPressed: () => _selectDate(context, 'start'),
                    )
                  ],
                ),
              ),
              const SizedBox(width: 32.0),
              Expanded(
                child: Column(
                  children: [
                    const Text(
                      'HASTA:',
                      style: TextStyle(fontSize: 18.0),
                    ),
                    const SizedBox(height: 4.0),
                    TextButton(
                      style: TextButton.styleFrom(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16.0),
                          side: const BorderSide(
                            color: Colors.black54,
                            width: 2.0,
                          ),
                        ),
                      ),
                      child: Text(
                        _finishDate == 'YYYY-MM-DD' ? _finishDate : _finishDate.substring(0, 10),
                        style: const TextStyle(
                          fontSize: 18.0,
                          color: Colors.black87,
                        ),
                      ),
                      onPressed: () => _selectDate(context, 'finish'),
                    ),
                  ],
                ),
              ),
              const SizedBox(width: 32.0),
            ],
          ),
          const SizedBox(height: 16.0),
          Expanded(
            child: GenerateItems(findedItems: _setDates ? _itemsClon : _items),
          ),
        ],
      ),
    );
  }

  void _selectDate(BuildContext context, String ident) async{
    if(ident == 'finish' && (_startDate.isEmpty || _startDate == 'YYYY-MM-DD')){
      Fluttertoast.showToast(
        msg: 'Selecciona una fecha de inicio',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER,
        timeInSecForIosWeb: 2,
      );
    }else if(ident == 'start'){
      DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(2000),
        lastDate: DateTime.now(),
        locale: const Locale('es', 'MX'),
      );

      if(picked != null) setState(() => _startDate = picked.toIso8601String());
    }else{
      DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime.parse(_startDate),
        lastDate: DateTime.now(),
        locale: const Locale('es', 'MX'),
      );

      if(picked != null){
        setState(() => _finishDate = picked.toIso8601String());
        Fluttertoast.showToast(
          msg: 'Rango de fechas desde ${_startDate.substring(0, 10)}, hasta ${_finishDate.substring(0, 10)}',
          toastLength: Toast.LENGTH_SHORT,
          gravity: ToastGravity.CENTER,
          timeInSecForIosWeb: 2,
        );

        _orderByDate();
      }
    }
  }

  void _orderByDate() async{
    final estantes = await DBProvider.db.getAllEstantesByDate(_startDate.substring(0, 10), _finishDate.substring(0, 10));
    setState(() {
      _itemsClon = estantes;
      _setDates = true;
    });
  }
}
