'use client';

import { useState, useEffect, useCallback } from 'react';
import { shareStorage, ShareEntry } from '@/lib/storage';

interface UseShareStorageReturn {
  shares: Omit<ShareEntry, 'encryptedShare' | 'iv' | 'salt'>[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  saveShare: (
    share: Omit<ShareEntry, 'encryptedShare' | 'iv' | 'salt'> & { rawShare: string },
    password: string
  ) => Promise<void>;
  getShare: (id: string, password: string) => Promise<{ share: ShareEntry; rawShare: string }>;
  deleteShare: (id: string) => Promise<void>;
  exportShare: (id: string, password: string) => Promise<string>;
  importShare: (data: string, password: string) => Promise<void>;
}

/**
 * React hook for TSS share storage operations
 */
export function useShareStorage(): UseShareStorageReturn {
  const [shares, setShares] = useState<Omit<ShareEntry, 'encryptedShare' | 'iv' | 'salt'>[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const list = await shareStorage.listShares();
      setShares(list);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Failed to load shares';
      setError(errorMessage);
      console.error('Failed to load shares:', err);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const saveShare = useCallback(
    async (
      share: Omit<ShareEntry, 'encryptedShare' | 'iv' | 'salt'> & { rawShare: string },
      password: string
    ) => {
      await shareStorage.saveShare(share, password);
      await refresh();
    },
    [refresh]
  );

  const getShare = useCallback(
    async (id: string, password: string) => {
      return shareStorage.getShare(id, password);
    },
    []
  );

  const deleteShare = useCallback(
    async (id: string) => {
      await shareStorage.deleteShare(id);
      await refresh();
    },
    [refresh]
  );

  const exportShare = useCallback(
    async (id: string, password: string) => {
      return shareStorage.exportShare(id, password);
    },
    []
  );

  const importShare = useCallback(
    async (data: string, password: string) => {
      await shareStorage.importShare(data, password);
      await refresh();
    },
    [refresh]
  );

  useEffect(() => {
    refresh();
  }, [refresh]);

  return {
    shares,
    isLoading,
    error,
    refresh,
    saveShare,
    getShare,
    deleteShare,
    exportShare,
    importShare,
  };
}
