import React, { useCallback, useState } from 'react';
import { Input, Button, message } from 'antd';
import styles from './ShareCodeValidator.module.css';
import {env} from '../../../env'
import { api } from '@nice/client';
interface ShareCodeValidatorProps {
  onValidSuccess: (fileId: string, fileName: string) => void;
}

export const ShareCodeValidator: React.FC<ShareCodeValidatorProps> = ({
  onValidSuccess,
}) => {
  const [code, setCode] = useState('');
  const [loading, setLoading] = useState(false);
  const { data: result, isLoading } = api.shareCode.getFileByShareCode.useQuery(
    { code: code.trim() },
    {
      enabled: !!code.trim()
    }
  )



  const validateCode = useCallback(() => {
    if (!code.trim()) {
      message.warning('请输入分享码');
      return;
    }

    setLoading(true);
    try {
      console.log('验证分享码返回数据:', result);
      onValidSuccess(result.fileId, result.fileName);
      message.success(`验证成功，文件名：${result.fileName}`);
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    } finally {
      setLoading(false);
    }
  },[result]) 

  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={validateCode}
        loading={loading}
        disabled={!code.trim()}
      >
        验证并下载
      </Button>
    </div>
  );
};