import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pmu/components/utils/debounce.dart';
import 'package:pmu/data/repository/food_repository.dart';
import 'package:pmu/data/repository/mock_repository.dart';
import 'package:pmu/domain/models/card.dart';
import 'package:pmu/main.dart';
import 'package:pmu/presentation/details_page/details_page.dart';
import 'package:pmu/presentation/home_page/bloc/bloc.dart';
import 'package:pmu/presentation/home_page/bloc/events.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:pmu/presentation/home_page/bloc/state.dart';

part 'card.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final Color _color = const Color(0xFFFFA400);
  final searchController = TextEditingController();
  late Future<List<MarketData>?> data;
  final repo = FoodRepository();

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<HomeBloc>().add(const HomeLoadDataEvent());
    });

    super.initState();
  }

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

  Future<void> _onRefresh() {
    context
        .read<HomeBloc>()
        .add(HomeLoadDataEvent(search: searchController.text));
    return Future.value(null);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(12),
              child: CupertinoSearchTextField(
                controller: searchController,
                onChanged: (search) {
                  Debounce.run(() => context
                      .read<HomeBloc>()
                      .add(HomeLoadDataEvent(search: search)));
                },
              ),
            ),
            BlocBuilder<HomeBloc, HomeState>(
                builder: (context, state) => state.error != null
                    ? Text(
                        state.error ?? '',
                        style: Theme.of(context)
                            .textTheme
                            .headlineSmall
                            ?.copyWith(color: Colors.red),
                      )
                    : state.isLoading
                        ? const CircularProgressIndicator()
                        : Expanded(
                            child: RefreshIndicator(
                            onRefresh: _onRefresh,
                            child: ListView.builder(
                              padding: EdgeInsets.zero,
                              itemCount: state.data?.length ?? 0,
                              itemBuilder: (context, index) {
                                final data = state.data?[index];
                                return data != null
                                    ? _MarketCard.fromData(
                                        data,
                                        onLike: (title, isLiked) =>
                                            _showSnackBar(
                                                context, title, isLiked),
                                        onTap: () =>
                                            _navToDetails(context, data),
                                      )
                                    : const SizedBox.shrink();
                              },
                            ),
                          ))),
          ],
        ),
      ),
    );
  }

  void _showSnackBar(BuildContext context, String title, bool isLiked) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(
        content: Text(
          'Товар $title ${isLiked ? 'добавлен в избранное' : 'удален из избранного'}',
          style: Theme.of(context).textTheme.bodyLarge,
        ),
        backgroundColor: Colors.orangeAccent,
        duration: const Duration(seconds: 1),
      ));
    });
  }

  void _navToDetails(BuildContext context, MarketData data) {
    Navigator.push(
      context,
      CupertinoPageRoute(builder: (context) => DetailsPage(data)),
    );
  }
}
