import React, { useCallback, useEffect, useState } from 'react';
import { Input, Button, message } from 'antd';
import styles from './ShareCodeValidator.module.css';
import { api } from '@nice/client';
import dayjs from 'dayjs';
interface ShareCodeValidatorProps {
  onValidSuccess: (fileId: string, fileName: string) => void;
}
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
import { env } from '@web/src/env';
import { copyToClipboard } from './sharecodegenerator';
dayjs.extend(utc);
dayjs.extend(timezone);
export const ShareCodeValidator: React.FC<ShareCodeValidatorProps> = ({
  onValidSuccess,
}) => {
  const [code, setCode] = useState('');
  const { data: result, isLoading, refetch } = api.shareCode.getFileByShareCode.useQuery(
    { code: code.trim() },
    {
      enabled: false
    }
  )
  const validateCode = useCallback(async () => {

    if (!code.trim()) {
      message.warning('请输入正确的分享码');
      return;
    }
    try {
      const { data: latestResult } = await refetch();
      console.log('验证分享码返回数据:', latestResult);
      onValidSuccess(latestResult.url, latestResult.fileName);
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    }
  }, [refetch, code, onValidSuccess]);
  const getDownloadUrl = useCallback(async () => {
    try {
      const { data: latestResult } = await refetch();
      console.log('验证分享码返回数据:', latestResult);
      const downloadUrl = `http://${env.SERVER_IP}:${env.FILE_PORT}/uploads/${latestResult.url}`;
      copyToClipboard(downloadUrl)
        .then(() => {
          message.success(`${latestResult.fileName}的下载链接已复制`,6)
        })
        .catch(() => {
          message.error('复制失败')
        });
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    }
  }, [refetch, code, onValidSuccess]);
  return (
    <>
      <div className={styles.container}>
        <Input
          className={styles.input}
          value={code}
          onChange={(e) => setCode(e.target.value.toUpperCase())}
          placeholder="请输入分享码"
          maxLength={8}
          onPressEnter={validateCode}
        />
        <Button
          type="primary"
          onClick={getDownloadUrl}
          loading={isLoading}
          disabled={!code.trim()}
        >
          获取下载链接
        </Button>
        <Button
          type="primary"
          onClick={validateCode}
          loading={isLoading}
          disabled={!code.trim()}
        >
          下载
        </Button>
      </div>
      {
        !isLoading && result && (
          <div className='w-full flex justify-between my-2 p-1 antialiased text-secondary-600'>
            <span >{`分享码：${result?.code ? result.code : ''}`}</span>
            <span >{`文件名：${result?.fileName ? result.fileName : ''}`}</span>
            <span >{`过期时间：${result?.expiresAt ? dayjs(result.expiresAt).format('YYYY-MM-DD HH:mm:ss') : ''}`}</span>
            <span >{`剩余使用次数：${result?.canUseTimes ? result.canUseTimes : ''}`}</span>
          </div>
        )
      }
    </>
  );
};