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

interface ProductionOrdersState {
  productionOrder: ProductionOrderDTO | null;
  loading: boolean;
  error: string | null;
}

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

export function useProductionOrders() {
  const [state, setState] = useState<ProductionOrdersState>({
    productionOrder: null,
    loading: false,
    error: null,
  });

  const createProductionOrder = useCallback(async (request: CreateProductionOrderRequest) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const productionOrder = await client.productionOrders.create(request);
      setState({ productionOrder, loading: false, error: null });
      return productionOrder;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const releaseProductionOrder = useCallback(async (id: string) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const productionOrder = await client.productionOrders.release(id);
      setState({ productionOrder, loading: false, error: null });
      return productionOrder;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

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

  return {
    ...state,
    createProductionOrder,
    releaseProductionOrder,
    clearError,
  };
}
