import React, { useState } from 'react';
import {
  Button,
  TextField,
  Box,
  Typography,
  Alert,
} from '@mui/material';
import { Download } from '@mui/icons-material';

interface S3DownloadButtonProps {
  label?: string;
}

const S3DownloadButton: React.FC<S3DownloadButtonProps> = ({ label = 'S3下载' }) => {
  const [fileName, setFileName] = useState('');
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleDownload = async () => {
    if (!fileName.trim()) {
      setError('请输入文件名');
      return;
    }

    try {
      setError('');
      setSuccess('');

      // 构建S3文件URL
      const fileUrl = `http://172.14.3.142:4566/my-bucket/uploads/${fileName.trim()}`;
      
      // 方法1：直接使用a标签下载（如果S3配置了正确的Content-Disposition）
      const link = document.createElement('a');
      link.href = fileUrl;
      link.download = fileName.trim();
      link.target = '_blank';
      
      // 方法2：如果方法1不行，尝试添加时间戳避免缓存问题
      // const timestamp = new Date().getTime();
      // const downloadUrl = `${fileUrl}?t=${timestamp}`;
      // link.href = downloadUrl;
      
      // 添加到DOM并触发点击
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      setSuccess(`文件 ${fileName} 下载成功！`);
      setFileName('');
    } catch (err) {
      setError(`下载失败: ${err instanceof Error ? err.message : '未知错误'}`);
    }
  };

  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      handleDownload();
    }
  };

  return (
    <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, p: 2, border: '1px solid #e0e0e0', borderRadius: 1 }}>
      <Typography variant="h6" gutterBottom>
        S3文件下载
      </Typography>
      
      <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
        <TextField
          label="文件名"
          variant="outlined"
          size="small"
          value={fileName}
          onChange={(e) => setFileName(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="例如: 20251125_150429_f43f9a67.txt"
          sx={{ minWidth: 300 }}
        />
        <Button
          variant="contained"
          startIcon={<Download />}
          onClick={handleDownload}
          disabled={!fileName.trim()}
        >
          {label}
        </Button>
      </Box>
      
      {error && (
        <Alert severity="error" onClose={() => setError('')}>
          {error}
        </Alert>
      )}
      
      {success && (
        <Alert severity="success" onClose={() => setSuccess('')}>
          {success}
        </Alert>
      )}
      
      <Typography variant="body2" color="text.secondary">
        提示：输入文件名后点击下载按钮，文件将从S3存储桶下载到本地
      </Typography>
    </Box>
  );
};

export default S3DownloadButton;