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

export interface Draft {
  id: string;
  content: string;
  saved_at: string;
}

function createDraftsStore() {
  const drafts = writable<Draft[]>([]);
  const isLoading = writable(false);

  async function loadDrafts(): Promise<void> {
    isLoading.set(true);
    try {
      const list = await invoke<Draft[]>("list_drafts");
      drafts.set(list);
    } catch (error) {
      console.error("Failed to load drafts:", error);
    } finally {
      isLoading.set(false);
    }
  }

  async function saveDraft(content: string): Promise<Draft | null> {
    try {
      const draft = await invoke<Draft>("save_draft", { content });
      await loadDrafts();
      return draft;
    } catch (error) {
      console.error("Failed to save draft:", error);
      return null;
    }
  }

  async function deleteDraft(draftId: string): Promise<boolean> {
    try {
      await invoke("delete_draft", { draftId });
      await loadDrafts();
      return true;
    } catch (error) {
      console.error("Failed to delete draft:", error);
      return false;
    }
  }

  async function deleteAllDrafts(): Promise<boolean> {
    try {
      await invoke("delete_all_drafts");
      drafts.set([]);
      return true;
    } catch (error) {
      console.error("Failed to delete all drafts:", error);
      return false;
    }
  }

  function formatTimestamp(isoString: string): string {
    const date = new Date(isoString);
    if (isNaN(date.getTime())) {
      return isoString;
    }
    try {
      return date.toLocaleString(undefined, {
        month: "short",
        day: "numeric",
        hour: "numeric",
        minute: "2-digit",
      });
    } catch {
      return isoString;
    }
  }

  return {
    drafts: { subscribe: drafts.subscribe },
    isLoading: { subscribe: isLoading.subscribe },
    loadDrafts,
    saveDraft,
    deleteDraft,
    deleteAllDrafts,
    formatTimestamp,
  };
}

export const draftsStore = createDraftsStore();
