import 'dart:async';

import 'package:easycook_mobile/blocs/recommendation/search_material/search_material_cubit.dart';
import 'package:easycook_mobile/blocs/recommendation/selected_raw_material/selected_raw_material_cubit.dart';
import 'package:easycook_mobile/models/recommedation.dart';
import 'package:easycook_mobile/pages/rekomendasi.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';

class DapurkuPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PageDapurku();
  }
}

class PageDapurku extends StatefulWidget {
  const PageDapurku({
    super.key,
  });

  @override
  State<PageDapurku> createState() => _PageDapurkuState();
}

class _PageDapurkuState extends State<PageDapurku> {
  Timer? _debounce;

  final _searchCtrl = TextEditingController();

  late SearchMaterialCubit _searchMaterialCubit;
  late SelectedRawMaterialCubit _selectedRawMaterialCubit;

  List<RawMaterial> rawMaterialSelected = [];

  @override
  void initState() {
    _searchMaterialCubit = SearchMaterialCubit();
    _selectedRawMaterialCubit = SelectedRawMaterialCubit();
    _searchCtrl.addListener(_onSearchChanged);
    super.initState();
  }

  _onSearchChanged() {
    if (_debounce?.isActive ?? false) _debounce?.cancel();
    _debounce = Timer(const Duration(milliseconds: 800), () {
      if (_searchCtrl.text.isNotEmpty) {
        _searchMaterialCubit.search(nameProduct: _searchCtrl.text);
        // print(_searchCtrl.text);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MultiBlocProvider(
      providers: [
        BlocProvider(
          create: (context) => _searchMaterialCubit,
        ),
        BlocProvider(
          create: (context) => _selectedRawMaterialCubit,
        ),
      ],
      child: BlocListener(
        bloc: _selectedRawMaterialCubit,
        listener: (context, state) {
          // TODO: implement listener
          if (state is SelectedRawMaterialSuccess) {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (BuildContext context) =>
                    RekomendasiPage(recipeData: state.recipe)));
          }
          if (state is SelectedRawMaterialFailure) {
            print("ERRORRR : ${state.message}");
          }
        },
        child: Scaffold(
          body: Container(
            child: ListView(
              children: [
                Container(
                  width: 360,
                  height: 166,
                  decoration: BoxDecoration(
                    color: Colors.orange,
                    borderRadius: BorderRadius.only(
                        bottomLeft: Radius.circular(30),
                        bottomRight: Radius.circular(30)),
                  ),
                  padding: EdgeInsets.only(
                    top: 24,
                    left: 16,
                    right: 16,
                    bottom: 19,
                  ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Dapurku',
                        style: GoogleFonts.montserrat().copyWith(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                            color: Colors.white),
                      ),
                      Text(
                        'Cari bahan yang ada di dapur dan Anda akan dapatkan inspirasi resep',
                        style: GoogleFonts.montserrat().copyWith(
                          fontSize: 14,
                          color: Colors.white,
                        ),
                      ),
                      Container(
                        width: 350,
                        height: 60,
                        child: TextFormField(
                          controller: _searchCtrl,
                          decoration: const InputDecoration(
                            border: OutlineInputBorder(),
                            filled: true,
                            fillColor: Colors.white,
                            enabledBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.white),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(color: Colors.blueAccent),
                            ),
                            hintText: "Cari Bahan",
                            hintStyle: TextStyle(color: Colors.black26),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 150,
                  child: BlocBuilder(
                      bloc: _searchMaterialCubit,
                      builder: (context, state) {
                        return state is SearchMaterialLoading
                            ? Center(
                                child: CircularProgressIndicator(),
                              )
                            : state is SearchMaterialFailure
                                ? Center(
                                    child: Text(state.message),
                                  )
                                : state is SearchMaterialSuccess
                                    ? ListView.separated(
                                        shrinkWrap: true,
                                        separatorBuilder: (context, index) =>
                                            SizedBox(
                                          height: 10,
                                        ),
                                        itemCount: state.material.length,
                                        itemBuilder: (context, index) {
                                          final data = state.material[index];
                                          return InkWell(
                                            onTap: () {
                                              setState(() {
                                                if (rawMaterialSelected
                                                    .isNotEmpty) {
                                                  if (rawMaterialSelected
                                                      .contains(data)) {
                                                    rawMaterialSelected
                                                        .remove(data);
                                                  } else {
                                                    rawMaterialSelected
                                                        .add(data);
                                                  }
                                                } else {
                                                  rawMaterialSelected.add(data);
                                                }
                                              });

                                              print(
                                                  "JUMLAHHH : ${rawMaterialSelected.length}");
                                            },
                                            child: ListTile(
                                              tileColor: rawMaterialSelected
                                                      .contains(data)
                                                  ? Colors.amber
                                                  : Colors.transparent,
                                              title: Text(data.name),
                                            ),
                                          );
                                        },
                                      )
                                    : SizedBox();
                      }),
                ),
                Padding(
                  padding: const EdgeInsets.only(top: 24, bottom: 24),
                  child: const Divider(
                    thickness: 1,
                    color: Colors.black26,
                  ),
                ),
                Row(
                  children: [
                    SizedBox(
                      width: 10,
                    ),
                    Text(
                      "Bahan yang dipilih",
                      style: GoogleFonts.montserrat().copyWith(
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 10,
                ),
                Padding(
                  padding: const EdgeInsets.all(10),
                  child: SizedBox(
                    width: 150,
                    height: 100,
                    child: Wrap(
                      spacing: 20,
                      runSpacing: 20,
                      children: rawMaterialSelected.map((data) {
                        return Container(
                          padding: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(15),
                            border: Border.all(color: Colors.amber),
                          ),
                          child: Text(
                            data.name,
                            style:
                                GoogleFonts.montserrat().copyWith(fontSize: 12),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(
                      top: 100, left: 55, right: 55, bottom: 10),
                  child: SizedBox(
                    height: 48,
                    width: 328,
                    child: TextButton(
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.orange,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(20),
                        ),
                      ),
                      onPressed: () {
                        _selectedRawMaterialCubit.selectedId(
                            rawMaterialSelected: rawMaterialSelected);
                      },
                      child: Text(
                        'Simpan Bahan',
                        style: GoogleFonts.montserrat().copyWith(
                            color: Colors.white, fontWeight: FontWeight.bold),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
