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

export default function BulkPriceModal({ products, onClose, onDone }) {
  const [target, setTarget] = useState('all');
  const [category, setCategory] = useState('');
  const [direction, setDirection] = useState('increase');
  const [pct, setPct] = useState('');
  const [applying, setApplying] = useState(false);

  const categories = [...new Set(products.map(p => p.category).filter(Boolean))];

  const affected = products.filter(p =>
    target === 'all' || p.category === category
  );

  const multiplier = direction === 'increase' ? 1 + (parseFloat(pct) || 0) / 100 : 1 - (parseFloat(pct) || 0) / 100;

  const exampleProduct = affected[0];
  const exampleOld = exampleProduct?.price || 0;
  const exampleNew = (exampleOld * multiplier).toFixed(2);

  const handleApply = async () => {
    if (!pct || isNaN(parseFloat(pct))) return;
    setApplying(true);
    await Promise.all(
      affected.map(p =>
        shire.entities.Product.update(p.id, {
          price: parseFloat((p.price * multiplier).toFixed(2)),
          etsy_price: p.etsy_price ? parseFloat((p.etsy_price * multiplier).toFixed(2)) : undefined,
          square_price: p.square_price ? parseFloat((p.square_price * multiplier).toFixed(2)) : undefined,
          ebay_price: p.ebay_price ? parseFloat((p.ebay_price * multiplier).toFixed(2)) : undefined,
        })
      )
    );
    setApplying(false);
    onDone();
  };

  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">Bulk % Price Change</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-4">
          {/* Target */}
          <div>
            <label className="block text-xs font-medium text-gray-600 mb-1">Apply to</label>
            <select
              value={target}
              onChange={e => setTarget(e.target.value)}
              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"
            >
              <option value="all">All Products</option>
              <option value="category">Specific Category</option>
            </select>
          </div>
          {target === 'category' && (
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Category</label>
              <select
                value={category}
                onChange={e => setCategory(e.target.value)}
                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"
              >
                <option value="">Select…</option>
                {categories.map(c => <option key={c} value={c}>{c}</option>)}
              </select>
            </div>
          )}

          {/* Direction + Pct */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Direction</label>
              <select
                value={direction}
                onChange={e => setDirection(e.target.value)}
                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"
              >
                <option value="increase">Increase</option>
                <option value="decrease">Decrease</option>
              </select>
            </div>
            <div>
              <label className="block text-xs font-medium text-gray-600 mb-1">Percentage (%)</label>
              <input
                type="number"
                min="0"
                max="100"
                value={pct}
                onChange={e => setPct(e.target.value)}
                placeholder="e.g. 10"
                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>

          {/* Preview */}
          {pct && (
            <div className="bg-orange-50 border border-orange-100 rounded-lg px-4 py-3 text-sm">
              <p className="text-gray-700 font-medium">Preview</p>
              <p className="text-gray-600 mt-1">{affected.length} product{affected.length !== 1 ? 's' : ''} affected</p>
              {exampleProduct && (
                <p className="text-gray-600">
                  E.g. "{exampleProduct.title?.slice(0, 30)}…" → ${exampleOld.toFixed(2)} → <strong>${exampleNew}</strong>
                </p>
              )}
            </div>
          )}
        </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={handleApply}
            disabled={applying || !pct}
            className="flex-1 py-2.5 rounded-lg text-white text-sm font-semibold transition-opacity disabled:opacity-60"
            style={{ background: '#f97316' }}
          >
            {applying ? 'Applying…' : 'Confirm'}
          </button>
        </div>
      </div>
    </div>
  );
}