import { useState, useCallback } from 'react';
import type {
  SupplierDTO,
  CreateSupplierRequest,
  UpdateSupplierRequest,
  RateSupplierRequest,
  AddCertificateRequest,
  RemoveCertificateRequest,
} from '@effigenix/api-client';
import { client } from '../utils/api-client.js';

interface SuppliersState {
  suppliers: SupplierDTO[];
  loading: boolean;
  error: string | null;
}

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

export function useSuppliers() {
  const [state, setState] = useState<SuppliersState>({
    suppliers: [],
    loading: false,
    error: null,
  });

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

  const createSupplier = useCallback(async (request: CreateSupplierRequest) => {
    setState((s) => ({ ...s, loading: true, error: null }));
    try {
      const supplier = await client.suppliers.create(request);
      setState((s) => ({ suppliers: [...s.suppliers, supplier], loading: false, error: null }));
      return supplier;
    } catch (err) {
      setState((s) => ({ ...s, loading: false, error: errorMessage(err) }));
      return null;
    }
  }, []);

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

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

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

  const rateSupplier = useCallback(async (id: string, request: RateSupplierRequest) => {
    try {
      const updated = await client.suppliers.rate(id, request);
      setState((s) => ({
        ...s,
        suppliers: s.suppliers.map((sup) => (sup.id === id ? updated : sup)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const addCertificate = useCallback(async (id: string, request: AddCertificateRequest) => {
    try {
      const updated = await client.suppliers.addCertificate(id, request);
      setState((s) => ({
        ...s,
        suppliers: s.suppliers.map((sup) => (sup.id === id ? updated : sup)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

  const removeCertificate = useCallback(async (id: string, request: RemoveCertificateRequest) => {
    try {
      const updated = await client.suppliers.removeCertificate(id, request);
      setState((s) => ({
        ...s,
        suppliers: s.suppliers.map((sup) => (sup.id === id ? updated : sup)),
      }));
      return updated;
    } catch (err) {
      setState((s) => ({ ...s, error: errorMessage(err) }));
      return null;
    }
  }, []);

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

  return {
    ...state,
    fetchSuppliers,
    createSupplier,
    updateSupplier,
    activateSupplier,
    deactivateSupplier,
    rateSupplier,
    addCertificate,
    removeCertificate,
    clearError,
  };
}
