'use client';

import React, { useEffect, useRef } from 'react';
import JsBarcode from 'jsbarcode';

interface BarcodeProps {
  value: string;
  displayValue?: boolean;
  format?: string;
  width?: number;
  height?: number;
  fontSize?: number;
  margin?: number;
}

export default function BarcodeGenerator({
  value,
  displayValue = true,
  format = 'CODE128',
  width = 2,
  height = 55,
  fontSize = 13,
  margin = 5
}: BarcodeProps) {
  const svgRef = useRef<SVGSVGElement | null>(null);

  useEffect(() => {
    if (svgRef.current && value) {
      try {
        JsBarcode(svgRef.current, value, {
          format,
          displayValue,
          width,
          height,
          fontSize,
          margin,
          font: 'monospace',
          textMargin: 4
        });
      } catch (err) {
        console.error('Error generating barcode for value:', value, err);
      }
    }
  }, [value, displayValue, format, width, height, fontSize, margin]);

  return <svg ref={svgRef} style={{ maxWidth: '100%', height: 'auto', display: 'block', margin: '0 auto' }} />;
}
