"use client";

import { useState, useTransition } from "react";
import { toggleFollow, toggleWatch } from "@/lib/actions/social";
import { BellIcon } from "@/components/ui/BellIcon";

export function FollowWatchButtons({
  targetUserId,
  initialFollowing,
  initialWatching,
}: {
  targetUserId: string;
  initialFollowing: boolean;
  initialWatching: boolean;
}) {
  const [following, setFollowing] = useState(initialFollowing);
  const [watching, setWatching] = useState(initialWatching);
  const [, startTransition] = useTransition();

  function handleFollow() {
    const next = !following;
    setFollowing(next);
    // A fresh follow starts watching (matches the server default); unfollow
    // clears watch too, since the underlying Follow row is deleted.
    setWatching(next);
    startTransition(() => {
      toggleFollow(targetUserId);
    });
  }

  function handleBell() {
    setWatching((w) => !w);
    startTransition(() => {
      toggleWatch(targetUserId);
    });
  }

  return (
    <div className="flex items-center gap-2">
      <button
        type="button"
        onClick={handleFollow}
        className={`rounded-full border px-4 py-1.5 text-sm font-medium ${
          following
            ? "border-terracotta bg-terracotta/10 text-terracotta"
            : "border-charcoal/20 text-charcoal hover:bg-charcoal/5"
        }`}
      >
        {following ? "Following" : "Follow"}
      </button>
      {following && (
        <button
          type="button"
          onClick={handleBell}
          aria-label={
            watching
              ? "Notifications on (click to mute)"
              : "Notifications muted (click to turn on)"
          }
          title={
            watching
              ? "Notifications on (click to mute)"
              : "Notifications muted (click to turn on)"
          }
          className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border ${
            watching
              ? "border-terracotta bg-terracotta/10 text-terracotta"
              : "border-charcoal/20 text-charcoal/50"
          } hover:bg-charcoal/5`}
        >
          <BellIcon muted={!watching} />
        </button>
      )}
    </div>
  );
}
