import { Card, Col, Row, message, notification, Spin, Dropdown  } from 'antd';
import {docReq, IDoc} from '../request/doc';
import { useNavigate } from 'react-router-dom';
import { konva_type, rich_text_type, spreadsheet_type } from '../ot-types';
import { getDocIcon } from '../util/icon';
import React, {useRef, useState} from 'react';
import { FileExcelOutlined, UploadOutlined }  from '@ant-design/icons'
import { normalizeError } from '../util/util';

const { Meta } = Card;
export default function Create (props: { onUpload: (doc: IDoc) => void; }) {
    const { onUpload } = props;
    const [isUploading, setIsUploading] = useState<boolean>(false);
    const navigate = useNavigate();

    const handleFileUpload = async (file: File) => {
        try {
            setIsUploading(true);
            const doc = await docReq.uploadFile(file);
            setIsUploading(false);
            notification.success({ message: 'File uploaded successfully!' });
            onUpload(doc);
        } catch (e) {
            notification.error({
                message: 'File upload failed!',
                description: normalizeError(e),
            });
            setIsUploading(false);
        }
    };

    const onClick = async (type: string, title?: string) => {
        try {
            const d = await docReq.create(type, title + '-' + Math.floor(Math.random() * 1000));
            message.success('Create Successful!');
            console.log(d);
            navigate(`/open/${d.id}`);
        } catch (e) {
            notification.error({
                message: 'Create Failed!',
                description: normalizeError(e),
            });
        }
    }
    const items = [
        {
            type: spreadsheet_type.uri,
            title: 'Workbook',
            content: 'Create a Workbook',
        },
        {
            type: rich_text_type.uri,
            title: 'Text',
            content: 'Create a Text',
        },
        {
            type: konva_type.uri,
            title: 'Drawing',
            content: 'Create a Drawing',
        }
    ];

    return (
        <div style={{ width: '96%' }}>
            <Row gutter={20}>
                {items.map(item => (
                    <Col span={5} key={item.type}>
                        {item.type === spreadsheet_type.uri ?
                            <WorkbookCard desc={item.content}
                                          spinning={isUploading}
                                          icon={<img width={"40px"} height={"40px"} style={{ borderRadius: "6px" }} src={getDocIcon(item.type)}></img>}
                                          title={item.title}
                                          createEmpty={() => onClick(spreadsheet_type.uri, 'Workbook')}
                                          importLocalFile={(file) => handleFileUpload(file)}
                            />
                            : <CustomerCard desc={item.content}
                                            icon={<img width={"40px"} height={"40px"} style={{ borderRadius: "6px" }}
                                                       src={getDocIcon(item.type)}></img>}
                                            title={item.title} onClick={() => onClick(item.type, item.title)}/>
                        }
                    </Col>
                ))}
            </Row>
        </div>
    );
}

const CustomerCard = (props: { title: string, icon: any, desc: any, onClick: () => void; }) => {
    const { title, icon, desc, onClick } = props;
    return (
        <Card hoverable={true} onClick={() => onClick()}>
            <Meta
                avatar={icon}
                title={title}
                description={desc}
            />
        </Card>
    )
}

const WorkbookCard = (props: { spinning: boolean, title: string, icon: any, desc: any, createEmpty: () => void; importLocalFile: (file: File) => void; }) => {
    const { title, icon, desc, createEmpty, importLocalFile, spinning } = props;
    const myRef = useRef<any>();
    const items = [
        {
            label: 'Empty Workbook',
            key: 'Empty',
            icon: <FileExcelOutlined />,
        },
        {
            label: 'Import Local File',
            key: 'Import',
            icon: <UploadOutlined />,
        }];

    const handleClick = (key: string) => {
        if (key === 'Empty') {
            createEmpty();
        } else {
            myRef.current?.click?.();
        }
    }
    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (file) {
            const allowedTypes = ['.xlsx', '.sjs', '.ssjson'];
            const fileExtension = file.name.slice(file.name.lastIndexOf('.')).toLowerCase();

            if (allowedTypes.includes(fileExtension)) {
                importLocalFile(file);
            } else {
                message.error('please upload xlsx, sjs or ssjson file type');
            }
        }
    };
    return (
        <Spin spinning={spinning}>
            <Dropdown menu={{ items, onClick: (v) => handleClick(v.key) }} disabled={spinning} arrow overlayStyle={{ height: '80px' }}>
                <Card hoverable={true}>
                    <Meta
                        avatar={icon}
                        title={title}
                        description={desc}
                    />
                    <input
                        ref={myRef}
                        type="file"
                        style={{ display: 'none' }}
                        onChange={handleFileChange}
                        accept=".xlsx,.sjs,.ssjson"
                    />
                </Card>
            </Dropdown>
        </Spin>
    )
}