import { memo, useMemo } from 'react';
import { Handle, Position, type NodeProps } from '@xyflow/react';
import { Database } from 'lucide-react';

export const DatabaseNode = memo(({ data, selected }: NodeProps) => {
  const label = (data as { label?: string }).label ?? 'Database';
  
  const meta = useMemo(() => {
    try {
      return (data as any).metadata ? JSON.parse((data as any).metadata) : {};
    } catch {
      return {};
    }
  }, [data]);
  
  const hasAddress = meta.ipAddress || meta.port;
  return (
    <div className={`min-w-[140px] bg-slate-800 border rounded-lg shadow-lg overflow-hidden ${selected ? 'ring-2 ring-teal-500 border-teal-500' : 'border-teal-700'}`}>
      <Handle type="target" position={Position.Top} className="!bg-teal-400 !border-teal-600" />
      <div className="px-3 py-2 flex flex-col gap-1">
        <div className="flex items-center gap-2">
          <Database size={13} className="text-teal-400 shrink-0" />
          <span className="text-xs font-medium text-slate-100 truncate">{label}</span>
        </div>
        {hasAddress && (
          <div className="text-[10px] text-slate-400 font-mono pl-[21px] truncate">
            {meta.ipAddress}
            {meta.ipAddress && meta.port && ':'}
            {meta.port}
          </div>
        )}
      </div>
      <Handle type="source" position={Position.Bottom} className="!bg-teal-400 !border-teal-600" />
    </div>
  );
});
DatabaseNode.displayName = 'DatabaseNode';
