import {redirect, useLoaderData} from 'react-router-dom';
import {docReq, IDoc} from '../request/doc';
import {konva_type, rich_text_type, spreadsheet_type} from '../ot-types';
import {Empty, Flex, Layout, notification, Spin, Timeline} from 'antd';
import {normalizeError, translateToLocalDate} from '../util/util';
import KonvaViewer from '../components/viewer/konva';
import QuillViewer from '../components/viewer/quill';
import SpreadSheetsViewer from '../components/viewer/spreadsheets';
import {useEffect, useMemo, useState} from 'react';
import {Content} from 'antd/es/layout/layout';
import Sider from 'antd/es/layout/Sider';
import {CustomHeader, PageType} from "../components/Header";

export async function loader({ params }: any) {
    try {
        const doc = await docReq.get(params.docId);
        const ops = await docReq.getOps(params.docId);

        return { doc, ops };
    } catch (error) {
        notification.error({
            message: "fetch doc error!",
            description: normalizeError(error)
        });
        return redirect('/all-files');
    }
}

interface IOpEx {
    userId: string;
    username: string;
    docId: string;
    version: number;
    date: string;
}

export default function DocHistory() {
    const { doc, ops } = useLoaderData() as { doc: IDoc, ops: IOpEx[] };
    const [version, setVersion] = useState<number>();
    const [isLoading, setIsLoading] = useState<boolean>(false);
    const [data, setData] = useState<any>(null);

    useEffect(() => {
        setIsLoading(true);
        docReq.getHistorySnapshot(doc.id, version).then((snapshot) => {
            console.log('fetch snapshot', snapshot);
            setData(snapshot.data);
            setIsLoading(false);
        });
    }, [version, doc]);

    const onClick = (v: number) => {
        setVersion(v);
    };

    const ContentCom = useMemo(() => {
        const contentStyle: React.CSSProperties = {
            padding: 50,
            background: 'rgba(0, 0, 0, 0.05)',
            borderRadius: 4,
        };

        const content = <div style={contentStyle} />;
        if (isLoading) {
            return <Flex justify = "center" align="center" style={{ height: "100%" }}><Spin tip="Loading" size="large">
                {content}
            </Spin></Flex>;
        } else if (data === null) {
            return <Flex justify = "center" align="center" style={{ height: "100%" }}><Empty /></Flex>;
        } else {
            return <HistoryViewer type={doc.type} data={data} />
        }
    }, [data, doc, isLoading])

    return (
        <CustomHeader type={PageType.History} doc={doc}>
            <Layout>
                <Content >{ContentCom}</Content >
                <Sider style={{ background: "#f5f5f5", marginTop: "20px" }}>
                    <Timeline
                        style={{
                            padding: '5px 10px',
                            height: "100%",
                            overflow: "auto"
                        }}
                        items={
                            ops.slice().reverse().map((op) => ({
                                children: (
                                    // op.v是指op是基于哪个版本的snapshot产生的, 如果要获取apply该op后的snapshot, 需要在fetchHistorySnapshot时传入op.v + 1.
                                    <span style={{ userSelect: 'none' }} onClick={() => onClick(op.version + 1)}>
                                        <p style={{ margin: '0px' }}>{op.username}</p>
                                        <p style={{ margin: '0px' }}>{translateToLocalDate(op.date)}</p>
                                        <p style={{ margin: '0px' }}>version({op.version})</p>
                                    </span>
                                )
                            }))
                        }
                    ></Timeline>
                </Sider>
            </Layout>
        </CustomHeader>
    )
}

function HistoryViewer(props: { type: string, data: any }) {
    const { data, type } = props;

    let editor;
    if (type === konva_type.uri) {
        editor = <KonvaViewer data={data} />
    } else if (type === spreadsheet_type.uri) {
        editor = <SpreadSheetsViewer data={data} />
    } else if (type === rich_text_type.uri) {
        editor = <QuillViewer data={data} />
    } else {
        console.error('error');
    }

    return editor;
}