/**
 * React hook for managing custom XBRL concept mappings.
 */

import { useCallback, useEffect, useState } from 'react';
import { mappingsBridge } from '../lib/mappingsBridge';
import type { CustomXbrlConceptMapping } from '../types/mappings';

interface UseMappingsResult {
  /** All custom mappings */
  mappings: CustomXbrlConceptMapping[];
  /** Whether data is being loaded */
  isLoading: boolean;
  /** Error that occurred during operations */
  error: Error | null;
  /** Add a new mapping */
  addMapping: (mapping: CustomXbrlConceptMapping) => Promise<void>;
  /** Update an existing mapping */
  updateMapping: (
    id: string,
    mapping: CustomXbrlConceptMapping
  ) => Promise<void>;
  /** Delete a mapping */
  deleteMapping: (id: string) => Promise<void>;
  /** Toggle the enabled state of a mapping */
  toggleMapping: (id: string) => Promise<void>;
  /** Import mappings from JSON */
  importMappings: (json: string) => Promise<void>;
  /** Export mappings to JSON */
  exportMappings: () => Promise<string>;
  /** Reload all mappings */
  reload: () => Promise<void>;
}

/**
 * Hook for managing custom XBRL concept mappings.
 */
export function useMappings(): UseMappingsResult {
  const [mappings, setMappings] = useState<CustomXbrlConceptMapping[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);

  const loadMappings = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      const data = await mappingsBridge.listMappings();
      console.log('[useMappings] Loaded mappings:', data);
      console.log('[useMappings] Number of mappings:', data.length);
      console.log('[useMappings] Mappings with null/undefined:', data.filter(m => m == null).length);
      setMappings(data);
    } catch (e) {
      setError(e as Error);
      console.error('Failed to load mappings:', e);
    } finally {
      setIsLoading(false);
    }
  }, []);

  const addMapping = useCallback(async (mapping: CustomXbrlConceptMapping) => {
    setError(null);
    try {
      await mappingsBridge.addMapping(mapping);
      await loadMappings();
    } catch (e) {
      setError(e as Error);
      console.error('Failed to add mapping:', e);
      throw e;
    }
  }, [loadMappings]);

  const updateMapping = useCallback(
    async (id: string, mapping: CustomXbrlConceptMapping) => {
      setError(null);
      try {
        await mappingsBridge.updateMapping(id, mapping);
        await loadMappings();
      } catch (e) {
        setError(e as Error);
        console.error('Failed to update mapping:', e);
        throw e;
      }
    },
    [loadMappings]
  );

  const deleteMapping = useCallback(async (id: string) => {
    setError(null);
    try {
      await mappingsBridge.deleteMapping(id);
      await loadMappings();
    } catch (e) {
      setError(e as Error);
      console.error('Failed to delete mapping:', e);
      throw e;
    }
  }, [loadMappings]);

  const toggleMapping = useCallback(async (id: string) => {
    setError(null);
    try {
      await mappingsBridge.toggleMapping(id);
      await loadMappings();
    } catch (e) {
      setError(e as Error);
      console.error('Failed to toggle mapping:', e);
      throw e;
    }
  }, [loadMappings]);

  const importMappings = useCallback(async (json: string) => {
    setError(null);
    try {
      await mappingsBridge.importMappings(json);
      await loadMappings();
    } catch (e) {
      setError(e as Error);
      console.error('Failed to import mappings:', e);
      throw e;
    }
  }, [loadMappings]);

  const exportMappings = useCallback(async () => {
    setError(null);
    try {
      return await mappingsBridge.exportMappings();
    } catch (e) {
      setError(e as Error);
      console.error('Failed to export mappings:', e);
      throw e;
    }
  }, []);

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

  return {
    mappings,
    isLoading,
    error,
    addMapping,
    updateMapping,
    deleteMapping,
    toggleMapping,
    importMappings,
    exportMappings,
    reload: loadMappings,
  };
}
