import React, { useState } from 'react';
import { Modal, Descriptions, Space, Button, Tooltip, message, Table } from 'antd';
import { GzhPlanDataType, GzhPlanType } from '../../hooks/useGzhPlanList';
import { CopyOutlined, PlayCircleOutlined, DownloadOutlined, LinkOutlined, QrcodeOutlined } from '@ant-design/icons';
import { VideoItem } from '../types';
import VideoPlayModal from '@src/views/publishContent/weCom/components/videoPlayModal';
import modal from 'antd/es/modal';
import http from '@src/http';
import { getShareQrPic } from '@src/http/api';
import copy from 'copy-to-clipboard';
import { Typography } from 'antd';
const { Text } = Typography;
interface PunlishPlanDetailModalProps {
  visible: boolean;
  onCancel: () => void;
  planData: GzhPlanDataType;
}

const PunlishPlanDetailModal: React.FC<PunlishPlanDetailModalProps> = ({
  visible,
  onCancel,
  planData,
}) => {
	const [isVideoPlayModalVisible, setIsVideoPlayModalVisible] = useState(false);
	const [activeVideo, setActiveVideo] = useState<VideoItem | null>(null);

	const columns = [
    {
      title: '视频标题',
      dataIndex: 'title',
      key: 'title',
      render: (title: string) => (
        <Space>
          <Text style={{ maxWidth: 200 }} ellipsis={{ tooltip: title }}>{title}</Text>
          <Tooltip title="复制标题">
            <Button
              type="text"
              icon={<CopyOutlined />}
              onClick={() => {
                if (copy(title)) {
                  message.success('标题已复制');
                } else {
                  message.error('复制失败');
                }
              }}
              size="small"
            />
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '操作',
      key: 'action',
      render: (_: any, record: VideoItem) => (
        <Space wrap size="small">
          <Button type="link" icon={<PlayCircleOutlined />} onClick={() => playVideo(record)} size="small">播放</Button>
          <Button type="link" icon={<DownloadOutlined />} onClick={() => downloadCover(record)} size="small">下载封面</Button>
          <Button type="link" icon={<LinkOutlined />} onClick={() => copyPushLink(record)} size="small">复制推送链接</Button>
          <Button type="link" icon={<QrcodeOutlined />} onClick={() => showQRCode(record)} size="small">二维码</Button>
        </Space>
      ),
    },
	];
	const playVideo = (video: VideoItem) => {
		setActiveVideo(video);
		setIsVideoPlayModalVisible(true);
	};

	const downloadCover = (video: VideoItem) => {
		if (video.cover) {
			const link = document.createElement('a');
			link.href = video.cover;
			// Attempt to infer filename, might need refinement
			const filename = video.cover.substring(video.cover.lastIndexOf('/') + 1) || `cover_${video.videoId}.jpg`;
			link.download = filename;
			link.target = '_blank'; // Open in new tab might be safer for some browsers
			link.rel = 'noopener noreferrer';
			document.body.appendChild(link);
			link.click();
			document.body.removeChild(link);
		} else {
			message.warning('No cover image URL available.');
		}
	};
	
	const copyPushLink = (video: VideoItem) => {
		// Assuming video object might have a 'pushLink' property added by the parent component
		const linkToCopy = video.pageUrl || 'Push link not available'; // Updated placeholder
		if (video.pageUrl && copy(linkToCopy)) {
			message.success('推送链接已复制');
		} else if (!video.pageUrl) {
			message.warning('没有可复制的推送链接');
		} else {
			message.error('复制失败');
		}
	};
	
	const showQRCode = (video: VideoItem) => {
		http.get<string>(getShareQrPic, {
			params: {
				pageUrl: video.pageUrl,
			}
		}).then(res => {
			modal.info({
				title: '二维码',
				content: <img src={res.data} alt="二维码" />,
			});
		}).catch(err => {
			message.error(err.msg || '获取二维码失败');
		});
	};

  return (
    planData && visible && <Modal
      title="发布计划详情"
			open={true}
			destroyOnClose
      onCancel={onCancel}
      footer={null}
      width={800}
    >
			<Descriptions column={1} className='mb-4'>
				<Descriptions.Item label="发布计划类型">{planData.type.toString() === GzhPlanType.自动回复 ? '自动回复' : '服务号推送'}</Descriptions.Item>
				{ planData.type.toString() === GzhPlanType.自动回复 && <Descriptions.Item label="场景">关注回复</Descriptions.Item> }
				<Descriptions.Item label="发布方式">{planData?.publishStage === 0 ? '平台发布' : '用户获取路径'}</Descriptions.Item>
				<Descriptions.Item label="视频选取方式">{planData?.selectVideoType === 0 ? '手动选取' : '自动选取'}</Descriptions.Item>
        <Descriptions.Item label="公众号名称">{planData.accountName}</Descriptions.Item>
				{ 
					planData.videoList?.length > 0 ?
						<Descriptions.Item label="发布内容" >
							<Table
								columns={columns}
								dataSource={planData.videoList?.map(v => ({ ...v, key: v.videoId }))} // Ensure each item has a unique key
								pagination={false} // Disable pagination if the list is expected to be short
								size="small"
							/>
							<VideoPlayModal
								visible={isVideoPlayModalVisible}
								onClose={() => setIsVideoPlayModalVisible(false)}
								videoUrl={activeVideo?.video || ''}
								title={activeVideo?.title || ''}
							/>
						</Descriptions.Item>
						: <Descriptions.Item label="发布内容">
							<Text className='text-gray-500'>视频由系统自动选取</Text>
						</Descriptions.Item>
				}
			</Descriptions>
    </Modal>
  );
};

export default PunlishPlanDetailModal; 
