import React, { useState, useRef, useEffect } from 'react';
import { Button, Card, Row, Col, Typography, List, message } from 'antd';
const { Text } = Typography;

// 生成随机ID
const randomId = (length) => {
    return Array.from({ length }, () => Math.random().toString(36).charAt(2)).join('');
};

const WebRTCClient = () => {
    const [connectionStates, setConnectionStates] = useState({
        iceConnection: 'new',
        iceGathering: 'new',
        signaling: 'stable',
        dataChannel: []
    });
    const [sdpInfo, setSdpInfo] = useState({ offer: '', answer: '' });
    const [mediaState, setMediaState] = useState({ started: false });

    const clientId = useRef(randomId(10));
    const websocket = useRef(null);
    const pc = useRef(null);
    const dc = useRef(null);
    const videoRef = useRef(null);
    const startTime = useRef(null);

    // WebSocket 初始化
    useEffect(() => {
        websocket.current = new WebSocket(`wss://amass.fun/api/v1/webrtc/signal/${clientId.current}`);

        websocket.current.onopen = () => {
            message.success('信令服务器连接成功');
        };

        websocket.current.onmessage = async (evt) => {
            if (typeof evt.data !== 'string') return;
            const message = JSON.parse(evt.data);
            if (message.type === "offer") {
                setSdpInfo(prev => ({ ...prev, offer: message.sdp }));
                handleOffer(message);
            }
        };

        return () => websocket.current?.close();
    }, []);

    // 状态更新方法
    const updateConnectionState = (type, state) => {
        setConnectionStates(prev => ({
            ...prev,
            [type]: [...prev[type], state]
        }));
    };

    // 创建PeerConnection
    const createPeerConnection = () => {
        const config = {
            bundlePolicy: "max-bundle",
            iceServers: [{ urls: ['stun:stun.l.google.com:19302'] }]
        };

        const newPc = new RTCPeerConnection(config);

        // ICE状态监听
        newPc.addEventListener('iceconnectionstatechange', () => {
            updateConnectionState('iceConnection', newPc.iceConnectionState);
        });

        newPc.addEventListener('icegatheringstatechange', () => {
            updateConnectionState('iceGathering', newPc.iceGatheringState);
        });

        newPc.addEventListener('signalingstatechange', () => {
            updateConnectionState('signaling', newPc.signalingState);
        });

        // 媒体流处理（网页2关键逻辑）
        newPc.ontrack = (evt) => {
            if (videoRef.current) {
                videoRef.current.srcObject = evt.streams[0];
                videoRef.current.play().catch(err => message.error('视频播放失败'));
            }
        };

        // 数据通道处理（网页1实现参考）
        newPc.ondatachannel = (evt) => {
            dc.current = evt.channel;
            dc.current.onmessage = (event) => {
                if (typeof event.data === 'string') {
                    setConnectionStates(prev => ({
                        ...prev,
                        dataChannel: [...prev.dataChannel, `< ${event.data}`]
                    }));
                }
            };
        };

        return newPc;
    };

    // 处理Offer
    const handleOffer = async (offer) => {
        pc.current = createPeerConnection();
        await pc.current.setRemoteDescription(offer);
        await sendAnswer();
    };

    // 发送Answer
    const sendAnswer = async () => {
        const answer = await pc.current.createAnswer();
        await pc.current.setLocalDescription(answer);

        setSdpInfo(prev => ({ ...prev, answer: answer.sdp }));

        websocket.current.send(JSON.stringify({
            id: "server",
            type: answer.type,
            sdp: answer.sdp
        }));
    };

    // 控制方法
    const startCall = () => {
        setMediaState({ started: true });
        websocket.current.send(JSON.stringify({ id: "server", type: "request" }));
        startTime.current = Date.now();
    };

    const stopCall = () => {
        if (dc.current) dc.current.close();
        if (pc.current) pc.current.close();
        setMediaState({ started: false });
    };

    return (
        <Card title="WebRTC 视频通话" style={{ width: 800 }}>
            <Row gutter={16}>
                {/* 视频区域 */}
                <Col span={16}>
                    <video
                        ref={videoRef}
                        style={{
                            width: '100%',
                            border: '1px solid #f0f0f0',
                            display: mediaState.started ? 'block' : 'none'
                        }}
                        muted
                        autoPlay
                    />

                    <div style={{ marginTop: 16 }}>
                        <Button
                            type="primary"
                            onClick={startCall}
                            disabled={!websocket.current?.readyState}
                        >
                            开始通话
                        </Button>
                        <Button
                            danger
                            onClick={stopCall}
                            style={{ marginLeft: 8 }}
                        >
                            结束通话
                        </Button>
                    </div>
                </Col>

                {/* 状态信息 */}
                <Col span={8}>
                    <Card size="small" title="连接状态">
                        <Text strong>ICE Connection:</Text>
                        <Text code>{connectionStates.iceConnection}</Text>
                        <br />

                        <Text strong>ICE Gathering:</Text>
                        <Text code>{connectionStates.iceGathering}</Text>
                        <br />

                        <Text strong>Signaling:</Text>
                        <Text code>{connectionStates.signaling}</Text>
                    </Card>

                    <Card size="small" title="SDP 信息" style={{ marginTop: 16 }}>
                        <Text strong>Offer SDP:</Text>
                        <pre style={{ fontSize: 10 }}>{sdpInfo.offer}</pre>

                        <Text strong>Answer SDP:</Text>
                        <pre style={{ fontSize: 10 }}>{sdpInfo.answer}</pre>
                    </Card>

                    <Card size="small" title="数据通道" style={{ marginTop: 16 }}>
                        <List
                            size="small"
                            dataSource={connectionStates.dataChannel}
                            renderItem={item => (
                                <List.Item style={{ fontFamily: 'monospace' }}>
                                    {item}
                                </List.Item>
                            )}
                            style={{ maxHeight: 200, overflowY: 'auto' }}
                        />
                    </Card>
                </Col>
            </Row>
        </Card>
    );
};

export default WebRTCClient;