import {useEffect, useState} from 'react';
import {Button, Flex, notification, Space, Typography} from 'antd';

import {docReq, IDoc} from '../request/doc';
import {normalizeError} from '../util/util';
import {FileList} from '../components/file-list';
import {FileFilter} from '../enum';
import Create from "./create";
import {CustomHeader, PageType} from '../components/Header';
import {useNavigate} from "react-router-dom";

const { Title } = Typography;

export default function Files() {
    const [data, setData] = useState<(IDoc & { key: string })[]>([]);
    const [filter, setFilter] = useState<FileFilter>(FileFilter.all);
    const navigate = useNavigate();
    const refresh = (filter: FileFilter) => {
        docReq.getFiles(filter).then((docs) => {
            setData(docs.map(d => ({ ...d, key: d.id })));
        }).catch((e) => {
            notification.error({
                message: 'fetch data failed!',
                description: normalizeError(e)
            });
        });
    };
    useEffect(() => {
        refresh(filter);
    }, [filter]);

    const handleUpload  = (doc: IDoc) => {
        doc?.id && navigate(`/open/${doc.id}`);
        refresh(filter);
    }

    return (
        <CustomHeader type={PageType.Home}>
            <Flex vertical gap="small">
                <Title level={3}>Create</Title>
                <Create onUpload={doc => handleUpload(doc)} />
                <Title level={3}>List</Title>
                <SelectFileFilter setFilter={item => setFilter(item)} selectItem={filter} />
                <FileList
                    style={{ flex: 1, overflow: 'auto' }}
                    files={data}
                    refresh={() => refresh(filter)}
                />
            </Flex>
        </CustomHeader>
    );
}

const SelectFileFilter = (props: { selectItem: FileFilter, setFilter: (type: FileFilter) => void }) => {
    const { selectItem, setFilter } = props;
    return (
        <Space style={{ display: 'flex' }}>
            <Button style={{ fontSize: "18px", color: selectItem === FileFilter.all ? "rgb(20, 86, 240)" : "rgba(0, 0, 0, 0.88)"}} type="text" onClick={() => setFilter(FileFilter.all)}>All Files</Button>
            <Button style={{ fontSize: "18px",color: selectItem === FileFilter.my ? "rgb(20, 86, 240)" : "rgba(0, 0, 0, 0.88)"}} type="text" onClick={() => setFilter(FileFilter.my)}>My Files</Button>
            <Button style={{ fontSize: "18px",color: selectItem === FileFilter.shared ? "rgb(20, 86, 240)" : "rgba(0, 0, 0, 0.88)"}} type="text" onClick={() => setFilter(FileFilter.shared)}>Shared With Me</Button>
        </Space>
    )
}