import { useState } from 'react';
import { X } from 'lucide-react';
import { shire } from '@/api/shireClient';

export default function AddUrlModal({ product, marketplace, onClose, onSaved }) {
  const [url, setUrl] = useState('');
  const [saving, setSaving] = useState(false);

  const fieldMap = { Etsy: 'etsy_url', Square: 'square_url', eBay: 'ebay_url' };

  const handleSave = async () => {
    if (!url.trim()) return;
    setSaving(true);
    await shire.entities.Product.update(product.id, { [fieldMap[marketplace]]: url.trim() });
    setSaving(false);
    onSaved();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-md">
        <div className="flex items-center justify-between px-6 py-4 border-b border-gray-100">
          <h2 className="font-semibold text-gray-900">Add {marketplace} URL</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-gray-700"><X size={20} /></button>
        </div>
        <div className="px-6 py-5 space-y-3">
          <p className="text-sm text-gray-600">Product: <span className="font-medium">{product?.title}</span></p>
          <input
            type="url"
            value={url}
            onChange={e => setUrl(e.target.value)}
            placeholder={`Paste ${marketplace} listing URL…`}
            autoFocus
            className="w-full px-3 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400"
          />
        </div>
        <div className="px-6 pb-5 flex gap-3">
          <button onClick={onClose} className="flex-1 py-2.5 rounded-lg border border-gray-200 text-sm font-medium text-gray-600 hover:bg-gray-50">
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={saving || !url.trim()}
            className="flex-1 py-2.5 rounded-lg text-white text-sm font-semibold transition-opacity disabled:opacity-60"
            style={{ background: '#f97316' }}
          >
            {saving ? 'Saving…' : 'Save URL'}
          </button>
        </div>
      </div>
    </div>
  );
}