"use client";

import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";

export function FollowButton({
  targetUserId: _targetUserId,
  targetUsername,
  initialFollowing = false,
}: {
  targetUserId: string;
  targetUsername: string;
  initialFollowing?: boolean;
}) {
  const [following, setFollowing] = useState(initialFollowing);
  const [loading, setLoading] = useState(false);

  async function toggle() {
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/users/${targetUsername}/follow`, {
        method: following ? "DELETE" : "POST",
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        toast.error(err.error ?? "Failed");
        return;
      }
      setFollowing(!following);
      toast.success(following ? "Unfollowed" : "Following");
    } finally {
      setLoading(false);
    }
  }

  return (
    <Button variant={following ? "outline" : "default"} size="sm" onClick={toggle} disabled={loading}>
      {loading ? "…" : following ? "Following" : "Follow"}
    </Button>
  );
}
