
import { Automation, Onvo } from "@onvo-ai/js";
import { create } from "zustand";
import { Dashboard } from "@onvo-ai/js";
import { toast } from "sonner";
import dayjs from "dayjs";

export const useAutomationsModal = create<{
    open: boolean;
    setOpen: (open: boolean) => void;
    automations: Automation[];
    selectedAutomation: Automation | null;
    setSelectedAutomation: (selectedAutomation: Partial<Automation> | null) => void;
    saveAutomation: () => Promise<void>;
    getAllAutomations: (backend: Onvo, dashboardId: string) => Promise<void>;
    createAutomation: (backend: Onvo, dashboard: Dashboard, automations: Automation[], account?: any, embedUser?: any) => Promise<void>;
}>((set, get) => ({
    open: false,
    setOpen: (op: boolean) => set({ open: op }),
    automations: [],
    selectedAutomation: null,
    getAllAutomations: async (backend: Onvo, dashboardId: string) => {
        if (!backend || !dashboardId) return;
        const response = await backend.automations.list({
            dashboard: dashboardId,
        });
        set({ automations: response });
        if (response.length > 0 && !get().selectedAutomation?.id) {
            get().setSelectedAutomation(response[0]);
        }
    },
    createAutomation: async (backend: Onvo, dashboard: Dashboard, automations: Automation[], account?: any, embedUser?: any) => {
        toast.promise(
            async () => {
                let newAutomation = await backend?.automations.create({
                    title: "Automation " + (automations.length + 1),
                    description: "",
                    dashboard: dashboard?.id,
                    schedule: "0 9 * * 1",
                    enabled: true,
                    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 get().getAllAutomations(backend, dashboard.id);
                return newAutomation;
            },
            {
                loading: "Creating automation...",
                success: (newAutomation) => {
                    get().setSelectedAutomation(newAutomation || null);
                    return "Automation created";
                },
                error: (e: any) => {
                    return "Error creating automation: " + e.message;
                }
            }
        );
    },
    saveAutomation: async () => { },
    setSelectedAutomation: (updatedAutomation: Partial<Automation> | null) => {
        if (updatedAutomation === null) return set({ selectedAutomation: null });
        let automation = get().selectedAutomation;
        set({
            selectedAutomation: {
                ...(automation as Automation),
                ...updatedAutomation
            }
        });
    }
}));
