// ignore_for_file: avoid_print

import 'package:didvan/config/theme_data.dart';
import 'package:didvan/constants/app_icons.dart';
import 'package:didvan/views/home/bookmarks/bookmark_service.dart';
import 'package:flutter/material.dart';

class BookmarkIcon extends StatefulWidget {
  final int postId; 

  const BookmarkIcon({super.key, required this.postId});

  @override
  State<BookmarkIcon> createState() => _BookmarkIconState();
}

class _BookmarkIconState extends State<BookmarkIcon> {
  bool _bookmarked = false;
  bool _loading = false;

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

  Future<void> _loadStatus() async {
    final bookmarks = await BookmarkService.fetchBookmarks();
    setState(() => _bookmarked = bookmarks.contains(widget.postId));
  }

  Future<void> _toggleBookmark() async {
    setState(() => _loading = true);
    try {
      if (_bookmarked) {
        await BookmarkService.removeBookmark(widget.postId);
        print("Bookmark removed for post ${widget.postId}");
      } else {
        await BookmarkService.addBookmark(widget.postId);
        print("Bookmark added for post ${widget.postId}");
      }
      setState(() {
        _bookmarked = !_bookmarked;
        _loading = false;
      });
    } catch (e) {
      print("Error toggling bookmark for post ${widget.postId}: $e");
      setState(() => _loading = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    return IconButton(
      onPressed: _loading ? null : _toggleBookmark,
      icon: Icon(
        _bookmarked ? DidvanIcons.bookmark_solid : DidvanIcons.bookmark_regular,
        color: _bookmarked
            ? Theme.of(context).colorScheme.secondary
            : Theme.of(context).colorScheme.caption,
      ),
    );
  }
}