import { useState } from 'react';
import { shire } from '@/api/shireClient';
import { toast } from 'sonner';

export default function PushToEtsyButton({ productId, hasEtsyUrl, onPushed }) {
  const [loading, setLoading] = useState(false);

  const handlePush = async () => {
    if (hasEtsyUrl) {
      toast.error('This product already has an Etsy listing.');
      return;
    }
    const taxonomyId = window.prompt('Enter the confirmed Etsy taxonomy/category ID for this product:');
    if (!taxonomyId) return;
    if (!window.confirm('APPROVAL REQUIRED: Create this product as a private Etsy DRAFT? It will not be published.')) return;
    setLoading(true);
    try {
      const res = await shire.functions.invoke('etsyPushListing', {
        product_id: productId,
        taxonomy_id: Number(taxonomyId),
        approved: true,
      });
      if (res.data && res.data.success) {
        toast.success(`✅ Draft listing created on Etsy!`);
        if (onPushed) onPushed(res.data.listing_url);
      } else {
        toast.error((res.data && res.data.error) || 'Failed to push listing to Etsy.');
      }
    } catch (err) {
      toast.error((err && err.response && err.response.data && err.response.data.error) || (err && err.message) || 'Failed to push listing to Etsy.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <button onClick={handlePush} disabled={loading || hasEtsyUrl}
      className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-white transition-all disabled:opacity-50 disabled:cursor-not-allowed"
      style={{ background: hasEtsyUrl ? '#9ca3af' : '#f97316' }}>
      {loading ? (
        <><div className="w-3.5 h-3.5 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Pushing…</>
      ) : hasEtsyUrl ? (
        '✅ On Etsy'
      ) : (
        '📤 Push to Etsy'
      )}
    </button>
  );
}
