import React, { useState, useEffect } from 'react';
import {
  Box, Container, Typography, Paper,
  List, ListItem, ListItemText, Chip, Stack, CircularProgress, Alert, Button
} from '@mui/material';
import { Link } from 'react-router-dom'; // 假设你已经配置了 React Router

// 模拟从API获取数据
const fetchTorrents = () => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve([
        {
          id: 1,
          title: 'Ubuntu ISO 镜像',
          tags: ['Linux', '操作系统', 'ISO'],
          size: '2.1 GB',
          uploader: 'admin',
          description: '最新的 Ubuntu Desktop 长期支持版。适用于开发者和普通用户。'
        },
        {
          id: 2,
          title: '开源电影素材包 - Blender "Sintel"',
          tags: ['视频', '素材', '开源', 'Blender'],
          size: '800 MB',
          uploader: 'user001',
          description: '来自 Blender Foundation 的开源电影 "Sintel" 的原始素材，可用于学习和创作。'
        },
        {
          id: 3,
          title: 'React 学习资料大全',
          tags: ['React', 'JavaScript', '前端开发', '教程'],
          size: '150 MB',
          uploader: 'dev_guru',
          description: '包含 React 官方文档、优秀教程链接和项目示例。'
        }
      ]);
    }, 1500); // 模拟网络延迟
  });
};


function Home() {
  const [torrents, setTorrents] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    setLoading(true);
    fetchTorrents()
      .then(data => {
        setTorrents(data);
        setLoading(false);
      })
      .catch(err => {
        console.error("Failed to fetch torrents:", err);
        setError("加载资源失败，请稍后再试。");
        setLoading(false);
      });
  }, []);

  return (
    <Box sx={{ minHeight: '100vh', py: 4, background: 'linear-gradient(135deg, #2c3e50, #4ca1af)', color: 'white' }}>
      <Container maxWidth="md" sx={{ position: 'relative', zIndex: 10 }}>
        <Typography variant="h4" sx={{ textAlign: 'center', mb: 3, fontWeight: 'bold' }}>
          🌐 首页 · Mini-Tracker
        </Typography>

        <Paper sx={{ position: 'relative', zIndex: 20, padding: '2rem', backgroundColor: 'rgba(30, 30, 30, 0.9)', borderRadius: '12px' }}>
          <Typography variant="h6" gutterBottom sx={{ mb: 2, color: '#eee' }}>
            最新种子资源
          </Typography>

          {loading && (
            <Box sx={{ display: 'flex', justifyContent: 'center', my: 3 }}>
              <CircularProgress color="inherit" />
            </Box>
          )}

          {error && (
            <Alert severity="error" sx={{ my: 2 }}>{error}</Alert>
          )}

          {!loading && !error && (
            <List sx={{ '& .MuiListItem-root:hover': { backgroundColor: 'rgba(255, 255, 255, 0.05)' }}}>
              {torrents.map(torrent => (
                <ListItem
                  key={torrent.id}
                  component={Link} // react-router-dom Link
                  to={`/detail/${torrent.id}`} // 假设的详情页路由
                  sx={{
                    color: 'white',
                    textDecoration: 'none',
                    mb: 1.5,
                    p: 1.5,
                    borderBottom: '1px solid rgba(255, 255, 255, 0.1)',
                    '&:last-child': {
                      borderBottom: 'none'
                    },
                    display: 'flex',
                    flexDirection: { xs: 'column', sm: 'row' },
                    alignItems: { xs: 'flex-start', sm: 'center' }
                  }}
                  divider={false}
                >
                  <ListItemText
                    primary={torrent.title}
                    secondary={`大小: ${torrent.size} · 上传者: ${torrent.uploader}`}
                    primaryTypographyProps={{
                      variant: 'h6',
                      component: 'div',
                      sx: { mb: 0.5, color: '#f5f5f5', fontWeight: 500 }
                    }}
                    secondaryTypographyProps={{ sx: { color: '#bbb', fontSize: '0.85rem' } }}
                    sx={{ flexGrow: 1, mb: { xs: 1, sm: 0 }, mr: { sm: 2 } }}
                  />

                  <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', gap: 0.5 }}>
                    {torrent.tags.map(tag => (
                      <Chip
                        key={tag}
                        label={tag}
                        size="small"
                        sx={{
                          backgroundColor: 'rgba(255, 255, 255, 0.2)',
                          color: 'white',
                          cursor: 'pointer',
                          '&:hover': {
                            backgroundColor: 'rgba(255, 255, 255, 0.3)',
                          }
                        }}
                      />
                    ))}
                  </Stack>

                  {/* ——— 在此处添加“下载”按钮 —— */}
                  <Button
                    variant="outlined"
                    component="a"
                    href={`http://localhost:8080/api/downloads/${torrent.id}/${encodeURIComponent(torrent.title)}.torrent`}
                    download={`${torrent.title}.torrent`}
                    sx={{
                      ml: { xs: 0, sm: 2 }, // 小屏幕时居中；大屏幕时与右边距留空
                      mt: { xs: 1, sm: 0 }, // 小屏时在下方，留一点间距
                      color: '#4caf50',
                      borderColor: '#4caf50',
                      fontSize: '0.85rem',
                      '&:hover': {
                        backgroundColor: 'rgba(76, 175, 80, 0.15)',
                        borderColor: '#388e3c'
                      }
                    }}
                  >
                    下载
                  </Button>
                  {/* ——— 下载按钮结束 ——— */}

                </ListItem>
              ))}
            </List>
          )}
        </Paper>
      </Container>

      {/* 背景泡泡动画复用 */}
      <Box className="bubbles" sx={{
         pointerEvents: 'none',
         position: 'fixed',
         top: 0,
         left: 0,
         width: '100%',
         height: '100%',
         overflow: 'hidden',
         zIndex: 1,
      }}>
        {[...Array(40)].map((_, i) => (
          <Box
            key={i}
            className="bubble"
            sx={{
              position: 'absolute',
              bottom: '-150px',
              background: `hsla(${Math.random() * 360}, 70%, 80%, 0.15)`,
              borderRadius: '50%',
              animation: 'rise 20s infinite ease-in',
              width: `${Math.random() * 25 + 10}px`,
              height: `${Math.random() * 25 + 10}px`,
              left: `${Math.random() * 100}%`,
              animationDuration: `${15 + Math.random() * 20}s`,
              animationDelay: `${Math.random() * 10}s`,
              opacity: 0,
            }}
          />
        ))}
      </Box>
      <style>
        {`
          body {
            margin: 0;
            font-family: 'Roboto', sans-serif;
          }

          @keyframes rise {
            0% {
              transform: translateY(0) scale(0.8);
              opacity: 0;
            }
            10% {
              opacity: 1;
            }
            90% {
              opacity: 1;
            }
            100% {
              transform: translateY(-130vh) scale(0.3);
              opacity: 0;
            }
          }
        `}
      </style>
    </Box>
  );
}

export default Home;
