import React, { useEffect, useState } from 'react';
import { Modal, Button, Descriptions, Image, Space, Tooltip, message, Typography } from 'antd';
import { CopyOutlined, PlayCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import { WeComPlan, WeComPlanType } from '@src/views/publishContent/weCom/type';
import copy from 'copy-to-clipboard';
import VideoPlayModal from '../videoPlayModal';
import { getShareQrPic } from '@src/http/api';
import http from '@src/http';

const { Text } = Typography;

interface PlanDetailModalProps {
  visible: boolean;
  onClose: () => void;
  planData: WeComPlan | null | undefined; 
}

const PlanDetailModal: React.FC<PlanDetailModalProps> = ({ visible, onClose, planData }) => {
	const [isVideoPlayModalVisible, setIsVideoPlayModalVisible] = useState<boolean>(false);
	const [qrCode, setQrCode] = useState<string>('');
	
	useEffect(() => {
		if (planData?.pageUrl) {
			getShareQr(planData?.pageUrl || '');
		}
	}, [planData]);

  if (!planData) {
    return null; // Don't render if no data
	}

	
	
	const getShareQr = (pageUrl: string) => {
		http.get<string>(getShareQrPic, {
			params: {
				pageUrl,
			}
		}).then(res => {
			setQrCode(res.data);
		}).catch(err => {
			message.error(err.msg || '获取二维码失败');
		});
		
	};

  const handleCopy = (text: string | undefined, successMessage: string) => {
    if (text && copy(text)) {
      message.success(successMessage);
    } else if (!text) {
      message.warning('没有内容可复制');
    } else {
      message.error('复制失败');
    }
  };

  const downloadFile = (url: string | undefined, filename: string) => {
    if (!url) {
      message.warning('无可用文件下载');
      return;
    }
    const link = document.createElement('a');
    link.href = url;
    link.download = filename || url.substring(url.lastIndexOf('/') + 1);
    link.target = '_blank';
    link.rel = 'noopener noreferrer';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    message.success('开始下载...');
  };

  const playVideo = () => {
    setIsVideoPlayModalVisible(true);
  }

  // Determine scene text based on plan type (adjust logic if needed)
  const getSceneText = (plan: WeComPlan) => {
    if (plan.type === +WeComPlanType.社群) {
      return plan.scene === 0 ? '群发' : '单发';
    }
    // Add logic for other plan types if necessary
    return '自动回复'; // Example placeholder for other types
  }
  
  // Determine publish type text (adjust based on your data model)
  const getPublishTypeText = (plan: WeComPlan) => {
     // This field isn't directly in WeComPlan, you might need to fetch/derive it
     // Returning a placeholder for now.
     return plan.type === +WeComPlanType.社群 ? '社群' : '自动回复'; // Example
  }
  
  // Determine account type text (adjust based on your data model)
  const getAccountTypeText = () => {
    // This field isn't in WeComPlan, returning placeholder.
    return '小慧爱厨房'; // Placeholder based on image
  }

  // Determine account name text (adjust based on your data model)
  const getAccountNameText = () => {
      // This field isn't in WeComPlan, returning placeholder.
      return '企微号'; // Placeholder based on image
  }

  return (
    <Modal
      title="内容详情"
      open={visible}
      onCancel={onClose}
      footer={[
        <Button key="close" type="primary" onClick={onClose}>
          关闭
        </Button>,
      ]}
      width={650} // Adjust width as needed
      destroyOnClose
    >
      <Descriptions bordered column={1} size="small" labelStyle={{ width: '120px' }}>
        <Descriptions.Item label="链接ID">{planData.id}</Descriptions.Item>
        {/* Placeholder fields based on image - replace with actual data source if available */}
        <Descriptions.Item label="发布账号类型">{getAccountTypeText()}</Descriptions.Item>
        <Descriptions.Item label="公众号名称">{getAccountNameText()}</Descriptions.Item>
        <Descriptions.Item label="发布场景">{getPublishTypeText(planData)}</Descriptions.Item>

        <Descriptions.Item label="场景">{getSceneText(planData)}</Descriptions.Item>
        <Descriptions.Item label="推送链接">
          <Space>
            <Text style={{ maxWidth: 350 }} ellipsis={{ tooltip: planData.pageUrl }}>
              {planData.pageUrl}
            </Text>
            <Tooltip title="复制链接">
              <Button
                type="text"
                icon={<CopyOutlined />}
                onClick={() => handleCopy(planData.pageUrl, '推送链接已复制')}
                size="small"
              />
            </Tooltip>
          </Space>
        </Descriptions.Item>
        <Descriptions.Item label="视频标题">
          <Space>
            <Text style={{ maxWidth: 400 }} ellipsis={{ tooltip: planData.title }}>
                {planData.title}
            </Text>
            <Tooltip title="复制标题">
              <Button
                type="text"
                icon={<CopyOutlined />}
                onClick={() => handleCopy(planData.title, '标题已复制')}
                size="small"
              />
            </Tooltip>
          </Space>
        </Descriptions.Item>
        <Descriptions.Item label="视频封面">
          <Space direction="vertical" align="start">
            <Image 
              width={150} 
              src={planData.cover} 
              alt="视频封面" 
              referrerPolicy="no-referrer" 
              placeholder={ <div style={{ width: 150, height: 100, background: '#f0f0f0', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>加载中...</div> }
             />
            <Button 
              type="link" 
              icon={<DownloadOutlined />} 
              onClick={() => downloadFile(planData.cover, planData.title + '_cover.jpg')} 
              size="small"
            >
              下载封面
            </Button>
          </Space>
        </Descriptions.Item>
        <Descriptions.Item label="二维码">
          {qrCode ? (
             <Space direction="vertical" align="start">
                 <img style={{ width: 150, height: 150 }} src={qrCode} alt="二维码" />
                 {/* You might want to add a logo overlay if needed */}
             </Space>
          ) : (
            <Text type="secondary">无可用链接生成二维码</Text>
          )}
        </Descriptions.Item>
        <Descriptions.Item label="视频内容">
          <Button type="link" icon={<PlayCircleOutlined />} onClick={playVideo} size="small">播放</Button>
        </Descriptions.Item>
			</Descriptions>
			<VideoPlayModal
				visible={isVideoPlayModalVisible}
				onClose={() => setIsVideoPlayModalVisible(false)}
				videoUrl={planData.video || ''}
				title={planData.title || ''}
			/>
    </Modal>
  );
};

export default PlanDetailModal; 
