import { useEffect, useState } from 'react';
import { fetchCreators, updateCreator } from '../api/client';

export function CreatorsPage() {
  const [creators, setCreators] = useState<Awaited<ReturnType<typeof fetchCreators>>['creators']>([]);
  const [keyword, setKeyword] = useState('');
  const [error, setError] = useState<string | null>(null);

  const load = async () => {
    try {
      const data = await fetchCreators(keyword);
      setCreators(data.creators);
    } catch (err) {
      setError(err instanceof Error ? err.message : '加载失败');
    }
  };

  useEffect(() => {
    void load();
  }, []);

  return (
    <div className="grid">
      <div className="card" style={{ display: 'flex', gap: 8 }}>
        <input value={keyword} onChange={(e) => setKeyword(e.target.value)} placeholder="搜索创作者" />
        <button type="button" className="btn secondary" onClick={() => void load()}>
          搜索
        </button>
      </div>
      {error ? <p className="alert">{error}</p> : null}
      {creators.map((creator) => (
        <div key={creator.user_id} className="card" style={{ display: 'flex', justifyContent: 'space-between' }}>
          <div>
            <strong>{creator.display_name}</strong> @{creator.slug}
            <p style={{ color: '#68716c', fontSize: 12 }}>
              {creator.post_count} 篇 · {creator.follower_count} 粉丝
              {creator.verified ? ' · 已认证' : ''}
            </p>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button
              type="button"
              className="btn secondary"
              onClick={() =>
                void updateCreator(creator.user_id, { verified: !creator.verified }).then(load)
              }
            >
              {creator.verified ? '取消认证' : '认证'}
            </button>
            <button
              type="button"
              className="btn secondary"
              onClick={() =>
                void updateCreator(creator.user_id, { post_banned: !creator.post_banned }).then(load)
              }
            >
              {creator.post_banned ? '解除禁发' : '禁发'}
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}
