import { useState, useEffect } from 'react';
import { Card, Tag, Row, Col, Spin } from 'antd';
import { RightOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { getWorksList } from '../api/works';
import { API_CONFIG } from '../utils/config';
import './Works.css';

const Works = ({ title, type, categoryFilter }) => {
  const navigate = useNavigate();
  const [works, setWorks] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadWorks();
  }, [type, categoryFilter]);

  const loadWorks = async () => {
    setLoading(true);
    const result = await getWorksList(1, 9, categoryFilter || '');
    setLoading(false);
    
    if (result.success) {
      setWorks(result.data.items || []);
    }
  };

  // 使用 Picsum 随机图片（更稳定）
  const getImageUrl = (id, width = 400, height = 300) => {
    return `https://picsum.photos/seed/${id}/${width}/${height}`;
  };

  const getLevelColor = (level) => {
    const colors = {
      1: '#999',
      2: '#74b9ff',
      3: '#00b894',
      4: '#6c5ce7',
      5: '#e17055',
      6: '#ff5a5a',
    };
    return colors[level] || '#999';
  };

  // 点击卡片，跳转到详情页
  const handleCardClick = (work) => {
    navigate(`/detail/${work.id}`);
  };

  if (loading) {
    return (
      <section className="works-section">
        <div style={{ textAlign: 'center', padding: '40px 0' }}>
          <Spin size="large" tip="加载中..." />
        </div>
      </section>
    );
  }

  return (
    <section className="works-section">
      <div className="section-header">
        <h2 className="section-title">{title}</h2>
        <a href="#" className="view-more">
          查看更多 <RightOutlined />
        </a>
      </div>
      
      <Row gutter={[16, 16]} className="works-grid">
        {works.map((work, index) => (
          <Col xs={12} sm={8} md={8} lg={8} xl={8} key={work.id}>
            <Card 
              className="work-card"
              hoverable
              style={{ '--delay': `${index * 0.05}s` }}
              onClick={() => handleCardClick(work)}
              cover={
                <div className="work-image">
                  <img 
                    src={work.thumbnail_image ? `${API_CONFIG.baseURL}${work.thumbnail_image}` : getImageUrl(work.id)} 
                    alt={work.title}
                    loading="lazy"
                    onError={(e) => {
                      e.target.src = getImageUrl(work.id);
                    }}
                  />
                  <div className="work-preview">
                    <span className="preview-icon">🔍</span>
                  </div>
                </div>
              }
            >
              <div className="work-info">
                <h3 className="work-title">{work.title}</h3>
                <div className="work-meta">
                  <span className="work-designer">{work.designer}</span>
                  <Tag 
                    className="work-level" 
                    style={{ 
                      color: getLevelColor(work.level),
                      borderColor: getLevelColor(work.level)
                    }}
                  >
                    Lv.{work.level}
                  </Tag>
                  <span className="work-level-text">{work.level_text}</span>
                </div>
                <div className="work-price" style={{ marginTop: 8, color: '#ff5a5a', fontWeight: 'bold', fontSize: 16 }}>
                  ¥{work.price}
                </div>
              </div>
            </Card>
          </Col>
        ))}
      </Row>
    </section>
  );
};

export default Works;
