import { writable } from "svelte/store";
import { invoke } from "@tauri-apps/api/core";

export interface QuickAction {
  id: string;
  name: string;
  prompt: string;
  icon: string;
  is_default: boolean;
  created_at: string;
  updated_at: string;
}

function createQuickActionsStore() {
  const actions = writable<QuickAction[]>([]);
  const isLoading = writable(false);

  async function loadQuickActions(): Promise<void> {
    isLoading.set(true);
    try {
      const actionList = await invoke<QuickAction[]>("list_quick_actions");
      actions.set(actionList);
    } catch (error) {
      console.error("Failed to load quick actions:", error);
    } finally {
      isLoading.set(false);
    }
  }

  async function saveQuickAction(action: QuickAction): Promise<boolean> {
    try {
      await invoke("save_quick_action", { action });
      await loadQuickActions();
      return true;
    } catch (error) {
      console.error("Failed to save quick action:", error);
      return false;
    }
  }

  async function createQuickAction(name: string, prompt: string, icon: string): Promise<boolean> {
    const now = new Date().toISOString();
    const action: QuickAction = {
      id: `custom-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
      name,
      prompt,
      icon,
      is_default: false,
      created_at: now,
      updated_at: now,
    };
    return saveQuickAction(action);
  }

  async function updateQuickAction(
    id: string,
    name: string,
    prompt: string,
    icon: string
  ): Promise<boolean> {
    const currentActions = await invoke<QuickAction[]>("list_quick_actions");
    const existing = currentActions.find((a) => a.id === id);

    if (!existing) {
      console.error("Quick action not found for update");
      return false;
    }

    const updated: QuickAction = {
      ...existing,
      name,
      prompt,
      icon,
      updated_at: new Date().toISOString(),
    };

    return saveQuickAction(updated);
  }

  async function deleteQuickAction(actionId: string): Promise<boolean> {
    try {
      await invoke("delete_quick_action", { actionId });
      await loadQuickActions();
      return true;
    } catch (error) {
      console.error("Failed to delete quick action:", error);
      return false;
    }
  }

  async function resetDefaults(): Promise<boolean> {
    try {
      await invoke("reset_default_quick_actions");
      await loadQuickActions();
      return true;
    } catch (error) {
      console.error("Failed to reset default quick actions:", error);
      return false;
    }
  }

  return {
    actions: { subscribe: actions.subscribe },
    isLoading: { subscribe: isLoading.subscribe },
    loadQuickActions,
    saveQuickAction,
    createQuickAction,
    updateQuickAction,
    deleteQuickAction,
    resetDefaults,
  };
}

export const quickActionsStore = createQuickActionsStore();
