import React, { useEffect, useState } from "react";
import { Button } from "../../tremor/Button";
import { Text } from "../../tremor/Text";
import { useBackend } from "../../layouts";
import { useDashboard } from "../../layouts/Dashboard/useDashboard";
import { toast } from "sonner";
import { useAutomationsModal } from "./useAutomationsModal";
import { Automation } from "@onvo-ai/js";
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 } = useAutomationsModal();
    const { backend, account, embedUser } = useBackend();
    const { dashboard } = useDashboard();
    const [automations, setAutomations] = useState<Automation[]>([]);

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

    const getAllAutomations = async () => {
        if (!backend || !dashboard) return;
        const response = await backend.automations.list({
            dashboard: dashboard?.id,
        });
        setAutomations(response);
        if (response.length > 0 && !selectedAutomation?.id) {
            setSelectedAutomation(response[0]);
        }
    }

    const createAutomation = async () => {
        toast.promise(async () => {
            let newAutomation = await backend?.automations.create({
                title: "Automation " + (automations.length + 1),
                description: "",
                dashboard: dashboard?.id,
                schedule: "",
                enabled: false,
                output_format: "pdf",
                method: "email",
                email_body: "Hello!<br /><br/>Here is your automated email from Onvo AI.",
                email_subject: "",
                email_cc: [],
                email_to: account?.email || embedUser?.email,
                timezone: dayjs.tz.guess().replace("Calcutta", "Kolkata")
            });
            await getAllAutomations();
            return newAutomation;
        }, {
            loading: "Creating automation...",
            success: (newAutomation) => {
                // @ts-ignore
                setSelectedAutomation(newAutomation || null);
                return "Automation created"
            },
            error: (e: any) => {
                return "Error creating automation: " + e.message
            }
        })
    }

    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={createAutomation}>+ 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>)
}