'use client';

// components/CopyShortenedLink.jsx
import SvgIcon from '@/components/SvgIcon';
import useGlobalStore from '@/config/use-global';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@workspace/airo-ui/components/button';
import { cn } from '@workspace/airo-ui/lib/utils';
import { isBrowser } from '@workspace/airo-ui/utils';
import { useTranslations } from 'next-intl';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { toast } from 'sonner';

const CopyShortenedLink = ({ className }: { className?: string }) => {
  const t = useTranslations('affiliate');
  const { user } = useGlobalStore();

  // 构建长链接，使用用户的唯一标识符作为查询键
  const target = isBrowser ? `${location?.origin}/?invite=${user?.refer_code}` : '';
  const queryKey = ['short-url', user?.refer_code];

  const { data: shortUrl } = useQuery({
    queryKey: queryKey,
    queryFn: async () => {
      const response = await fetch('/api/kutt', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ target }),
      });

      if (!response.ok) {
        throw new Error('Network response was not ok');
      }

      // 关键步骤：解析 JSON 数据并返回
      const json = await response.json();
      return json.link ?? null;
    },
    enabled: !!(user?.refer_code && target), // 默认不自动执行
    staleTime: Infinity, // 数据永不过期，除非手动失效
  });
  // 渲染组件
  return (
    <CopyToClipboard
      text={shortUrl} // 如果 shortUrl 还没有值，则传递空字符串
      onCopy={(text, result) => {
        if (!text) {
          toast.success('text is undefined');
          return;
        }
        if (result) {
          toast.success(t('copySuccess'));
        }
      }}
    >
      {/* 按钮的逻辑 */}
      <Button variant='link' size='sm' className={cn('h-auto p-0 px-0 [&_svg]:size-5', className)}>
        <SvgIcon name={'copy'}></SvgIcon>
      </Button>
    </CopyToClipboard>
  );
};

export default CopyShortenedLink;
