import 'package:empty_widget/empty_widget.dart';
import 'package:flutter/material.dart';
import '../models/food.dart';
import 'founded_search_component.dart';

class SearchComponent extends StatefulWidget {
  final List<Food> foods;
  final String cardName;
  const SearchComponent(this.foods, this.cardName, {super.key});

  @override
  State<SearchComponent> createState() => _SearchComponentState();
}

class _SearchComponentState extends State<SearchComponent> {
  final TextEditingController controller = TextEditingController();
  late List<Food> allFoods = widget.foods;
  List<Food> foundedFood = [];

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

  @override
  Widget build(BuildContext context) {
    return Container(
      constraints: const BoxConstraints.expand(),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(16, 16, 16, 0), // Add padding on the X-axis
        child: Column(
          children: [
            TextField(
              controller: controller,
              decoration: InputDecoration(
                contentPadding: const EdgeInsets.symmetric(horizontal: 16), // Add padding on the X-axis for text input
                prefix: const Icon(Icons.search),
                hintText: 'Suche nach Gericht',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: const BorderSide(color: Colors.blue),
                ),
              ),
              onChanged: findOnChanged,
            ),
            Expanded(
              child: controller.text.isNotEmpty && foundedFood.isNotEmpty
                  ? ListView.builder(
                itemCount: foundedFood.length,
                itemBuilder: (context, index) {
                  final food = foundedFood[index];
                  return SearchedFoodComponent(food, widget.cardName);
                },
              )
                  : EmptyWidget(),
            ),
          ],
        ),
      ),
    );
  }

  void findOnChanged(String searchedFood) async{
    foundedFood =
        allFoods
            .where((food) => food.name
            .toString()
            .toLowerCase()
            .startsWith(searchedFood.toLowerCase()))
            .toList();
    setState(() {
     foundedFood;
    });
  }
/*
  void findOnChanged(String searchedFood) async {
    foundedFood.clear();
    if(searchedFood.isEmpty){
      setState(() {});
      return;
    }else{
      for (final food in allFoods) {
        if (food.name.toString().toLowerCase().contains(searchedFood)) {
          foundedFood.add(food);
        }
      }
      setState(() => {foundedFood});
    }
  }
*/
}
