"use client";

import { useState, useEffect, useCallback } from "react";
import { useStorage } from "@/core/storage";
import { v4 as uuid } from "uuid";
import type { SignatureConfig, SavedSignature } from "../types";

export function useSavedSignatures() {
  const storage = useStorage("email-signature");
  const [saved, setSaved] = useState<SavedSignature[]>([]);
  const [loading, setLoading] = useState(true);

  const refresh = useCallback(async () => {
    setLoading(true);
    const all = await storage.exportAll();
    const items: SavedSignature[] = [];
    for (const [key, value] of Object.entries(all)) {
      if (key.startsWith("sig:") && value) {
        items.push(value as SavedSignature);
      }
    }
    items.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
    setSaved(items);
    setLoading(false);
  }, [storage]);

  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => {
    refresh();
  }, [refresh]);

  const save = useCallback(
    async (label: string, config: SignatureConfig) => {
      const now = new Date().toISOString();
      const entry: SavedSignature = {
        id: uuid(),
        label,
        config,
        createdAt: now,
        updatedAt: now,
      };
      await storage.set(`sig:${entry.id}`, entry);
      await refresh();
      return entry;
    },
    [storage, refresh],
  );

  const remove = useCallback(
    async (id: string) => {
      await storage.delete(`sig:${id}`);
      await refresh();
    },
    [storage, refresh],
  );

  return { saved, loading, save, remove, refresh };
}
