Can a company legally tell you that you can't take a prescription pain medication at work?

It depends. The answer depends on the laws in your state. There is a legal basis for employers to be able to restrict an employee from working while taking prescription pain medications to prevent injuries from occuring while working "under the influence". The same is true for driving and taking these medications which could result in a driving under the influence citation.
Certainly. If, for example, you are taking sedating medications that preclude you from operating heavy equipment, then your company would be liable for any damage you caused while under the influence of your meds. Just because something is prescribed doesn't mean that you take it and then do whatever you want. You can get a ticket for driving under the influence of legally prescribed drugs.
Depends.. Depends upon the medication, the company policy, and the type of work you perform during the day. All will have to be evaluated to determine any risk of harm to yourself or others before your question can be adequately discussed.