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

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

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

  const handlePush = async () => {
    if (!selectedId) return;
    setSaving(true);
    const rounded = Math.round(consumerPrice * 100) / 100;
    await shire.entities.Product.update(selectedId, {
      price: rounded,
      etsy_price: rounded,
      square_price: rounded,
    });
    setSaving(false);
    toast.success('✅ Price updated in database!');
    onClose();
  };

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4" style={{ background: 'rgba(0,0,0,0.7)' }}>
      <div className="w-full max-w-md rounded-2xl overflow-hidden" style={{
        background: '#1a1a2e',
        border: '1px solid rgba(107,47,179,0.5)',
        boxShadow: '0 0 40px rgba(107,47,179,0.3)',
      }}>
        <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">🚀 Push to Product</h2>
          <button onClick={onClose} className="text-white/40 hover:text-white transition-colors"><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)' }}>Consumer Price to apply</p>
            <p className="text-3xl font-black text-white">${consumerPrice.toFixed(2)}</p>
            <p className="text-xs mt-1" style={{ color: 'rgba(200,180,255,0.4)' }}>Will update: price, etsy_price, square_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="w-full px-3 py-2.5 text-sm text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500"
                style={{ background: '#0d0d1a', border: '1px solid rgba(107,47,179,0.3)' }}
              >
                <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">
            <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={handlePush}
              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, #f97316)' }}
            >
              {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>
  );
}