import { useEffect, useMemo, useState } from 'react';
import type { BatchIdComboboxOption } from '@/components/shared/BatchIdCombobox';
import { fetchAllBatchIds } from '@/services/batchService';
import type { ProcurementBatch } from '@/types';

export function mapProcurementBatchesToOptions(batches: ProcurementBatch[]): BatchIdComboboxOption[] {
  return batches.map((batch) => ({
    value: batch.batch_id,
    label: batch.name ? `${batch.batch_id}（${batch.name}）` : batch.batch_id,
    searchText: batch.name ? `${batch.batch_id} ${batch.name}` : batch.batch_id,
  }));
}

export function useProcurementBatchOptions() {
  const [batches, setBatches] = useState<ProcurementBatch[]>([]);

  useEffect(() => {
    let cancelled = false;

    (async () => {
      try {
        const data = await fetchAllBatchIds();
        if (!cancelled) {
          setBatches(data);
        }
      } catch (error) {
        console.error('Failed to fetch procurement batches:', error);
      }
    })();

    return () => {
      cancelled = true;
    };
  }, []);

  const batchOptions = useMemo(() => mapProcurementBatchesToOptions(batches), [batches]);

  return {
    batches,
    batchOptions,
  };
}