"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() {
    const next = !following;
    setFollowing(next);
    setLoading(true);
    try {
      const res = await fetch(`/api/v1/users/${targetUsername}/follow`, {
        method: next ? "POST" : "DELETE",
      });
      if (!res.ok) {
        const err = await res.json() as { error?: string };
        throw new Error(err.error);
      }
      toast.success(next ? "Following" : "Unfollowed");
    } catch (err) {
      setFollowing(!next);
      toast.error(err instanceof Error && err.message ? err.message : "Failed");
    } finally {
      setLoading(false);
    }
  }

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