import { useEffect, useState } from 'react';
import { shire } from '@/api/shireClient';
import { ExternalLink, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';
import AddUrlModal from '@/components/marketplaces/AddUrlModal';

const TABS = ['Etsy', 'Square', 'eBay'];
const URL_FIELD = { Etsy: 'etsy_url', Square: 'square_url', eBay: 'ebay_url' };
const PRICE_FIELD = { Etsy: 'etsy_price', Square: 'square_price', eBay: 'ebay_price' };

const TAB_COLORS = {
  Etsy: { active: 'bg-orange-500 text-white', dot: 'bg-orange-400' },
  Square: { active: 'bg-green-600 text-white', dot: 'bg-green-500' },
  eBay: { active: 'bg-blue-600 text-white', dot: 'bg-blue-500' },
};

function ProductCard({ product, marketplace, onAddUrl }) {
  const urlField = URL_FIELD[marketplace];
  const priceField = PRICE_FIELD[marketplace];
  const url = product[urlField];
  const price = product[priceField] || product.price;

  return (
    <div className="bg-white rounded-xl border border-gray-100 shadow-sm overflow-hidden flex flex-col">
      <div className="h-36 bg-gray-50 flex items-center justify-center overflow-hidden">
        {product.image_url ? (
          <img src={product.image_url} alt={product.title} className="w-full h-full object-cover" />
        ) : (
          <span className="text-4xl">📦</span>
        )}
      </div>
      <div className="p-3 flex flex-col gap-2 flex-1">
        <p className="text-sm font-semibold text-gray-900 leading-snug line-clamp-2">{product.title}</p>
        <p className="text-xs text-gray-500">{product.category || '—'}</p>
        <p className="text-sm font-bold text-gray-800">${(price || 0).toFixed(2)}</p>
        <div className="mt-auto">
          {url ? (
            <a
              href={url}
              target="_blank"
              rel="noreferrer"
              className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors"
            >
              <ExternalLink size={12} /> Open Listing
            </a>
          ) : (
            <button
              onClick={() => onAddUrl(product)}
              className="inline-flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded-lg text-white transition-opacity"
              style={{ background: '#f97316' }}
            >
              + Add URL
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

export default function Marketplaces() {
  const [products, setProducts] = useState([]);
  const [loading, setLoading] = useState(true);
  const [activeTab, setActiveTab] = useState('Etsy');
  const [addUrlTarget, setAddUrlTarget] = useState(null);
  const [syncing, setSyncing] = useState(false);

  const handleSyncEtsy = async () => {
    setSyncing(true);
    try {
      const res = await shire.functions.invoke('etsySyncListings', {});
      if (res.data?.success) {
        toast.success(`Synced ${res.data.total} listings — ${res.data.created} new, ${res.data.updated} updated.`);
        fetchProducts();
      } else {
        toast.error(res.data?.error || 'Etsy sync failed.');
      }
    } catch (err) {
      toast.error(err?.response?.data?.error || err.message || 'Etsy sync failed.');
    } finally {
      setSyncing(false);
    }
  };

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

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

  const urlField = URL_FIELD[activeTab];
  const listed = products.filter(p => p[urlField]);
  const notListed = products.filter(p => !p[urlField]);

  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-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-900">Marketplaces</h1>
        {activeTab === 'Etsy' && (
          <button
            onClick={handleSyncEtsy}
            disabled={syncing}
            className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-semibold border border-gray-200 text-gray-700 hover:bg-gray-50 transition-colors disabled:opacity-60"
          >
            <RefreshCw size={15} className={syncing ? 'animate-spin' : ''} />
            {syncing ? 'Syncing…' : 'Sync Etsy Listings'}
          </button>
        )}
      </div>

      {/* Tabs */}
      <div className="flex gap-2">
        {TABS.map(tab => (
          <button
            key={tab}
            onClick={() => setActiveTab(tab)}
            className={`px-5 py-2 rounded-full text-sm font-semibold transition-all
              ${activeTab === tab
                ? TAB_COLORS[tab].active
                : 'bg-white border border-gray-200 text-gray-600 hover:border-gray-300'
              }`}
          >
            {tab}
          </button>
        ))}
      </div>

      {/* Listed */}
      <div>
        <h2 className="font-semibold text-gray-900 mb-3">
          Listed on {activeTab}
          <span className="ml-2 text-sm font-normal text-gray-400">({listed.length})</span>
        </h2>
        {listed.length === 0 ? (
          <p className="text-gray-400 text-sm bg-white rounded-xl border border-gray-100 p-6">No products listed on {activeTab} yet.</p>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {listed.map(p => (
              <ProductCard key={p.id} product={p} marketplace={activeTab} onAddUrl={setAddUrlTarget} />
            ))}
          </div>
        )}
      </div>

      {/* Not listed */}
      <div>
        <h2 className="font-semibold text-gray-900 mb-3">
          Not Listed on {activeTab}
          <span className="ml-2 text-sm font-normal text-gray-400">({notListed.length})</span>
        </h2>
        {notListed.length === 0 ? (
          <p className="text-green-600 text-sm bg-green-50 rounded-xl border border-green-100 p-6">All products are listed on {activeTab}! 🎉</p>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4">
            {notListed.map(p => (
              <ProductCard key={p.id} product={p} marketplace={activeTab} onAddUrl={setAddUrlTarget} />
            ))}
          </div>
        )}
      </div>

      {addUrlTarget && (
        <AddUrlModal
          product={addUrlTarget}
          marketplace={activeTab}
          onClose={() => setAddUrlTarget(null)}
          onSaved={() => { setAddUrlTarget(null); fetchProducts(); }}
        />
      )}
    </div>
  );
}