import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/presentation/details_page/details_page.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);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: _color,
        title: Text(widget.title),
      ),
      body: const Body(),
    );
  }
}

class Body extends StatelessWidget {
  const Body({super.key});

  @override
  Widget build(BuildContext context) {
    final marketData = FoodRepository().loadData();

    return Center(
      child: FutureBuilder<List<MarketData>?>(
        future: marketData,
        builder: (context, snapshot) => SingleChildScrollView(
          child: snapshot.hasData
              ? Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: snapshot.data?.map((data) {
              return _MarketCard.fromData(
                data,
                onLike: (String title, bool isLiked) =>
                    _showSnackBar(context, title, isLiked),
                onTap: () => _navToDetails(context, data),
              );
            }).toList() ??
                [],
          )
              : const CircularProgressIndicator(),
        ),
      ),
    );
  }

  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)),
    );
  }
}
