import { useEffect, useState } from 'react';
import { Button, Spin } from 'antd';
import type { DouyuTaskItem } from '../api/types';
import { getExchangeImage } from '../utils/exchangeImage';

interface Props {
  task: DouyuTaskItem;
  onClick?: (task: DouyuTaskItem, url: string) => void;
}

export default function ExchangeResultImage({ task, onClick }: Props) {
  const [url, setUrl] = useState('');
  const [failed, setFailed] = useState(false);
  const [gen, setGen] = useState(0);

  useEffect(() => {
    let alive = true;
    setFailed(false);
    getExchangeImage(task)
      .then(({ url }) => { if (alive) setUrl(url); })
      .catch(() => { if (alive) setFailed(true); });
    return () => { alive = false; };
  }, [task, gen]);

  if (failed) {
    return (
      <Button
        size="small"
        type="text"
        onClick={() => setGen((g) => g + 1)}
      >
        重试
      </Button>
    );
  }
  if (!url) return <Spin size="small" />;
  return (
    <div
      onClick={() => onClick?.(task, url)}
      style={{ cursor: 'pointer', display: 'inline-block', lineHeight: 0 }}
      title="点击查看大图并复制"
    >
      <img
        src={url}
        width={56}
        height={82}
        alt="兑换结果"
        style={{ objectFit: 'cover', borderRadius: 6, border: '1px solid #f0f0f0' }}
      />
    </div>
  );
}
