import React, {useEffect, useState} from 'react';
import {useDispatch, useSelector} from "react-redux";
import {createSchema, schemaStatus} from "../httpServices/httpServiceSchema";
import {archiveOrders, archiveOrdersDelete, startBgProcess} from "../httpServices/httpServiceArchive";
import {createDB, getDBStatus} from "../httpServices/httpServiceDb";
import {setSchemaLoadingTrue} from "../slices/schemaSlice";
import {resetArchive, setArchiveAbort, setArchiveLoadingTrue} from "../slices/archiveSlice";
import {setDbLoadingTrue} from "../slices/dbSlice";
import {arcLoadingTrue} from "../slices/deleteOrdersSlice";
import {destroyAlerts, errorAlert, infoAlert, savedAlert, savingAlert, updateAlert} from "../actions/alertActions";
import {saveLog} from "../httpServices/httpServiceLog";
import {setProcessLoadingTrue} from "../slices/bgProcessSlice";

const SyncButton = () => {
    const {schema, loading, error} = useSelector(state => state.schema)
    const {archive, archiveLoading, archiveError, isAborted} = useSelector(state => state.archive)
    const {database, dbLoading, dbError} = useSelector(state => state.database)
    const {message, arcLoading, arcError} = useSelector(state => state.deleteOrders)
    const {bgProcessing, processLoading, processError} = useSelector(state => state.backgroundProcess)

    const [step, setStep] = useState(0)
    const dispatch = useDispatch();

    useEffect(()=>{
        switch (step) {
            case 1:
                dispatch(getDBStatus())
                break;
            case 2:
                dispatch(createDB())
                break;
            case 3:
                dispatch(schemaStatus())
                break;
            case 4:
                dispatch(create_schema())
                break;
            case 5:
                dispatch(archiveOrders())
                break;
            case 6:
                dispatch(setArchiveLoadingTrue())
                break;
            case 7:
                dispatch(resetArchive())
                break;
            case 8:
                dispatch(archiveOrdersDelete())
                break;
            case 9:
                dispatch(arcLoadingTrue())
                break;
            case 10:
                dispatch(startBgProcess())
                break;
            default:
                dispatch(setDbLoadingTrue())
                dispatch(setSchemaLoadingTrue())
                dispatch(setProcessLoadingTrue())
                break;
        }
    },[dispatch, step])

    useEffect(() => {
        if (isAborted) return
        // Logic For Check and create database
        if (!dbLoading){
            if (!loading) setStep(0)
            if (database.success){
                if (!database.database){
                    updateAlert({
                        title: (<span className="ml-[10px] inline">Checking ...</span>),
                        description: (
                            <div className="text-center">
                                <span className="block">{database.message}</span>
                                <span className="block text-red-600">Please wait and don't refresh the page!</span>
                            </div>
                        ),
                        abortProcess
                    })
                    setStep(2)
                } else {
                    updateAlert({
                        title: (<span className="ml-[10px] inline">Checking ...</span>),
                        description: (
                            <div className="text-center">
                                <span className="block">{database.message}</span>
                                <span className="block text-red-600">Please wait and don't refresh the page!</span>
                            </div>
                        ),
                        abortProcess
                    })
                    setStep(3)
                }
            } else {
                errorAlert({
                    title: 'Error',
                    description: database.message
                })
                setStep(0)
            }
        }

        // Logic for check and create wp schema
        if (!loading){
            if (schema.status){
                updateAlert({
                    title: (<span className="ml-[10px] inline">Archiving ...</span>),
                    description: (
                        <div className="text-center">
                            <span className="block">Orders in queue for the archive</span>
                            <span className="block text-red-600">Please wait and don't refresh the page!</span>
                        </div>
                    ),
                    abortProcess
                })
                setStep(0)
                setTimeout(() => {
                    setStep(5)
                }, 100)
            } else {
                updateAlert({
                    title: (<span className="ml-[10px] inline">Checking ...</span>),
                    description: (
                        <div className="text-center">
                            <span className="block">{schema.message}</span>
                            <span className="block text-red-600">Please wait and don't refresh the page!</span>
                        </div>
                    ),
                    abortProcess
                })
                setStep(0)
                setTimeout(() => {
                    setStep(4)
                }, 100)
            }
        }

        // Start Archiving
        if (!archiveLoading) {
            if (!archive.status){
                destroyAlerts()
                abortProcess()
                errorAlert({
                    title:"Abort!",
                    description: archive.message,
                    abortProcess
                })

                setTimeout(() => {
                    setStep(0)
                    setStep(6)
                    setStep(7)
                }, 100)
            }

            if (archive.error) {
                infoAlert({
                    title: 'Info',
                    description: archive.message
                })
                setStep(0)
                setStep(6)
                setStep(7)
            }else{
                if (archive.loop){
                    if (archive.bgProcess){
                        destroyAlerts()
                        savedAlert({
                            title:"Process running",
                            description: "Background process already running",
                        })
                    }else{
                        destroyAlerts()
                        savedAlert({
                            title: (<span className="inline">Queue completed ...</span>),
                            description: (
                                <div className="text-left">
                                    <span className="block">Initiated or running the archive's background process.</span>
                                    {/*<span className="block text-red-600">Please wait and don't refresh the page!</span>*/}
                                </div>
                            ),
                            abortProcess
                        })

                        setStep(0)
                        setStep(6)
                        setStep(7)

                        // setTimeout(() =>{
                        //     setStep(10)
                        // },200)
                    }

                    // setStep(0)
                    // setStep(6)
                    // setStep(7)

                    // setTimeout(() =>{
                    //     setStep(8)
                    // },200)
                }else{
                    updateAlert({
                        title: (<span className="ml-[10px] inline">Queue ...</span>),
                        description: (
                            <div className="text-center">
                                <span className="block">Queued orders <b>{archive.remotePostCount}</b> of <b>{archive.mainPostCount}</b> for archive.</span>
                                <span className="block text-red-600">Please wait and don't refresh the page!</span>
                            </div>
                        ),
                        abortProcess
                    })
                    setStep(0)
                    setStep(6)

                    setTimeout(()=>{
                        setStep(5)
                    }, 1000)
                }
            }
        }

        if (!processLoading){
            destroyAlerts()
            savedAlert({
                title       : bgProcessing.title,
                description : bgProcessing.message
            })

            setStep(0)
            setStep(6)
            setStep(7)
        }

        // if (!arcLoading){
        //     if (message.status){
        //         if(message.error){
        //             destroyAlerts()
        //             errorAlert({
        //                 title:"Error",
        //                 description: message.message
        //             })
        //         }else{
        //             destroyAlerts()
        //             savedAlert({
        //                 title:"Success",
        //                 description: "Archive saved successfully.",
        //             })
        //             dispatch(saveLog({
        //                 title: "Archive saved",
        //                 content: "Archive saved successfully",
        //                 activity: "Archive saved successfully",
        //             }))
        //         }
        //         setStep(0)
        //         setStep(7)
        //         setStep(9)
        //     }else{
        //         if (message.error){
        //             destroyAlerts()
        //             errorAlert({
        //                 title:"Error",
        //                 description: message.message
        //             })
        //             setStep(0)
        //             setStep(7)
        //             setStep(9)
        //         }else{
        //             updateAlert({
        //                 title: (<span className="ml-[10px] inline">Deleting ...</span>),
        //                 description: (
        //                     <div className="text-center">
        //                         <span className="block">{message.message}</span>
        //                         <span className="block text-red-600">Please wait and don't refresh the page!</span>
        //                     </div>
        //                 ),
        //                 abortProcess
        //             })
        //             setStep(9)
        //             setTimeout(() => {
        //                 setStep(8)
        //             }, 100)
        //         }
        //     }
        // }

    }, [
        setStep,
        database, dbLoading,
        schema, loading,
        archive, archiveLoading,
        message, arcLoading,
        processLoading, bgProcessing
    ]);

    const handleArchiving = () =>{
        savingAlert({
            title: (<span className="ml-[10px] inline">Checking ...</span>),
            description: (
                <div className="text-center">
                    <span className="block">Checking database</span>
                    <span className="block text-red-600">Please wait and don't refresh the page!</span>
                </div>
            ),
            abortProcess
        })
        dispatch(setArchiveAbort(false))
        setStep(1)
    }

    const abortProcess = () =>{
        dispatch(setDbLoadingTrue())
        dispatch(setSchemaLoadingTrue())
        dispatch(arcLoadingTrue())
        dispatch(setArchiveLoadingTrue())
        dispatch(setArchiveAbort(true))

        // dispatch(saveLog({
        //     title: "Archive canceled",
        //     content: "Archive canceled successfully",
        //     activity: "Archive canceled",
        // }))
    }

    return (
        <div className="mb-[15px]">
            <a onClick={handleArchiving} href="javaScript:void(0)"
               className="flex w-full justify-center rounded bg-primary p-3 font-medium text-gray hover:bg-opacity-90 hover:bg-blue-700 hover:text-white focus:text-white">
                Start Archiving
            </a>
        </div>
    );
};

export default SyncButton;