import { useState, useCallback } from 'react';
import type {
  StorageLocationDTO,
  CreateStorageLocationRequest,
  UpdateStorageLocationRequest,
  StorageLocationFilter,
} from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface StorageLocationsState {
  storageLocations: StorageLocationDTO[];
  loading: boolean;
  error: string | null;
}

function errorMessage(err: unknown): string {
  return err instanceof Error ? err.message : 'Unbekannter Fehler';
}

export function useStorageLocations() {
  const [state, setState] = useState<StorageLocationsState>({
    storageLocations: [],
    loading: false,
    error: null,
  });

  const fetchStorageLocations = useCallback(async (filter?: StorageLocationFilter) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const storageLocations = await client.storageLocations.list(filter);
      setState({ storageLocations, loading: false, error: null });
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
    }
  }, []);

  const createStorageLocation = useCallback(async (request: CreateStorageLocationRequest) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const location = await client.storageLocations.create(request);
      setState((s) => ({ storageLocations: [...s.storageLocations, location], loading: false, error: null }));
      return location;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const updateStorageLocation = useCallback(async (id: string, request: UpdateStorageLocationRequest) => {
    try {
      const updated = await client.storageLocations.update(id, request);
      setState((s) => ({
        ...s,
        storageLocations: s.storageLocations.map((loc) => (loc.id === id ? updated : loc)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const activateStorageLocation = useCallback(async (id: string) => {
    try {
      const updated = await client.storageLocations.activate(id);
      setState((s) => ({
        ...s,
        storageLocations: s.storageLocations.map((loc) => (loc.id === id ? updated : loc)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const deactivateStorageLocation = useCallback(async (id: string) => {
    try {
      const updated = await client.storageLocations.deactivate(id);
      setState((s) => ({
        ...s,
        storageLocations: s.storageLocations.map((loc) => (loc.id === id ? updated : loc)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

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

  return {
    ...state,
    fetchStorageLocations,
    createStorageLocation,
    updateStorageLocation,
    activateStorageLocation,
    deactivateStorageLocation,
    clearError,
  };
}
