'use client';

import { useState, useCallback } from 'react';

interface LibrarySwitchState {
  isLoading: boolean;
  targetLibraryName: string | null;
  error: string | null;
}

interface LibrarySwitchResult {
  state: LibrarySwitchState;
  switchLibrary: (password: string) => Promise<boolean>;
  clearError: () => void;
  reset: () => void;
}

export function useLibrarySwitch(): LibrarySwitchResult {
  const [state, setState] = useState<LibrarySwitchState>({
    isLoading: false,
    targetLibraryName: null,
    error: null,
  });

  const switchLibrary = useCallback(async (password: string): Promise<boolean> => {
    setState({
      isLoading: true,
      targetLibraryName: null,
      error: null,
    });

    try {
      const response = await fetch('/api/libraries/switch', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ password }),
      });

      const data = await response.json();

      if (!response.ok) {
        setState(prev => ({
          ...prev,
          isLoading: false,
          error: data.error || 'Failed to switch library',
        }));
        return false;
      }

      if (data.status === 'already_active') {
        setState(prev => ({
          ...prev,
          isLoading: false,
          error: data.message,
        }));
        return false;
      }

      if (data.status === 'switching') {
        // Get library name if available
        try {
          const librariesResponse = await fetch('/api/libraries');
          if (librariesResponse.ok) {
            const libraries = await librariesResponse.json();
            const targetLibrary = libraries.find((lib: any) => lib.id === data.targetLibrary);
            setState(prev => ({
              ...prev,
              targetLibraryName: targetLibrary?.name || data.targetLibrary,
            }));
          }
        } catch (e) {
          // Continue without library name
        }
        
        return true; // Switch initiated successfully
      }

      setState(prev => ({
        ...prev,
        isLoading: false,
        error: 'Unexpected response from server',
      }));
      return false;

    } catch (error) {
      setState(prev => ({
        ...prev,
        isLoading: false,
        error: 'Network error occurred',
      }));
      return false;
    }
  }, []);

  const clearError = useCallback(() => {
    setState(prev => ({
      ...prev,
      error: null,
    }));
  }, []);

  const reset = useCallback(() => {
    setState({
      isLoading: false,
      targetLibraryName: null,
      error: null,
    });
  }, []);

  return {
    state,
    switchLibrary,
    clearError,
    reset,
  };
}