import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Button, Drawer, Input, Modal, Popconfirm, Spin, Table, Tag, Tooltip, Upload, message } from 'antd';
import { ArrowLeftOutlined, PlusOutlined, XOutlined } from '@ant-design/icons';
import { createRemoveLens, getShotReplicationDetail, Removelist, removeCreate, splitCustom, uploadImage } from '../api';
import VideoTrimPicker from '../components/VideoTrimPicker';

const { TextArea } = Input;

const API_BASE = import.meta.env.VITE_API_BASE || 'http://localhost:8000';
const MIN_TRIM_SECONDS = 2;
const MAX_TRIM_SECONDS = 15;

function buildAssetUrl(url?: string): string {
    if (!url) return '';
    if (/^https?:\/\//i.test(url)) return url;
    return `${API_BASE}${url}`;
}

function RemoveInfo() {
    const { creatID } = useParams<{ creatID: string }>();
    const navigate = useNavigate();
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [trimModalVisible, setTrimModalVisible] = useState(false);
    const [currentSegment, setCurrentSegment] = useState<string | null>(null);
    const [currentSegmentName, setCurrentSegmentName] = useState<string | null>(null);
    const [previewVideoUrl, setPreviewVideoUrl] = useState<string | null>(null);
    const [previewModalVisible, setPreviewModalVisible] = useState(false);
    const previewVideoRef = useRef<HTMLVideoElement>(null);
    const [productName, setProductName] = useState('');
    const [productSellingPoint, setProductSellingPoint] = useState('');
    const [productImage, setProductImage] = useState('');
    const [taskDetail, setTaskDetail] = useState<any>(null);
    const [tableData, setTableData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);
    const [splitLoading, setSplitLoading] = useState(false);
    const [autoSplitLoading, setAutoSplitLoading] = useState(false);
    const pollingIntervalRef = useRef<number | null>(null);
    const analysisPollingRef = useRef<number | null>(null);

    const videoUrl = useMemo(() => buildAssetUrl(taskDetail?.videoUrl), [taskDetail?.videoUrl]);

    const autoSplitButtonText = useMemo(() => {
        if (tableData.length === 0) {
            return 'AI自动拆分';
        }
        if (tableData.some(item => item.sourceMode === 'ai_suggestion')) {
            return 'AI重拆';
        }
        return 'AI自动拆分';
    }, [tableData]);

    const fetchTaskDetail = useCallback(async () => {
        if (!creatID) return;
        try {
            const res = await getShotReplicationDetail(creatID);
            setTaskDetail(res);
        } catch {
            message.error('获取任务详情失败');
        }
    }, [creatID]);

    const fetchSegments = useCallback(async () => {
        if (!creatID) return;
        try {
            const res = await Removelist(creatID);
            const items = res.items || [];
            setTableData(items);

            // 检查是否需要开启轮询
            const needsPolling = items.some(
                (item: any) =>
                    item.moduleProjectCurrentStepCode !== 'video_generate' &&
                    item.moduleProjectStatus !== 'completed' &&
                    item.moduleProjectStatus !== 'failed'
            );

            if (needsPolling) {
                // 如果没有轮询在运行，则开启轮询
                if (!pollingIntervalRef.current) {
                    pollingIntervalRef.current = window.setInterval(async () => {
                        try {
                            const pollRes = await Removelist(creatID);
                            const pollItems = pollRes.items || [];

                            // 只更新未完成的项目
                            setTableData((prevData) =>
                                prevData.map((prevItem) => {
                                    const pollItem = pollItems.find((p: any) => p.id === prevItem.id);
                                    if (pollItem) {
                                        // 只有当原项目未完成时才更新
                                        if (
                                            prevItem.moduleProjectCurrentStepCode !== 'video_generate' ||
                                            (prevItem.moduleProjectStatus !== 'completed' && prevItem.moduleProjectStatus !== 'failed')
                                        ) {
                                            return pollItem;
                                        }
                                    }
                                    return prevItem;
                                })
                            );

                            // 检查是否所有项目都已完成
                            const allCompleted = pollItems.every(
                                (item: any) =>
                                    item.moduleProjectCurrentStepCode === 'video_generate' ||
                                    item.moduleProjectStatus === 'completed' ||
                                    item.moduleProjectStatus === 'failed'
                            );

                            if (allCompleted) {
                                // 停止轮询
                                if (pollingIntervalRef.current) {
                                    clearInterval(pollingIntervalRef.current);
                                    pollingIntervalRef.current = null;
                                }
                            }
                        } catch (error) {
                            console.error('轮询获取拆镜列表失败:', error);
                        }
                    }, 30000); // 30秒轮询
                }
            } else {
                // 如果不需要轮询，停止现有轮询
                if (pollingIntervalRef.current) {
                    clearInterval(pollingIntervalRef.current);
                    pollingIntervalRef.current = null;
                }
            }
        } catch {
            message.error('获取拆镜列表失败');
        }
    }, [creatID]);

    const refreshPageData = useCallback(async () => {
        await Promise.all([fetchTaskDetail(), fetchSegments()]);
    }, [fetchTaskDetail, fetchSegments]);

    useEffect(() => {
        refreshPageData();

        return () => {
            if (pollingIntervalRef.current) {
                clearInterval(pollingIntervalRef.current);
                pollingIntervalRef.current = null;
            }
            if (analysisPollingRef.current) {
                clearInterval(analysisPollingRef.current);
                analysisPollingRef.current = null;
            }
        };
    }, [refreshPageData]);

    useEffect(() => {
        if (!taskDetail) return;

        if (taskDetail.analysisStatus === 'processing') {
            console.log("开始轮询");
            
            analysisPollingRef.current = window.setInterval(async () => {
                try {
                    const res = await getShotReplicationDetail(creatID);
                    setTaskDetail(res);
                } catch {
                }
            }, 3000);
        } else {
            if (analysisPollingRef.current) {
                clearInterval(analysisPollingRef.current);
                analysisPollingRef.current = null;
            }
        }

        return () => {
            if (analysisPollingRef.current) {
                clearInterval(analysisPollingRef.current);
                analysisPollingRef.current = null;
            }
        };
    }, [taskDetail?.analysisStatus, creatID]);

    const handleGenerate = (segmentId: string, segmentName: string) => {
        setCurrentSegment(segmentId);
        setCurrentSegmentName(segmentName);
        setDrawerVisible(true);
    };

    const handleCloseDrawer = () => {
        setDrawerVisible(false);
        setCurrentSegment(null);
        setProductName('');
        setCurrentSegmentName('');
        setProductSellingPoint('');
        setProductImage('');
    };

    const handleProductImageChange: any = (info: any) => {
        if (info.fileList.length === 0) {
            setProductImage('');
        }
    };

    const beforeUploadProductImage = async (file: File) => {
        try {
            const uploadResult = await uploadImage(file);
            setProductImage(uploadResult.url);
            message.success('图片上传成功');
        } catch {
            message.error('图片上传失败，请重试');
        }
        return false;
    };

    const handleManualGenerate = async () => {
        if (!currentSegment) {
            message.warning('请先选择拆镜片段');
            return;
        }
        if (!productImage) {
            message.warning('请上传产品图');
            return;
        }
        if (!productName.trim()) {
            message.warning('请输入产品名称');
            return;
        }
        if (!productSellingPoint.trim()) {
            message.warning('请输入产品卖点');
            return;
        }

        
        const params = {
                target_project_name: productName.trim(),
                core_content_point: productSellingPoint.trim(),
                material_image_url: buildAssetUrl(productImage),
                idempotency_key: `replication_${Date.now()}`,
            };
        console.log(currentSegment,params);


        setLoading(true);
        try {
            await removeCreate(currentSegment, params);
            message.success('视频生成任务创建成功');
            handleCloseDrawer();
            Removelist(creatID).then((res: any) => {
                console.log('123123123123',res);
                
                 const targetItem = res.items.find((item: any) => item.id === currentSegment);
            console.log(targetItem);
                          message.loading('创建中...', 3);
            
            setTimeout(() => {
                    navigate(`/removelens/${targetItem.moduleProjectId}/removefenbu`);
                }, 3000);
            });
            //  fetchSegments().then((res: any) => {
            //     console.log('123123123123',res);
                
            //     //  const targetItem = res.items.find((item: any) => item.id === currentSegment);
            // // console.log(targetItem);
            // });

           
            
            // if (targetItem?.moduleProjectId) {
            //     message.loading('跳转中...', 1.5);
            //     
            // }
        } catch (err: any) {
            message.error(err?.message || '创建失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    const handleAutoGenerate = async () => {
        if (!creatID) return;
        setAutoSplitLoading(true);
        try {
            const shouldReplace = tableData.some(item => item.sourceMode === 'ai_suggestion');
            await createRemoveLens(creatID, {
                selected_indices: [],
                replace_existing: shouldReplace,
            });
            message.success(shouldReplace ? 'AI 重拆任务已提交' : 'AI 拆镜任务已提交');
            await refreshPageData();
        } catch (error: any) {
            message.error(error?.message || '拆镜失败');
        } finally {
            setAutoSplitLoading(false);
        }
    };

    const handleOpenTrimModal = () => {
        if (!videoUrl) {
            message.warning('原视频地址不存在');
            return;
        }
        setTrimModalVisible(true);
    };

    const handleCustomSplit = async (range: { startSecond: number; endSecond: number; durationSecond: number }) => {
        if (!creatID) return;
        if (range.durationSecond < MIN_TRIM_SECONDS) {
            message.warning(`拆镜片段不能低于 ${MIN_TRIM_SECONDS} 秒`);
            return;
        }
        if (range.durationSecond > MAX_TRIM_SECONDS) {
            message.warning(`拆镜片段不能超过 ${MAX_TRIM_SECONDS} 秒`);
            return;
        }

        setSplitLoading(true);
        try {
            await splitCustom(creatID, {
                start_second: range.startSecond,
                end_second: range.endSecond,
            });
            message.success('手动拆镜任务已提交');
            setTrimModalVisible(false);
            await refreshPageData();
        } catch (error: any) {
            message.error(error?.message || '手动拆镜失败');
        } finally {
            setSplitLoading(false);
        }
    };

    const canCreateReplication = (record: any) => {
        return record?.splitStatus === 'completed' && !!record?.segmentVideoUrl;
    };

    const columns: any[] = [
        {
            title: '片段',
            width: 100,
            fixed: 'left',
            align: 'center' as const,
            render: (_: any, record: any) => (
                <div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: '#333' }}>{record.segmentName || `片段${record.segmentIndex || ''}`}</div>
                    <div style={{ fontSize: 12, color: '#999' }}>{record.timeNode}</div>
                    {record.sourceMode === 'custom' && <Tag color="blue" style={{ marginTop: 6 }}>手动</Tag>}
                    {record.sourceMode === 'ai_suggestion' && <Tag color="orange" style={{ marginTop: 6 }}>自动</Tag>}

                </div>
            ),
        },
        {
            title: '片段视频',
            width: 150,
            align: 'center' as const,
            render: (_: any, record: any) => (
                <div style={{ position: 'relative', width: 120, height: 80, borderRadius: 6, overflow: 'hidden', background: '#f1f5f9', cursor: 'pointer' }}
                    onClick={() => {
                        console.log('video clicked:', record.segmentVideoUrl);
                        if (record.segmentVideoUrl) {
                            setPreviewVideoUrl(buildAssetUrl(record.segmentVideoUrl));
                            setPreviewModalVisible(true);
                        }
                    }}>
                    {record.segmentVideoUrl ? (
                        <>
                            <video
                                src={buildAssetUrl(record.segmentVideoUrl)}
                                style={{ width: '100%', height: '100%', objectFit: 'cover', pointerEvents: 'none' }}
                            />
                            <div style={{ position: 'absolute', top: 0, left: 0, right: 0, bottom: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'rgba(0,0,0,0.3)' }}>
                                <div style={{ width: 32, height: 32, borderRadius: '50%', background: 'rgba(255,255,255,0.9)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                                    <div style={{ width: 0, height: 0, borderTop: '8px solid transparent', borderBottom: '8px solid transparent', borderLeft: '14px solid #6366f1', marginLeft: 2 }} />
                                </div>
                            </div>
                        </>
                    ) : (
                        <div style={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#94a3b8', fontSize: 12 }}>
                            {record.splitStatus === 'failed' ? '切割失败' : '切割中'}
                        </div>
                    )}
                </div>
            ),
        },
        {
            title: '视频内容',
            width: 500,
            align: 'left' as const,
            render: (_: any, record: any) => {
          
                
                // AI建议的片段直接显示内容，不经过分析状态判断
                if (record.source_mode === 'ai_suggestion' || record.sourceMode === 'ai_suggestion') {
                    return <div style={{ fontSize: 14, color: '#333', lineHeight: 1.6 }}>{record.segmentContent || record.lastError || '-'}</div>;
                }
                
                const analysisStatus = record.analysis_status || record.analysisStatus;
                const statusMap: Record<string, string> = {
                    'not_required': '无需单独分析',
                    'pending': '等待分析',
                    'processing': '分析中',
                    'failed': '分析失败',
                };
                
                if (analysisStatus === 'processing') {
                    return (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                            <Spin size="small" />
                            <span style={{ fontSize: 14, color: '#f59e0b' }}>分析中</span>
                        </div>
                    );
                }
                
                if (analysisStatus === 'failed') {
                    return <div style={{ fontSize: 14, color: '#ef4444', lineHeight: 1.6 }}>分析失败</div>;
                }
                
                const displayText = analysisStatus && statusMap[analysisStatus] ? statusMap[analysisStatus] : (record.segmentContent || record.lastError || '-');
                return <div style={{ fontSize: 14, color: '#333', lineHeight: 1.6 }}>{displayText}</div>;
            },
        },
        {
            title: '视频类型',
            width: 120,
            align: 'center' as const,
            render: (_: any, record: any) => (
                <div style={{ fontSize: 14, color: '#333', fontWeight: 500 }}>
                    {record.segmentCategory || '-'}
                </div>
            ),
        },
        {
            title: '状态',
            width: 120,
            align: 'center' as const,
            dataIndex: 'moduleProjectStatus',
             render: (text: string, record: any) => {
                  const status = text;
                  const currentStepCode = record.moduleProjectCurrentStepCode || record.currentStepCode;
                  
                  const getStatusText = () => {
                    if (currentStepCode === 'image_prompt_optimize') {
                      switch (status) {
                        case 'waiting_user':
                          return { text: '等待融合图生成', color: '#f59e0b' };
                        case 'processing':
                          return { text: '图片提示词生成中', color: '#f59e0b' };
                        case 'completed':
                          return { text: '图片提示词生成成功', color: '#10b981' };
                        case 'failed':
                          return { text: '图片提示词生成失败', color: '#ef4444' };
                        default:
                          return { text: status || '-', color: '#666' };
                      }
                    } else if (currentStepCode === 'image_generate') {
                      switch (status) {
                        case 'waiting_user':
                          return { text: '等待生成视频提示词', color: '#f59e0b' };
                        case 'processing':
                          return { text: '融合图生成中', color: '#f59e0b' };
                        case 'completed':
                          return { text: '融合图生成成功', color: '#10b981' };
                        case 'failed':
                          return { text: '融合图生成失败', color: '#ef4444' };
                        default:
                          return status || '-';
                      }
                    } else if (currentStepCode === 'video_prompt_optimize') {
                      switch (status) {
                        case 'waiting_user':
                          return { text: '等待最终视频生成', color: '#f59e0b' };
                        case 'processing':
                          return { text: '视频提示词生成中', color: '#f59e0b' };
                        case 'completed':
                          return { text: '视频提示词生成成功', color: '#10b981' };
                        case 'failed':
                          return { text: '视频提示词生成失败', color: '#ef4444' };
                        default:
                          return { text: status || '-', color: '#666' };
                      }
                    } else if (currentStepCode === 'video_generate') {
                      switch (status) {
                        case 'waiting_user':
                          return { text: '', color: '#666' };
                        case 'processing':
                          return { text: '最终视频生成中', color: '#f59e0b' };
                        case 'completed':
                          return { text: '任务完成', color: '#10b981' };
                        case 'failed':
                          return { text: '最终视频生成失败', color: '#ef4444' };
                        default:
                          return { text: status || '-', color: '#666' };
                      }
                    } else if (currentStepCode === 'material_input') {
                      switch (status) {
                        case 'waiting_user':
                          return { text: '等待生成图片提示词', color: '#f59e0b' };
                        case 'processing':
                          return { text: '素材处理中', color: '#f59e0b' };
                        case 'completed':
                          return { text: '素材上传成功', color: '#10b981' };
                        case 'failed':
                          return { text: '素材上传失败', color: '#ef4444' };
                        default:
                          return { text: status || '-', color: '#666' };
                      }
                    } else {
                      if (!record.moduleProjectId) {
                        return { text: '待生成任务', color: '#94a3b8' };
                      }
                      const statusMap: Record<string, { text: string; color: string }> = {
                        'pending': { text: '子任务待处理', color: '#f59e0b' },
                        'waiting_user': { text: '等待用户确认或触发', color: '#f59e0b' },
                        'processing': { text: '子任务处理中', color: '#f59e0b' },
                        'completed': { text: '子任务完成', color: '#10b981' },
                        'failed': { text: '子任务失败', color: '#ef4444' },
                        'cancelled': { text: '子任务取消', color: '#94a3b8' },
                      };
                      const result = statusMap[status] || { text: status || '-', color: '#666' };
                      return result;
                    }
                  };
                  
                  const result = getStatusText() as { text: string; color: string };
                  if (typeof result === 'string') {
                    return <span style={{ fontSize: 12, color: '#666', fontWeight: 500 }}>{result}</span>;
                  }
                  return <span style={{ fontSize: 12, color: result.color, fontWeight: 500 }}>{result.text}</span>;
                },
            

            // render: (_: any, record: any) => {
            //     const statusMap: Record<string, { text: string; color: string }> = {
            //         pending: { text: '待切割', color: 'default' },
            //         processing: { text: '切割中', color: 'processing' },
            //         retry_waiting: { text: '等待重试', color: 'warning' },
            //         completed: { text: '已完成', color: 'success' },
            //         failed: { text: '失败', color: 'error' },
            //     };
            //     const item = statusMap[record.splitStatus] || { text: record.splitStatus || '-', color: 'default' };
            //     return <Tag color={item.color}>{item.text}</Tag>;
            // },
        },
        {
            title: '操作',
            width: 140,
            fixed: 'right',
            align: 'center' as const,
            render: (_: any, record: any) => (
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                    {record.moduleProjectId ? (
                        <Button
                            type="text"
                            onClick={() => navigate(`/removelens/${record.moduleProjectId}/removefenbu`)}
                            style={{ color: '#10b981', fontSize: 12, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}
                        >
                            详情任务
                        </Button>
                    ) : (
                        <Button
                            type="text"
                            onClick={() => handleGenerate(String(record.id), record.segmentName)}
                            disabled={!canCreateReplication(record)}
                            style={{ color: canCreateReplication(record) ? '#f59e0b' : '#94a3b8', fontSize: 12, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}
                        >
                            {canCreateReplication(record) ? '视频生成' : '待切割完成'}
                        </Button>
                    )}
                </div>
            ),
        },
    ];

    return (
        <>
            <div
                style={{
                    margin: '-24px -32px -32px',
                    borderRadius: 20,
                    minHeight: 'calc(100vh - 34px)',
                    display: 'flex',
                    flexDirection: 'column',
                    overflow: 'hidden',
                    background: 'linear-gradient(135deg, #f8fafc 0%, #eef2ff 50%, #f0f9ff 100%)',
                    position: 'relative',
                }}
            >
                {/* 背景装饰 */}
                <div style={{ position: 'absolute', top: -100, right: -100, width: 300, height: 300, background: 'radial-gradient(circle, rgba(99,102,241,0.08) 0%, transparent 70%)', borderRadius: '50%' }} />
                <div style={{ position: 'absolute', bottom: -100, left: -100, width: 300, height: 300, background: 'radial-gradient(circle, rgba(167,139,250,0.08) 0%, transparent 70%)', borderRadius: '50%' }} />

                {/* 标题栏 */}
                <div style={{ padding: '20px 32px', display: 'flex', alignItems: 'center', gap: 16, position: 'relative', zIndex: 10 }}>
                    <Button
                        type="text"
                        icon={<ArrowLeftOutlined />}
                        onClick={() => navigate(-1)}
                        style={{ 
                            fontSize: 16, 
                            color: '#6366f1',
                            background: 'rgba(99, 102, 241, 0.1)',
                            borderRadius: 12,
                            padding: '8px 16px',
                            transition: 'all 0.2s ease',
                        }}
                        onMouseEnter={(e) => {
                            e.currentTarget.style.background = 'rgba(99, 102, 241, 0.15)';
                        }}
                        onMouseLeave={(e) => {
                            e.currentTarget.style.background = 'rgba(99, 102, 241, 0.1)';
                        }}
                    />
                    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
                            <div style={{ width: 40, height: 2, background: 'linear-gradient(90deg, transparent, #6366f1, #8b5cf6, transparent)', borderRadius: 1 }} />
                            <h1 style={{ fontSize: 22, fontWeight: 700, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent', margin: 0 }}>
                                AI视频拆镜工作台
                            </h1>
                            <div style={{ width: 40, height: 2, background: 'linear-gradient(90deg, transparent, #8b5cf6, #6366f1, transparent)', borderRadius: 1 }} />
                        </div>
                    </div>
                </div>

                {taskDetail ? (
                    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', overflow: 'hidden', padding: '0 32px 32px' }}>
                        {/* 视频总结卡片 */}
                        <div 
                            style={{ 
                                flex: 1, 
                                background: 'linear-gradient(135deg, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0.6) 100%)', 
                                backdropFilter: 'blur(20px)',
                                borderRadius: 20, 
                                display: 'flex', 
                                alignItems: 'center', 
                                gap: 30,
                                padding: 24,
                                border: '1px solid rgba(99, 102, 241, 0.1)',
                                boxShadow: '0 8px 32px rgba(99, 102, 241, 0.08), inset 0 1px 0 rgba(255, 255, 255, 0.8)',
                                position: 'relative',
                                overflow: 'hidden',
                            }}
                        >
                            {/* 卡片装饰 */}
                            <div style={{ position: 'absolute', top: -50, right: -50, width: 200, height: 200, background: 'radial-gradient(circle, rgba(99,102,241,0.05) 0%, transparent 70%)', borderRadius: '50%' }} />
                            
                            <div style={{ position: 'relative', width: 280, height: 160, borderRadius: 12, overflow: 'hidden', flexShrink: 0, boxShadow: '0 4px 16px rgba(0,0,0,0.1)' }}>
                                <video
                                    controls
                                    src={videoUrl}
                                    style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                />
                            </div>

                            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', position: 'relative', zIndex: 1 }}>
                                <div>
                                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                        <h2 style={{ fontSize: 20, fontWeight: 600, marginBottom: 16, background: 'linear-gradient(135deg, #1e293b 0%, #334155 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>视频总结</h2>
                                        <div style={{ textAlign: 'right' }}>
                                            <span style={{ color: '#94a3b8', fontSize: 12 }}>上传时间: {taskDetail.createdAt ? new Date(taskDetail.createdAt).toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '-'}</span>
                                        </div>
                                    </div>
                                    <div style={{ display: 'flex', marginBottom: 12 }}>
                                        <span style={{ color: '#64748b', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>产品名称:</span>
                                        <span style={{ color: '#1e293b', fontWeight: 500 }}>{taskDetail.title}</span>
                                    </div>
                                    <div style={{ display: 'flex', marginBottom: 12 }}>
                                        <span style={{ color: '#64748b', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>受众群体:</span>
                                        {taskDetail.analysisStatus === 'processing' ? (
                                            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                                <Spin size="small" style={{ color: '#f59e0b' }} />
                                                <span style={{ fontSize: 14, color: '#f59e0b' }}>分析中</span>
                                            </div>
                                        ) : taskDetail.analysisStatus === 'completed' ? (
                                            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                                                {(taskDetail.originalVideoAudience?.split('、') || []).map((point: string, index: number) => (
                                                    <Tag key={index} style={{ fontSize: 12, background: 'rgba(99, 102, 241, 0.1)', color: '#6366f1', border: 'none', borderRadius: 20 }}>
                                                        {point}
                                                    </Tag>
                                                ))}
                                            </div>
                                        ) : null}
                                    </div>
                                    <div style={{ display: 'flex' }}>
                                        <span style={{ color: '#64748b', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>视频内容:</span>
                                        {taskDetail.analysisStatus === 'processing' ? (
                                            <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                                                <Spin size="small" style={{ color: '#f59e0b' }} />
                                                <span style={{ fontSize: 14, color: '#f59e0b' }}>分析中</span>
                                            </div>
                                        ) : taskDetail.analysisStatus === 'completed' ? (
                                            <span style={{ color: '#475569', lineHeight: 1.6 , height: 100,overflowY: 'auto'}}>{taskDetail.originalVideoContent}</span>
                                        ) : null}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div style={{ display: 'flex', gap: 16, marginBottom: 20, marginTop: 20 }}>
                            <Button
                                type="default"
                                onClick={handleOpenTrimModal}
                                disabled={!videoUrl || splitLoading}
                                style={{
                                    flex: 1,
                                    height: 52,
                                    borderRadius: 12,
                                    border: '2px solid rgba(99, 102, 241, 0.3)',
                                    color: '#6366f1',
                                    fontWeight: 600,
                                    fontSize: 15,
                                    background: 'rgba(255, 255, 255, 0.9)',
                                    backdropFilter: 'blur(10px)',
                                    transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                }}
                                onMouseEnter={(e) => {
                                    e.currentTarget.style.borderColor = '#6366f1';
                                    e.currentTarget.style.boxShadow = '0 4px 20px rgba(99, 102, 241, 0.2)';
                                }}
                                onMouseLeave={(e) => {
                                    e.currentTarget.style.borderColor = 'rgba(99, 102, 241, 0.3)';
                                    e.currentTarget.style.boxShadow = 'none';
                                }}
                            >
                                手动
                            </Button>
                            <Popconfirm
                                title={autoSplitButtonText === 'AI重拆' ? '确定要AI重拆吗？' : '确定要AI拆分吗？'}
                                okText="确定"
                                cancelText="取消"
                                onConfirm={handleAutoGenerate}
                            >
                                <Button
                                    type="primary"
                                    loading={autoSplitLoading}
                                    disabled={autoSplitLoading}
                                    style={{
                                        flex: 1,
                                        height: 52,
                                        borderRadius: 12,
                                        background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 50%, #a855f7 100%)',
                                        fontWeight: 600,
                                        fontSize: 15,
                                        border: 'none',
                                        boxShadow: '0 4px 20px rgba(99, 102, 241, 0.3)',
                                        transition: 'all 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
                                        position: 'relative',
                                        overflow: 'hidden',
                                    }}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.transform = 'translateY(-2px)';
                                        e.currentTarget.style.boxShadow = '0 6px 25px rgba(99, 102, 241, 0.4)';
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.transform = 'translateY(0)';
                                        e.currentTarget.style.boxShadow = '0 4px 20px rgba(99, 102, 241, 0.3)';
                                    }}
                                >
                                    <span style={{ position: 'relative', zIndex: 1 }}>{autoSplitButtonText}</span>
                                    {/* 按钮光效 */}
                                    <div style={{ 
                                        position: 'absolute', 
                                        top: 0, 
                                        left: '-100%', 
                                        width: '100%', 
                                        height: '100%', 
                                        background: 'linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent)',
                                        transition: 'left 0.5s ease'
                                    }} 
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.left = '100%';
                                    }} />
                                    {taskDetail?.aiSuggestions && taskDetail.aiSuggestions.length > 0 && (
                                    <Tooltip
                                        title={
                                            <div>
                                                <div style={{ fontWeight: 600, marginBottom: 8, color: '#6366f1' }}>AI拆分方案</div>
                                                {(() => {
                                                    const suggestions = taskDetail?.ai_suggestions || taskDetail?.aiSuggestions || [];
                                                    return suggestions.map((item: any) => (
                                                        <div key={item.index} style={{ marginBottom: 8, fontSize: 13, lineHeight: 1.5 }}>
                                                            <span style={{ fontWeight: 500, color: '#6366f1' }}>{item.index}.</span>
                                                            <span style={{ marginLeft: 4, color: '#000000ff' }}>{item.timeNode}</span>
                                                            <br />
                                                            <span style={{ color: '#666' }}>{item.content}</span>
                                                        </div>
                                                    ));
                                                })()}
                                            </div>
                                        }
                                        placement="top"
                                        trigger="hover"
                                        overlayInnerStyle={{ backgroundColor: '#fff', height: 300, overflowY: 'auto', border: '1px solid rgba(99, 102, 241, 0.1)', borderRadius: 12, boxShadow: '0 8px 24px rgba(99, 102, 241, 0.12)' }}
                                    >
                                        <span style={{ marginLeft: 8, fontSize: 13, opacity: 0.9 }}>(AI 镜头拆分方案)</span>
                                    </Tooltip>
                                    )}
                                </Button>
                            </Popconfirm>
                        </div>

                        <div 
                            style={{ 
                                flex: 2, 
                                background: 'linear-gradient(135deg, rgba(255,255,255,0.9) 0%, rgba(255,255,255,0.7) 100%)', 
                                backdropFilter: 'blur(20px)',
                                borderRadius: 20, 
                                overflow: 'hidden', 
                                display: 'flex', 
                                flexDirection: 'column',
                                border: '1px solid rgba(99, 102, 241, 0.1)',
                                boxShadow: '0 8px 32px rgba(99, 102, 241, 0.08)',
                            }}
                        >
                            <div style={{ padding: '16px 24px', borderBottom: '1px solid rgba(99, 102, 241, 0.1)', background: 'linear-gradient(135deg, rgba(99,102,241,0.02) 0%, transparent 100%)' }}>
                                <h3 style={{ fontSize: 16, fontWeight: 600, color: '#1e293b', margin: 0 }}>拆镜片段列表</h3>
                                <span style={{ fontSize: 12, color: '#64748b', marginLeft: 12 }}>共 {tableData.length} 个片段</span>
                            </div>
                            <Table
                                columns={columns}
                                dataSource={tableData}
                                pagination={false}
                                bordered={false}
                                rowKey="id"
                                scroll={{ y: 300 }}
                                style={{ flex: 1 }}
                                components={{
                                    body: {
                                        row: ({ className, style, ...rest }) => (
                                            <tr 
                                                {...rest} 
                                                className={className} 
                                                style={{ 
                                                    ...style, 
                                                    transition: 'all 0.2s ease',
                                                    borderBottom: '1px solid rgba(99, 102, 241, 0.05)',
                                                    height: 80,
                                                    overflow: 'auto',
                                                }} 
                                            />
                                        ),
                                        cell: ({ className, style, ...rest }) => (
                                            <td 
                                                {...rest} 
                                                className={className} 
                                                style={{ 
                                                    ...style, 
                                                    padding: '16px 24px',
                                                }} 
                                            />
                                        ),
                                    },
                                    header: {
                                        cell: ({ className, style, ...rest }) => (
                                            <th 
                                                {...rest} 
                                                className={className} 
                                                style={{ 
                                                    ...style, 
                                                    background: 'rgba(255, 255, 255, 1)',
                                                    color: '#64748b',
                                                    fontWeight: 500,
                                                    fontSize: 13,
                                                    padding: '16px 24px',
                                                    borderBottom: 'none',
                                                }} 
                                            />
                                        ),
                                    },
                                }}
                            />
                        </div>
                    </div>
                ) : (
                    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <span style={{ fontSize: 16, color: '#999' }}>加载中...</span>
                    </div>
                )}
            </div>

            <VideoTrimPicker
                open={trimModalVisible}
                videoUrl={videoUrl}
                title="手动视频切片"
                loading={splitLoading}
                minDuration={MIN_TRIM_SECONDS}
                maxDuration={MAX_TRIM_SECONDS}
                onCancel={() => setTrimModalVisible(false)}
                onConfirm={handleCustomSplit}
            />

            <Drawer
                title={
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                            <div style={{ width: 4, height: 20, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', borderRadius: 2 }} />
                            <span style={{ fontSize: 18, fontWeight: 600, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>智能视频复刻</span>
                            {currentSegmentName && <span style={{ fontSize: 14, color: '#64748b' }}>- {currentSegmentName}</span>}
                        </div>
                        <Button
                            type="text"
                            icon={<XOutlined />}
                            onClick={handleCloseDrawer}
                            style={{ padding: 0, color: '#64748b', fontSize: 14 }}
                        />
                    </div>
                }
                placement="right"
                closable={false}
                onClose={handleCloseDrawer}
                open={drawerVisible}
                size={480}
                styles={{
                    body: { padding: '24px', background: 'linear-gradient(180deg, #f8fafc 0%, #eef2ff 100%)' },
                    header: { background: '#fff', borderBottom: '1px solid rgba(99, 102, 241, 0.1)', padding: '20px 24px' },
                    section: { borderRadius: '20px 0 0 20px', overflow: 'hidden' },
                }}
            >
                <div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
                    <div style={{ background: '#fff', borderRadius: 12, padding: 16, border: '1px solid rgba(99, 102, 241, 0.1)' }}>
                        <label style={{ fontWeight: 500, color: '#334155', marginBottom: 8, display: 'block', fontSize: 14 }}>
                            产品白底图 <span style={{ color: '#ef4444' }}>*</span>
                        </label>
                        <div style={{ display: 'flex', gap: 12 }}>
                            <Upload
                                listType="picture-card"
                                onChange={handleProductImageChange}
                                beforeUpload={beforeUploadProductImage}
                                maxCount={1}
                                accept="image/*"
                                style={{ width: 120, height: 120, borderRadius: 8, border: '2px dashed rgba(99, 102, 241, 0.3)', background: 'rgba(99, 102, 241, 0.02)' }}
                            >
                                {!productImage && (
                                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                                        <PlusOutlined style={{ fontSize: 20, color: '#6366f1' }} />
                                        <span style={{ fontSize: 12, color: '#64748b' }}>上传产品图</span>
                                    </div>
                                )}
                            </Upload>
                        </div>
                    </div>

                    <div style={{ background: '#fff', borderRadius: 12, padding: 16, border: '1px solid rgba(99, 102, 241, 0.1)' }}>
                        <label style={{ fontWeight: 500, color: '#334155', marginBottom: 8, display: 'block', fontSize: 14 }}>
                            产品名称 <span style={{ color: '#ef4444' }}>*</span>
                        </label>
                        <Input
                            value={productName}
                            onChange={(e) => setProductName(e.target.value)}
                            placeholder="请输入产品名称"
                            style={{ height: 44, borderRadius: 8, border: '1px solid rgba(99, 102, 241, 0.2)' }}
                            maxLength={10}
                            showCount
                        />
                    </div>

                    <div style={{ background: '#fff', borderRadius: 12, padding: 16, border: '1px solid rgba(99, 102, 241, 0.1)' }}>
                        <label style={{ fontWeight: 500, color: '#334155', marginBottom: 8, display: 'block', fontSize: 14 }}>
                            产品卖点 <span style={{ color: '#ef4444' }}>*</span>
                        </label>
                        <TextArea
                            value={productSellingPoint}
                            onChange={(e) => setProductSellingPoint(e.target.value)}
                            placeholder="请输入产品卖点"
                            style={{ borderRadius: 8, border: '1px solid rgba(99, 102, 241, 0.2)' }}
                            maxLength={100}
                            showCount
                            rows={3}
                        />
                    </div>

                    <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                        <Button
                            type="primary"
                            onClick={handleManualGenerate}
                            loading={loading}
                            disabled={loading}
                            style={{
                                flex: 1,
                                height: 48,
                                borderRadius: 10,
                                background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                                fontWeight: 600,
                                fontSize: 15,
                                border: 'none',
                                boxShadow: '0 4px 15px rgba(99, 102, 241, 0.3)',
                                transition: 'all 0.2s ease',
                            }}
                            onMouseEnter={(e) => {
                                e.currentTarget.style.boxShadow = '0 6px 20px rgba(99, 102, 241, 0.4)';
                                e.currentTarget.style.transform = 'translateY(-1px)';
                            }}
                            onMouseLeave={(e) => {
                                e.currentTarget.style.boxShadow = '0 4px 15px rgba(99, 102, 241, 0.3)';
                                e.currentTarget.style.transform = 'translateY(0)';
                            }}
                        >
                            {loading ? '生成中...' : '手动生成'}
                        </Button>
                    </div>
                </div>
            </Drawer>

            <Modal
                title={
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <div style={{ width: 4, height: 20, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', borderRadius: 2 }} />
                        <span style={{ fontSize: 16, fontWeight: 600, background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)', WebkitBackgroundClip: 'text', WebkitTextFillColor: 'transparent' }}>视频预览</span>
                    </div>
                }
                open={previewModalVisible}
                onCancel={() => setPreviewModalVisible(false)}
                afterClose={() => {
                    if (previewVideoRef.current) {
                        previewVideoRef.current.pause();
                        previewVideoRef.current.currentTime = 0;
                    }
                }}
                footer={null}
                width={640}
                centered
                styles={{
                    body: { padding: 24, },
                    header: {  borderBottom: '1px solid #e0e0e0', padding: '20px 24px' },
                }}
            >
                <div style={{ borderRadius: 12, overflow: 'hidden',  }}>
                    <video
                        ref={previewVideoRef}
                        controls
                        src={previewVideoUrl || ''}
                        style={{ width: '100%', maxHeight: 420, objectFit: 'contain', backgroundColor: '#000' }}
                        playsInline
                        webkit-playsinline
                        autoPlay
                    />
                </div>
            </Modal>
        </>
    );
}

export default RemoveInfo;
