import { useState, useEffect } from 'react';
import { X, Check } from 'lucide-react';
import { shire } from '@/api/shireClient';
import { toast } from 'sonner';

export default function UpdateProductModal({ results, onClose }) {
  const [products, setProducts] = useState([]);
  const [selectedId, setSelectedId] = useState('');
  const [saving, setSaving] = useState(false);
  const [loading, setLoading] = useState(true);

  const cp = Math.round(results.consumerPrice * 100) / 100;

  useEffect(() => {
    shire.entities.Product.list('title', 500).then(data => {
      setProducts(data);
      setLoading(false);
    });
  }, []);

  const handleUpdate = async () => {
    if (!selectedId) return;
    setSaving(true);
    await shire.entities.Product.update(selectedId, {
      price: cp,
      etsy_price: cp,
      square_price: cp,
      ebay_price: cp,
    });
    setSaving(false);
    toast.success('✅ Price updated in database!');
    onClose();
  };

  const overlayStyle = { background: 'rgba(0,0,0,0.75)', backdropFilter: 'blur(4px)' };
  const modalStyle = {
    background: '#1a1a2e',
    border: '1px solid rgba(107,47,179,0.5)',
    boxShadow: '0 0 60px rgba(107,47,179,0.3)',
  };
  const inputStyle = { background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)', color: 'white' };
  const inputClass = 'w-full px-3 py-2.5 text-sm rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 text-white';

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={overlayStyle}>
      <div className="w-full max-w-md rounded-2xl overflow-hidden" style={modalStyle}>
        <div className="flex items-center justify-between px-5 py-4" style={{ borderBottom: '1px solid rgba(107,47,179,0.2)' }}>
          <h2 className="font-bold text-white">📦 Update Existing Product</h2>
          <button onClick={onClose} className="transition-colors" style={{ color: 'rgba(200,180,255,0.5)' }}
            onMouseEnter={e => e.target.style.color = 'white'} onMouseLeave={e => e.target.style.color = 'rgba(200,180,255,0.5)'}>
            <X size={18} />
          </button>
        </div>

        <div className="p-5 space-y-4">
          <div className="rounded-xl p-4 text-center" style={{ background: 'rgba(124,58,237,0.1)', border: '1px solid rgba(124,58,237,0.3)' }}>
            <p className="text-xs mb-1" style={{ color: 'rgba(200,180,255,0.6)' }}>Price to apply to all marketplaces</p>
            <p className="text-3xl font-black text-white">${cp.toFixed(2)}</p>
            <p className="text-xs mt-1" style={{ color: 'rgba(200,180,255,0.4)' }}>Updates: price · etsy_price · square_price · ebay_price</p>
          </div>

          <div>
            <label className="block text-xs font-medium mb-2" style={{ color: 'rgba(200,180,255,0.7)' }}>Select Product</label>
            {loading ? (
              <div className="flex justify-center py-4">
                <div className="w-5 h-5 border-2 border-purple-400/30 border-t-purple-400 rounded-full animate-spin" />
              </div>
            ) : (
              <select value={selectedId} onChange={e => setSelectedId(e.target.value)}
                className={inputClass} style={inputStyle}>
                <option value="">Select a product…</option>
                {products.map(p => <option key={p.id} value={p.id}>{p.title}</option>)}
              </select>
            )}
          </div>

          <div className="flex gap-3 pt-1">
            <button onClick={onClose} className="flex-1 py-2.5 rounded-xl text-sm font-semibold border transition-all hover:bg-white/5"
              style={{ color: 'rgba(200,180,255,0.7)', borderColor: 'rgba(107,47,179,0.3)' }}>
              Cancel
            </button>
            <button onClick={handleUpdate} disabled={!selectedId || saving}
              className="flex-1 py-2.5 rounded-xl text-white text-sm font-bold flex items-center justify-center gap-2 transition-all disabled:opacity-40"
              style={{ background: 'linear-gradient(135deg, #7c3aed, #6366f1)' }}>
              {saving
                ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                : <><Check size={14} /> Apply Price</>}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}