import { useState, useEffect, useCallback } from 'react';

interface MusicApiKeys {
  youtubeApiKey: string;
  soundcloudClientId: string;
}

const STORAGE_KEY = 'music-api-keys';

export const useMusicApiKeys = () => {
  const [apiKeys, setApiKeys] = useState<MusicApiKeys>({
    youtubeApiKey: '',
    soundcloudClientId: '',
  });
  const [isLoaded, setIsLoaded] = useState(false);

  useEffect(() => {
    const stored = localStorage.getItem(STORAGE_KEY);
    if (stored) {
      try {
        setApiKeys(JSON.parse(stored));
      } catch (e) {
        console.error('Failed to parse stored API keys');
      }
    }
    setIsLoaded(true);
  }, []);

  const saveApiKeys = useCallback((keys: Partial<MusicApiKeys>) => {
    setApiKeys(prev => {
      const updated = { ...prev, ...keys };
      localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
      return updated;
    });
  }, []);

  const clearApiKeys = useCallback(() => {
    localStorage.removeItem(STORAGE_KEY);
    setApiKeys({ youtubeApiKey: '', soundcloudClientId: '' });
  }, []);

  const hasYoutubeKey = Boolean(apiKeys.youtubeApiKey);
  const hasSoundcloudKey = Boolean(apiKeys.soundcloudClientId);

  return {
    apiKeys,
    saveApiKeys,
    clearApiKeys,
    hasYoutubeKey,
    hasSoundcloudKey,
    isLoaded,
  };
};
