'use client';

import { useState } from 'react';
import { LoginPrompt } from '@/components/auth/LoginPrompt';
import { PlazaApiError, toggleFollow } from '@/lib/api';

type FollowButtonProps = {
  slug: string;
  initialFollowing?: boolean;
  className?: string;
};

export function FollowButton({ slug, initialFollowing, className = '' }: FollowButtonProps) {
  const [following, setFollowing] = useState(initialFollowing ?? false);
  const [loginOpen, setLoginOpen] = useState(false);
  const [busy, setBusy] = useState(false);

  const handleClick = async () => {
    if (busy) return;
    setBusy(true);
    try {
      const result = await toggleFollow(slug, following);
      setFollowing(result.following);
    } catch (error) {
      if (error instanceof PlazaApiError && error.code === 'unauthorized') {
        setLoginOpen(true);
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <button
        type="button"
        disabled={busy}
        onClick={handleClick}
        className={`rounded-full border px-4 py-2 text-sm font-semibold transition ${
          following
            ? 'border-[#d6d0c3] bg-[#f0ebe0] text-[#4a5751]'
            : 'border-[#2f6f57] text-[#2f6f57] hover:bg-[#2f6f57] hover:text-white'
        } ${className}`}
      >
        {following ? '已关注' : '关注'}
      </button>
      <LoginPrompt
        open={loginOpen}
        onClose={() => setLoginOpen(false)}
        message="登录后即可关注创作者"
      />
    </>
  );
}
