import React, { useEffect } from "react";
import { Button } from "../../tremor/Button";
import { Text } from "../../tremor/Text";
import { useBackend } from "../../layouts";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import { useAutomationsModal } from "./useAutomationsModal";
import dayjs from "dayjs";
import relativeTime from "dayjs/plugin/relativeTime";
import utc from "dayjs/plugin/utc";
import timezone from "dayjs/plugin/timezone";
import cronstrue from "cronstrue";

dayjs.extend(relativeTime);
dayjs.extend(utc);
dayjs.extend(timezone);

export const AutomationSidebar: React.FC<{}> = ({ }) => {

    const { open, selectedAutomation, setSelectedAutomation, automations, getAllAutomations, createAutomation } = useAutomationsModal();
    const { backend, account, embedUser } = useBackend();
    const { dashboard } = useDashboard();

    useEffect(() => {
        if (open && dashboard && backend) {
            getAllAutomations(backend, dashboard.id);
        }
    }, [open, dashboard, backend]);

    return (<div className="onvo-w-full onvo-h-full onvo-foreground-color dark:onvo-bg-slate-950">

        <Button variant="primary" className="onvo-w-[calc(100%-16px)] onvo-m-2" onClick={() => {
            if (!backend || !dashboard) return;
            createAutomation(backend, dashboard, automations, account, embedUser)
        }}>+ New automation</Button>
        {automations.map(a => (
            <div key={a.id} className={"onvo-py-2 onvo-px-3 onvo-rounded-lg onvo-mx-2 onvo-cursor-pointer " + (selectedAutomation?.id === a.id ? "onvo-bg-black/10 dark:onvo-bg-white/10" : "")} onClick={() => {
                setSelectedAutomation(a);
            }}>
                <Text className="onvo-font-semibold">{a.title}</Text>
                <Text className="!onvo-text-xs onvo-mt-1"> {a.schedule.trim() === "" ? "Automation not setup" : cronstrue.toString(a.schedule, { verbose: true })}</Text>
            </div>
        ))}
    </div>)
}