import React, { useState } from 'react';
import { Input, Button, message } from 'antd';
import styles from './ShareCodeValidator.module.css';
import {env} from '../../../env'
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 validateCode = async () => {
    if (!code.trim()) {
      message.warning('请输入分享码');
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(`http://${env.SERVER_IP}:${env.SERVER_PORT}/upload/share/${code.trim()}`);
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || '分享码无效或已过期');
      }

      const data = await response.json();
      console.log('验证分享码返回数据:', data);

      if (!data.fileId) {
        throw new Error('未找到文件ID');
      }

      const fileName = data.fileName || 'downloaded_file';
      
      onValidSuccess(data.fileId, fileName);
      message.success(`验证成功，文件名：${fileName}`);
    } catch (error) {
      console.error('验证分享码失败:', error);
      message.error('分享码无效或已过期');
    } finally {
      setLoading(false);
    }
  };

  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>
  );
};