import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button, Table, Tag, Drawer, Input, Upload, message } from 'antd';
import { ArrowLeftOutlined, PlayCircleOutlined, XOutlined, PlusOutlined, UploadOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd';
import { getShotReplicationDetail, createRemoveLens, Removelist, uploadImage, removeCreate, splitCustom } from '../api';

const { TextArea } = Input;

function RemoveInfo() {
    const { creatID } = useParams<{ creatID: string }>();
    const navigate = useNavigate();
    const [drawerVisible, setDrawerVisible] = useState(false);
    const [currentSegment, setCurrentSegment] = useState<number | null>(null);
    const [productName, setProductName] = useState('');
    const [productSellingPoint, setProductSellingPoint] = useState('');
    const [productImage, setProductImage] = useState('');
    const [detailImage, setDetailImage] = useState('');
    const [taskDetail, setTaskDetail] = useState<any>(null);
    const [tableData, setTableData] = useState<any[]>([]);
    const [loading, setLoading] = useState(false);

    const handleGenerate = (segmentId: number) => {
        setCurrentSegment(segmentId);
        setDrawerVisible(true);
    };

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

    useEffect(() => {
        console.log('ididi', creatID);
        if (creatID) {
            getShotReplicationDetail(creatID).then((res: any) => {
                setTaskDetail(res);
                console.log('res', res);
            }).catch((error: any) => {
                message.error('获取任务详情失败');
            });

            Removelist(creatID).then((res: any) => {
                console.log('Removelist res', res);
                setTableData(res.items || []);
            }).catch((error: any) => {
                message.error('获取拆镜列表失败');
            });
        }
    }, [creatID]);

    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 (err) {
            message.error('图片上传失败，请重试');
        }
        return false;
    };

    const handleDetailImageChange: any = (info: any) => {
        if (info.fileList.length > 0) {
            const file = info.fileList[0];
            if (file.originFileObj) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    setDetailImage(e.target?.result as string);
                };
                reader.readAsDataURL(file.originFileObj);
            }
        } else {
            setDetailImage('');
        }
    };

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

        setLoading(true);
        try {
            const params = {
                target_project_name: productName.trim(),
                core_content_point: productSellingPoint.trim(),
                material_image_url: `${import.meta.env.VITE_API_BASE || "http://localhost:8000"}${productImage}`,
                idempotency_key: `replication_${Date.now()}`,
            };
            console.log(params);


            await removeCreate(String(currentSegment), params);
            message.success('视频生成任务创建成功');
            // handleCloseDrawer();
        } catch (err) {
            message.error('创建失败，请重试');
        } finally {
            setLoading(false);
        }
    };

    const handleAutoGenerate = () => {
        // console.log('123123');
        let params = {
            selected_indices: [],
            replace_existing: false,
        }
        createRemoveLens(creatID, params).then((res: any) => {
            console.log('res', res);
        }).catch((error: any) => {
            message.error('拆镜失败');
        });

    }





    const columns = [
        {
            title: '片段',
            width: 100,
            align: 'center' as const,
            render: (text: any, record: any) => (
                <div>
                    <div style={{ fontSize: 16, fontWeight: 600, color: '#333' }}>{record.segmentName}</div>
                    <div style={{ fontSize: 12, color: '#999' }}>{record.timeNode}</div>
                </div>
            )
        },
        {
            title: '片段视频',
            width: 150,
            align: 'center' as const,

            render: (text: any, record: any) => (
                <div style={{ position: 'relative', width: 120, height: 80, borderRadius: 6, overflow: 'hidden' }}>
                    <video
                        controls
                        src={`${import.meta.env.VITE_API_BASE || "http://localhost:8000"}${record.segmentVideoUrl}`}
                        // alt={`片段${record.id}`}
                        style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                    />
                    {/* <div style={{
                        position: 'absolute',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%, -50%)',
                        width: 28,
                        height: 28,
                        background: 'rgba(0,0,0,0.6)',
                        borderRadius: '50%',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center'
                    }}>
                        <PlayCircleOutlined style={{ fontSize: 16, color: '#fff' }} />
                    </div> */}
                </div>
            )
        },
        {
            title: '视频内容',
            width: 250,
            align: 'left' as const,

            render: (text: any, record: any) => (
                <div style={{ fontSize: 14, color: '#333', lineHeight: 1.6 }}>
                    {record.segmentContent}
                </div>
            )
        },
        // {
        //     title: '台词',
        //     width: 250,

        //     render: (text: any, record: any) => (
        //         <div style={{ fontSize: 14, color: '#333', lineHeight: 1.6 }}>
        //             {record.lines}
        //         </div>
        //     )
        // },
        {
            title: '视频类型',

            width: 120,
            align: 'center' as const,
            render: (text: any, record: any) => (
                <div style={{ fontSize: 14, color: '#333', fontWeight: 500 }}>
                    {record.segmentCategory || '-'}
                </div>
            )
        },
        {
            title: '素材',
            width: 140,

            align: 'center' as const,
            render: (text: 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: '#656efa', fontSize: 12, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}
                        >
                            详情任务
                        </Button>
                    ) : (
                        <Button
                            type="text"
                            onClick={() => handleGenerate(record.id)}
                            style={{ color: '#656efa', fontSize: 12, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}
                        >
                            视频生成
                        </Button>
                    )}
                </div>
            )
        }
    ];

    return (
        <>
            <div style={{
                // height: '100%',
                minHeight: 'calc(100vh - 90px)',
                display: 'flex',
                flexDirection: 'column',
                overflow: 'hidden',
            }}>
                <div style={{ background: '#fff',}}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                        <Button
                            type="text"
                            icon={<ArrowLeftOutlined />}
                            onClick={() => navigate(-1)}
                            style={{ fontSize: 16, color: '#666' }}
                        />
                    </div>
                </div>

                {taskDetail ? (
                    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between', overflow: 'hidden' }}>
                        <div style={{ flex: 0.4,  background: '#fff', borderRadius: 12,   }}>

                            {/* 213123 */}
                            <div style={{ display: 'flex', alignItems: 'center', gap: 30, marginBottom: 12 }}>
                                <div style={{ position: 'relative', width: 280, height: 160, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
                                    <video
                                        controls
                                        src={`${import.meta.env.VITE_API_BASE || "http://localhost:8000"}${taskDetail.videoUrl}`}
                                        style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                                    />
                                </div>

                                <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                                    <div>
                                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                                            <h2 style={{ fontSize: 20, fontWeight: 600, marginBottom: 16 }}>视频总结</h2>
                                            <div style={{ textAlign: 'right' }}>
                                                <span style={{ color: '#999', fontSize: 12 }}>上传时间: {taskDetail.createdAt}</span>
                                            </div>

                                        </div>
                                        <div style={{ display: 'flex', marginBottom: 12 }}>
                                            <span style={{ color: '#999', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>产品名称:</span>
                                            <span style={{ color: '#333', fontWeight: 500 }}>{taskDetail.title}</span>
                                        </div>
                                        <div style={{ display: 'flex', marginBottom: 12 }}>
                                            <span style={{ color: '#999', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>受众群体:</span>
                                            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                                                {(taskDetail.originalVideoAudience?.split('、') || []).map((point, index) => (
                                                    <Tag key={index} color="purple" style={{ fontSize: 12 }}>
                                                        {point}
                                                    </Tag>
                                                ))}
                                            </div>
                                        </div>
                                        <div style={{ display: 'flex' }}>
                                            <span style={{ color: '#999', fontSize: 14, marginRight: 12, width: 80, flexShrink: 0 }}>视频内容:</span>
                                            <span style={{ color: '#333' }}>{taskDetail.originalVideoContent}</span>
                                        </div>
                                    </div>


                                </div>
                            </div>
                        </div>

                        <div style={{ display: 'flex', gap: 16, marginBottom: 20, marginTop: 20 }}>
                            <Button
                                type="default"
                                onClick={() => handleAutoGenerate()}
                                style={{
                                    flex: 1,
                                    height: 48,
                                    borderRadius: 8,
                                    borderColor: '#6366f1',
                                    color: '#6366f1',
                                    fontWeight: 500
                                }}
                            >
                                手动
                            </Button>
                            <Button
                                type="primary"
                                onClick={() => handleAutoGenerate()}
                                style={{
                                    flex: 1,
                                    height: 48,
                                    borderRadius: 8,
                                    background: 'linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%)',
                                    fontWeight: 500,
                                    border: 'none'
                                }}
                            >
                                自动
                            </Button>
                        </div>

                        <div style={{ flex: 0.6, background: '#fff', borderRadius: 12, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
                            <Table
                                columns={columns}
                                dataSource={tableData}
                                pagination={false}
                                bordered={false}
                                rowKey="id"
                                scroll={{ y: '1005'}}
                                // style={{ flex: 1 }}
                            />
                        </div>

                    </div>
                ) : (
                    <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                        <span style={{ fontSize: 16, color: '#999' }}>加载中...</span>
                    </div>
                )}
            </div>

            <Drawer
                title={
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
                        <span>
                            <span style={{ color: '#6366f1' }}>智能视频复刻</span>
                            <span style={{ color: '#6366f1' }}>-片段{currentSegment}</span>
                        </span>
                        <Button
                            type="text"
                            icon={<XOutlined />}
                            onClick={handleCloseDrawer}
                            style={{ padding: 0 }}
                        />
                    </div>
                }
                placement="right"
                closable={false}
                onClose={handleCloseDrawer}
                open={drawerVisible}
                size={480}
                styles={{
                    body: { padding: '24px' }
                }}
            >
                <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>
                    <div>
                        <label style={{ fontWeight: 400, color: '#333', marginBottom: 12, display: 'block' }}>
                            产品白底图 <span style={{ color: '#ff4d4f' }}>*</span>
                        </label>
                        <div style={{ display: 'flex', gap: 16 }}>
                            <Upload
                                listType="picture-card"
                                onChange={handleProductImageChange}
                                beforeUpload={beforeUploadProductImage}
                                maxCount={1}
                                accept="image/*"
                                style={{ width: 140, height: 140 }}
                            >
                                {!productImage && (
                                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                                        <PlusOutlined style={{ fontSize: 24, color: '#999' }} />
                                        <span style={{ fontSize: 12, color: '#999' }}>产品图 *</span>
                                    </div>
                                )}
                            </Upload>
                        </div>
                    </div>

                    <div>
                        <label style={{ fontWeight: 500, color: '#333', marginBottom: 12, display: 'block' }}>
                            产品名称
                        </label>
                        <Input
                            value={productName}
                            onChange={(e) => setProductName(e.target.value)}
                            placeholder="请输入产品名称"
                            style={{ height: 48, borderRadius: 8 }}
                            maxLength={10}
                            showCount
                        />
                    </div>

                    <div>
                        <label style={{ fontWeight: 500, color: '#333', marginBottom: 12, display: 'block' }}>
                            产品卖点
                        </label>
                        <TextArea
                            value={productSellingPoint}
                            onChange={(e) => setProductSellingPoint(e.target.value)}
                            placeholder="请输入产品卖点"
                            style={{ borderRadius: 8 }}
                            maxLength={100}
                            showCount
                            rows={3}
                        />
                    </div>

                    <div style={{ display: 'flex', gap: 16, marginTop: 24 }}>
                        <Button
                            type="default"
                            onClick={handleManualGenerate}
                            loading={loading}
                            disabled={loading}
                            style={{
                                flex: 1,
                                height: 48,
                                borderRadius: 8,
                                borderColor: '#6366f1',
                                color: '#6366f1',
                                fontWeight: 500
                            }}
                        >
                            {loading ? '生成中...' : '手动生成'}
                        </Button>

                    </div>
                </div>
            </Drawer>
        </>
    );
}

export default RemoveInfo;
