import { useEffect, useState, useRef } from 'react';
import { shire } from '@/api/shireClient';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Search, ExternalLink, Percent, Sparkles } from 'lucide-react';
import ProductSidePanel from '@/components/products/ProductSidePanel';
import BulkPriceModal from '@/components/products/BulkPriceModal';

const MktBadge = ({ url, label }) =>
  url ? (
    <a href={url} target="_blank" rel="noreferrer"
      className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-green-100 text-green-700 font-medium hover:bg-green-200"
      onClick={e => e.stopPropagation()}
    >
      <span className="w-1.5 h-1.5 rounded-full bg-green-500 inline-block" />
      {label} <ExternalLink size={10} />
    </a>
  ) : (
    <span className="inline-flex items-center gap-1 text-xs px-2 py-0.5 rounded-full bg-red-100 text-red-600 font-medium">
      ✗ {label}
    </span>
  );

export default function Products() {
  const navigate = useNavigate();
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');
  const [catFilter, setCatFilter] = useState('');
  const [selectedProduct, setSelectedProduct] = useState(null);
  const [showBulk, setShowBulk] = useState(false);
  const [editingPriceId, setEditingPriceId] = useState(null);
  const [priceVal, setPriceVal] = useState('');
  const [searchParams] = useSearchParams();
  const priceInputRef = useRef();

  const fetchProducts = () => {
    shire.entities.Product.list('-created_date', 500).then(data => {
      setProducts(data);
      setLoading(false);

      // Handle ?edit= param from dashboard
      const editId = searchParams.get('edit');
      if (editId) {
        const p = data.find(p => p.id === editId);
        if (p) setSelectedProduct(p);
      }
    });
  };

  useEffect(() => { fetchProducts(); }, []);

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

  const filtered = products.filter(p => {
    const q = search.toLowerCase();
    const matchSearch = !q || p.title?.toLowerCase().includes(q) || p.category?.toLowerCase().includes(q);
    const matchCat = !catFilter || p.category === catFilter;
    return matchSearch && matchCat;
  });

  const startPriceEdit = (e, p) => {
    e.stopPropagation();
    setEditingPriceId(p.id);
    setPriceVal(p.price ?? '');
    setTimeout(() => priceInputRef.current?.focus(), 0);
  };

  const savePriceEdit = async (product) => {
    const newPrice = parseFloat(priceVal);
    if (!isNaN(newPrice) && newPrice !== product.price) {
      await shire.entities.Product.update(product.id, { price: newPrice });
      setProducts(prev => prev.map(p => p.id === product.id ? { ...p, price: newPrice } : p));
    }
    setEditingPriceId(null);
  };

  const handleSaved = () => {
    setSelectedProduct(null);
    fetchProducts();
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="w-8 h-8 border-4 border-orange-200 border-t-orange-500 rounded-full animate-spin" />
      </div>
    );
  }

  return (
    <div className="p-6 md:p-8 max-w-7xl mx-auto space-y-5">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
        <h1 className="text-2xl font-bold text-gray-900">Products <span className="text-gray-400 text-lg font-normal">({filtered.length})</span></h1>
        <div className="flex gap-2 flex-wrap">
          <button
            onClick={() => navigate('/products/create')}
            className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg text-white text-sm font-bold transition-all shadow-sm"
            style={{ background: 'linear-gradient(135deg, #7c3aed, #f97316)' }}
          >
            <Sparkles size={15} /> ➕ New Product
          </button>
          <button
            onClick={() => setShowBulk(true)}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-200 text-gray-700 text-sm font-semibold hover:bg-gray-50 transition-all"
          >
            <Percent size={15} /> Bulk % Price Change
          </button>
        </div>
      </div>

      {/* Filters */}
      <div className="flex flex-col sm:flex-row gap-3">
        <div className="relative flex-1 max-w-sm">
          <Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400" />
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder="Search products…"
            className="w-full pl-9 pr-4 py-2 text-sm border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-orange-400 bg-white"
          />
        </div>
        <select
          value={catFilter}
          onChange={e => setCatFilter(e.target.value)}
          className="px-3 py-2 text-sm border border-gray-200 rounded-lg bg-white focus:outline-none focus:ring-2 focus:ring-orange-400"
        >
          <option value="">All Categories</option>
          {categories.map(c => <option key={c} value={c}>{c}</option>)}
        </select>
      </div>

      {/* Table */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm min-w-[700px]">
            <thead>
              <tr className="bg-gray-50 text-gray-500 text-xs uppercase tracking-wide">
                <th className="px-4 py-3 text-left w-16">Image</th>
                <th className="px-4 py-3 text-left">Title</th>
                <th className="px-4 py-3 text-left">Category</th>
                <th className="px-4 py-3 text-left">Base Price</th>
                <th className="px-4 py-3 text-left">Etsy</th>
                <th className="px-4 py-3 text-left">Square</th>
                <th className="px-4 py-3 text-left">eBay</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {filtered.length === 0 ? (
                <tr>
                  <td colSpan={7} className="px-4 py-12 text-center text-gray-400">
                    No products found.
                  </td>
                </tr>
              ) : (
                filtered.map(product => (
                  <tr
                    key={product.id}
                    onClick={() => setSelectedProduct(product)}
                    className="hover:bg-orange-50/50 cursor-pointer transition-colors"
                  >
                    <td className="px-4 py-3">
                      {product.image_url ? (
                        <img src={product.image_url} alt="" className="w-10 h-10 object-cover rounded-lg" />
                      ) : (
                        <div className="w-10 h-10 bg-gray-100 rounded-lg flex items-center justify-center text-gray-300 text-lg">📦</div>
                      )}
                    </td>
                    <td className="px-4 py-3 font-medium text-gray-900 max-w-[200px] truncate">{product.title}</td>
                    <td className="px-4 py-3 text-gray-500">{product.category || '—'}</td>
                    <td className="px-4 py-3" onClick={e => e.stopPropagation()}>
                      {editingPriceId === product.id ? (
                        <input
                          ref={priceInputRef}
                          type="number"
                          value={priceVal}
                          onChange={e => setPriceVal(e.target.value)}
                          onBlur={() => savePriceEdit(product)}
                          onKeyDown={e => { if (e.key === 'Enter') savePriceEdit(product); if (e.key === 'Escape') setEditingPriceId(null); }}
                          className="w-24 px-2 py-1 border border-orange-400 rounded text-sm focus:outline-none"
                        />
                      ) : (
                        <span
                          onClick={e => startPriceEdit(e, product)}
                          className="cursor-pointer hover:text-orange-600 font-medium text-gray-800"
                          title="Click to edit"
                        >
                          ${(product.price || 0).toFixed(2)}
                        </span>
                      )}
                    </td>
                    <td className="px-4 py-3"><MktBadge url={product.etsy_url} label="Etsy" /></td>
                    <td className="px-4 py-3"><MktBadge url={product.square_url} label="Square" /></td>
                    <td className="px-4 py-3"><MktBadge url={product.ebay_url} label="eBay" /></td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>
      </div>

      {/* Side panel */}
      {selectedProduct && (
        <ProductSidePanel
          product={selectedProduct}
          onClose={() => setSelectedProduct(null)}
          onSaved={handleSaved}
        />
      )}

      {/* Bulk modal */}
      {showBulk && (
        <BulkPriceModal
          products={products}
          onClose={() => setShowBulk(false)}
          onDone={() => { setShowBulk(false); fetchProducts(); }}
        />
      )}
    </div>
  );
}
