import 'package:flutter/material.dart';
import '../../data/dtos/hero_dto.dart';
import '../components/screens/hero_detail_screen.dart';
import '../services/like_service.dart';
import '../../Components/locale/l10n/app_locale.dart';

class HeroCard extends StatefulWidget {
  final HeroDto hero;

  const HeroCard({Key? key, required this.hero}) : super(key: key);

  @override
  _HeroCardState createState() => _HeroCardState();
}

class _HeroCardState extends State<HeroCard> {
  final LikeService _likeService = LikeService();
  bool _isLiked = false;

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

  Future<void> _loadLikeStatus() async {
    final isLiked = await _likeService.isHeroLiked(widget.hero.id);
    setState(() {
      _isLiked = isLiked;
    });
  }

  Future<void> _toggleLike() async {
    final locale = AppLocale.of(context)!; // Получаем текущую локализацию
    String message;

    if (_isLiked) {
      await _likeService.unlikeHero(widget.hero.id);
      message = '${locale.disliked} ${widget.hero.name}';
    } else {
      await _likeService.likeHero(widget.hero.id);
      message = '${locale.liked} ${widget.hero.name}';
    }

    setState(() {
      _isLiked = !_isLiked;
    });

    // Отображение Snackbar с локализованным сообщением
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        duration: const Duration(seconds: 2),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Card(
      child: ListTile(
        leading: widget.hero.portraitUrl != null
            ? Image.network(widget.hero.portraitUrl!)
            : const Icon(Icons.image),
        title: Text(widget.hero.name),
        trailing: IconButton(
          icon: Icon(
            _isLiked ? Icons.favorite : Icons.favorite_border,
            color: _isLiked ? Colors.red : null,
          ),
          onPressed: _toggleLike, // Вызываем метод с Snackbar
        ),
        onTap: () {
          Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HeroDetailScreen(heroId: widget.hero.id),
            ),
          );
        },
      ),
    );
  }
}
