import { useState, useCallback } from 'react';
import type { StockMovementDTO, RecordStockMovementRequest, StockMovementFilter } from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface StockMovementsState {
  movements: StockMovementDTO[];
  movement: StockMovementDTO | null;
  loading: boolean;
  error: string | null;
}

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

export function useStockMovements() {
  const [state, setState] = useState<StockMovementsState>({
    movements: [],
    movement: null,
    loading: false,
    error: null,
  });

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

  const fetchMovement = useCallback(async (id: string) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const movement = await client.stockMovements.getById(id);
      setState((s) => ({ ...s, movement, loading: false, error: null }));
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
    }
  }, []);

  const recordMovement = useCallback(async (request: RecordStockMovementRequest) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const movement = await client.stockMovements.record(request);
      setState((s) => ({ ...s, movement, loading: false, error: null }));
      return movement;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

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

  return {
    ...state,
    fetchMovements,
    fetchMovement,
    recordMovement,
    clearError,
  };
}
