import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:quiosco_soler_2/quiosco/models/db_estante_model.dart';
import 'package:quiosco_soler_2/quiosco/widgets/generate_items.dart';
import 'package:quiosco_soler_2/src/providers/db_provider.dart';

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

  @override
  State<SearchPage> createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final _searchController = TextEditingController();
  final _focusNode = FocusNode();

  List<DbEstantes> _items = [];
  List<DbEstantes> _itemsClon = [];

  bool _isSearching = false;
  bool _isLoading = true;

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

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

  @override
  void dispose() {
    super.dispose();
    _searchController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        iconTheme: const IconThemeData(color: Color(0xFFFF0000)),
        actions: [
          if(!_isSearching)
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: () => setState(() {
                _isSearching = true;
                _focusNode.requestFocus();
              }),
            ),
          if(_isSearching)
            IconButton(
              icon: const Icon(Icons.close),
              onPressed: () => setState(() {
                _searchController.clear();
                _itemsClon = _items;
                _isSearching = false;
              }),
            )
        ],
        title: _isSearching ? TextField(
          controller: _searchController,
          cursorColor: const Color(0xFFFF0000),
          decoration: const InputDecoration(
            border: InputBorder.none,
            hintText: 'Buscar...',
          ),
          style: GoogleFonts.roboto(color: const Color(0xFFFF0000)),
          onChanged: (val) => _search(val),
          focusNode: _focusNode,
        ) : const Text(''),
      ),
      body: SafeArea(
        child: _isLoading ? const Center(
          child: CircularProgressIndicator(),
        ) : GenerateItems(findedItems: _isSearching ? _itemsClon : _items),
      ),
    );
  }

  void _search(String value) => setState(() {
    List<DbEstantes> tmp = _items.where((element) => element.esta!.toLowerCase().contains(value.toLowerCase())).toList();
    _itemsClon = tmp;
  });
}
