import { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Tag, message, Input, Modal, Spin } from 'antd';
import { HeartOutlined, HeartFilled, DownloadOutlined, ShareAltOutlined, EyeOutlined, PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { QRCodeSVG } from 'qrcode.react';
import { getWorkDetail } from '../api/works';
import { createOrder } from '../api/orders';
import { createPayment, queryPaymentStatus } from '../api/payment';
import { downloadWork } from '../api/download';
import { isLoggedIn } from '../api/auth';
import { API_CONFIG } from '../utils/config';
import Header from '../components/Header';
import Footer from '../components/Footer';
import './WorkDetail.css';

const WorkDetail = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [collected, setCollected] = useState(false);
  const [followed, setFollowed] = useState(false);
  const [downloadModalOpen, setDownloadModalOpen] = useState(false);
  const [workData, setWorkData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [purchasing, setPurchasing] = useState(false);
  const [paymentUrl, setPaymentUrl] = useState('');
  const [orderNumber, setOrderNumber] = useState('');
  const [checkingPayment, setCheckingPayment] = useState(false);

  // 加载作品详情
  useEffect(() => {
    loadWorkDetail();
  }, [id]);

  const loadWorkDetail = async () => {
    setLoading(true);
    const result = await getWorkDetail(id);
    setLoading(false);
    
    if (result.success) {
      setWorkData(result.data);
    } else {
      message.error('加载作品详情失败');
    }
  };

  // 使用 Picsum 图片作为后备
  const getImageUrl = (workId) => {
    return `https://picsum.photos/seed/${workId}/800/1200`;
  };

  const getRelatedImageUrl = (workId) => {
    return `https://picsum.photos/seed/related${workId}/400/600`;
  };

  const relatedWorks = [
    {
      id: '20',
      title: '相关设计作品1',
      image: getRelatedImageUrl(20),
      designer: 'cestbon',
      level: 1,
      levelName: '设计爱好者'
    },
    {
      id: '21',
      title: '相关设计作品2',
      image: getRelatedImageUrl(21),
      designer: '六十六号屯',
      level: 4,
      levelName: '资深设计师'
    },
    {
      id: '22',
      title: '相关设计作品3',
      image: getRelatedImageUrl(22),
      designer: '扶摇',
      level: 3,
      levelName: '设计师'
    }
  ];

  const handleCollect = () => {
    setCollected(!collected);
    message.success(collected ? '已取消收藏' : '收藏成功');
  };

  const handleFollow = () => {
    setFollowed(!followed);
    message.success(followed ? '已取消关注' : '关注成功');
  };

  const handleDownload = async () => {
    // 检查是否登录
    if (!isLoggedIn()) {
      message.warning('请先登录');
      return;
    }

    // 尝试直接下载
    const result = await downloadWork(id, `${workData.title}.jpg`);
    
    // 如果需要购买，显示购买确认弹窗
    if (!result.success && result.needPurchase) {
      setDownloadModalOpen(true);
    }
  };

  const confirmDownload = async () => {
    setPurchasing(true);
    
    // 1. 创建订单
    const orderResult = await createOrder(id);
    if (!orderResult.success) {
      setPurchasing(false);
      message.error(orderResult.message);
      return;
    }

    const order = orderResult.data;
    setOrderNumber(order.order_no);

    // 2. 创建支付链接
    const paymentResult = await createPayment(order.id);
    setPurchasing(false);
    
    if (paymentResult.success) {
      setPaymentUrl(paymentResult.data.pay_url);
      message.success('请扫描二维码完成支付');
      // 开始轮询支付状态
      startPaymentStatusCheck(order.order_no);
    } else {
      message.error(paymentResult.message);
      setDownloadModalOpen(false);
    }
  };

  // 轮询检查支付状态
  const startPaymentStatusCheck = (orderNum) => {
    setCheckingPayment(true);
    const checkInterval = setInterval(async () => {
      const result = await queryPaymentStatus(orderNum);
      if (result.success) {
        // 检查本地订单状态是否为已支付
        if (result.data.local_status === 'paid' || result.data.remote_status === 'SUCCESS') {
          clearInterval(checkInterval);
          setCheckingPayment(false);
          setDownloadModalOpen(false);
          setPaymentUrl('');
          message.success('支付成功！开始下载...');
          // 重新尝试下载
          await downloadWork(id, `${workData.title}.jpg`);
        }
      }
    }, 3000); // 每3秒检查一次

    // 5分钟后停止检查
    setTimeout(() => {
      clearInterval(checkInterval);
      setCheckingPayment(false);
    }, 300000);
  };

  const handleModalClose = () => {
    setDownloadModalOpen(false);
    setPaymentUrl('');
    setOrderNumber('');
    setCheckingPayment(false);
  };

  // 生成作品编号：半年前日期 + 当前时分秒 + 作品ID
  const generateWorkNumber = (workId) => {
    const now = new Date();
    const sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000); // 半年前
    const datePart = sixMonthsAgo.toISOString().slice(0, 10).replace(/-/g, ''); // YYYYMMDD
    const timePart = now.toTimeString().slice(0, 8).replace(/:/g, ''); // HHMMSS
    return `${datePart}${timePart}${workId}`;
  };

  const handleShare = () => {
    navigator.clipboard.writeText(window.location.href);
    message.success('链接已复制到剪贴板');
  };

  const copyWorkId = () => {
    const fullWorkNumber = generateWorkNumber(workData?.id || 0);
    navigator.clipboard.writeText(fullWorkNumber);
    message.success('编号已复制');
  };

  if (loading) {
    return (
      <div className="work-detail-page">
        <Header />
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
          <Spin size="large" tip="加载中..." />
        </div>
        <Footer />
      </div>
    );
  }

  if (!workData) {
    return (
      <div className="work-detail-page">
        <Header />
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '60vh' }}>
          <p>作品不存在</p>
        </div>
        <Footer />
      </div>
    );
  }

  // 解析标签
  const tags = workData.tags ? (typeof workData.tags === 'string' ? JSON.parse(workData.tags) : workData.tags) : [];

  return (
    <div className="work-detail-page">
      <Header />
      
      <div className="work-detail-container">
        {/* 面包屑导航 */}
        <div className="breadcrumb">
          <a onClick={() => navigate('/')}>首页</a>
          <span> / </span>
          <span className="current">{workData.title}</span>
        </div>

        <div className="work-detail-content">
          {/* 左侧：作品展示 */}
          <div className="work-main">
            <div className="work-image-wrapper">
              <img 
                src={workData.watermarked_image ? `${API_CONFIG.baseURL}${workData.watermarked_image}` : getImageUrl(id)} 
                alt={workData.title} 
                className="work-image" 
              />
              
              {/* 相关搜索标签 */}
              <div className="related-tags">
                <h4>相关搜索</h4>
                <div className="tags-list">
                  {tags.map((tag, index) => (
                    <Tag key={index} className="work-tag">{tag}</Tag>
                  ))}
                </div>
              </div>

              {/* 猜你喜欢 */}
              <div className="related-works">
                <h3>猜你喜欢</h3>
                <div className="related-works-grid">
                  {relatedWorks.map(work => (
                    <div key={work.id} className="related-work-card" onClick={() => navigate(`/detail/${work.id}`)}>
                      <div className="related-work-image">
                        <img src={work.image} alt={work.title} />
                        <div className="related-work-overlay">
                          <Button type="primary" size="small" icon={<DownloadOutlined />}>
                            源文件下载
                          </Button>
                        </div>
                      </div>
                      <div className="related-work-info">
                        <h4>{work.title}</h4>
                        <div className="related-work-designer">
                          <span className="designer-level">Lv.{work.level}</span>
                          <span className="designer-level-name">{work.levelName}</span>
                          <p className="designer-name">{work.designer}</p>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </div>

          {/* 右侧：作品信息 */}
          <div className="work-sidebar">
            {/* 编号和复制 */}
            <div className="work-id-section">
              <span className="work-id">{generateWorkNumber(workData.id)}</span>
              <Button type="link" size="small" onClick={copyWorkId}>复制</Button>
            </div>

            {/* 作品标题 */}
            <h1 className="work-title">{workData.title}</h1>

            {/* 作品信息 */}
            <div className="work-info-list">
              <div className="work-info-item">
                <span className="info-label">分类</span>
                <span className="info-value">{workData.category}</span>
              </div>
              <div className="work-info-item">
                <span className="info-label">设计师</span>
                <span className="info-value">{workData.designer}</span>
              </div>
              <div className="work-info-item">
                <span className="info-label">等级</span>
                <span className="info-value">Lv.{workData.level} {workData.level_text}</span>
              </div>
              <div className="work-info-item">
                <span className="info-label">价格</span>
                <span className="info-value" style={{ color: '#ff5a5a', fontWeight: 'bold' }}>¥{workData.price}</span>
              </div>
            </div>

            {/* 操作按钮 */}
            <div className="work-actions">
              <Button 
                type="primary" 
                size="large" 
                block 
                icon={<DownloadOutlined />}
                onClick={handleDownload}
                className="download-btn"
              >
                我要下载
              </Button>
              <Button 
                size="large" 
                icon={collected ? <HeartFilled /> : <HeartOutlined />}
                onClick={handleCollect}
                className={`collect-btn ${collected ? 'collected' : ''}`}
              />
              <Button 
                size="large" 
                icon={<ShareAltOutlined />}
                onClick={handleShare}
                className="share-btn"
              />
            </div>

            {/* 设计师信息 */}
            <div className="designer-card">
              <div className="designer-header">
                <div className="designer-avatar">
                  <img src={`https://api.dicebear.com/7.x/avataaars/svg?seed=${workData.designer}`} alt={workData.designer} />
                </div>
                <div className="designer-info">
                  <div className="designer-name-level">
                    <span className="designer-level-badge">Lv.{workData.level}</span>
                    <span className="designer-level-text">{workData.level_text}</span>
                  </div>
                  <h3 className="designer-name">{workData.designer}</h3>
                </div>
              </div>
              
              <div className="designer-stats">
                <div className="stat-item">
                  <span className="stat-value">-</span>
                  <span className="stat-label">作品</span>
                </div>
                <div className="stat-item">
                  <span className="stat-value">-</span>
                  <span className="stat-label">粉丝</span>
                </div>
              </div>

              <Button 
                type="primary" 
                block 
                icon={<PlusOutlined />}
                onClick={handleFollow}
                className={`follow-btn ${followed ? 'followed' : ''}`}
              >
                {followed ? '已关注' : '关注'}
              </Button>
            </div>

            {/* 搜索画板 */}
            <div className="board-search">
              <h4>搜索画板</h4>
              <Input 
                placeholder="搜索画板" 
                prefix={<SearchOutlined />}
                className="board-search-input"
              />
            </div>

            {/* 浏览统计 */}
            <div className="work-stats">
              <div className="stat-item">
                <EyeOutlined />
                <span>{workData.views} 浏览</span>
              </div>
              <div className="stat-item">
                <HeartOutlined />
                <span>{workData.collects} 收藏</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 购买确认弹窗 */}
      <Modal
        title={paymentUrl ? "扫码支付" : "购买作品"}
        open={downloadModalOpen}
        onOk={paymentUrl ? null : confirmDownload}
        onCancel={handleModalClose}
        okText="确定购买"
        cancelText={paymentUrl ? "关闭" : "取消"}
        centered
        confirmLoading={purchasing}
        footer={paymentUrl ? [
          <Button key="close" onClick={handleModalClose}>
            关闭
          </Button>
        ] : undefined}
        width={paymentUrl ? 450 : 416}
      >
        {!paymentUrl ? (
          <div>
            <p>作品：{workData.title}</p>
            <p>价格：<span style={{ color: '#ff5a5a', fontSize: '18px', fontWeight: 'bold' }}>¥{workData.price}</span></p>
            <p style={{ color: '#999', fontSize: '12px' }}>点击确定后将生成支付二维码</p>
          </div>
        ) : (
          <div style={{ textAlign: 'center', padding: '20px 0' }}>
            <div style={{ 
              background: '#fff', 
              padding: '20px', 
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              display: 'inline-block'
            }}>
              <QRCodeSVG 
                value={paymentUrl} 
                size={200}
                level="H"
                includeMargin={true}
              />
            </div>
            <p style={{ marginTop: '20px', fontSize: '16px', fontWeight: 'bold' }}>
              订单金额：<span style={{ color: '#ff5a5a' }}>¥{workData.price}</span>
            </p>
            <p style={{ color: '#666', fontSize: '14px' }}>
              请使用微信或支付宝扫码支付
            </p>
            {checkingPayment && (
              <div style={{ marginTop: '15px' }}>
                <Spin size="small" />
                <span style={{ marginLeft: '10px', color: '#1890ff' }}>等待支付中...</span>
              </div>
            )}
            <p style={{ color: '#999', fontSize: '12px', marginTop: '15px' }}>
              订单号：{orderNumber}
            </p>
            <p style={{ color: '#999', fontSize: '12px' }}>
              支付完成后将自动开始下载
            </p>
          </div>
        )}
      </Modal>

      <Footer />
    </div>
  );
};

export default WorkDetail;
