import { useState } from 'react';
import { Copy, Check, Save } from 'lucide-react';
import { shire } from '@/api/shireClient';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';

function CopyButton({ label, text }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = () => {
    navigator.clipboard.writeText(text || '');
    setCopied(true);
    toast.success(`${label} copied to clipboard!`);
    setTimeout(() => setCopied(false), 2000);
  };

  return (
    <button
      onClick={handleCopy}
      disabled={!text}
      className="flex items-center gap-1.5 px-3 py-2 rounded-lg text-xs font-semibold border transition-all disabled:opacity-40
        border-gray-200 text-gray-700 hover:bg-gray-50"
    >
      {copied ? <Check size={13} className="text-green-500" /> : <Copy size={13} />}
      {label}
    </button>
  );
}

export default function Step4Review({ data, onSaved }) {
  const [saving, setSaving] = useState(false);
  const navigate = useNavigate();

  const handleSave = async () => {
    setSaving(true);
    const payload = {
      title: data.title,
      category: data.category,
      price: Number(data.price) || 0,
      etsy_price: Number(data.etsy_price) || Number(data.price) || 0,
      square_price: Number(data.square_price) || Number(data.price) || 0,
      ebay_price: Number(data.ebay_price) || Number(data.price) || 0,
      image_url: data.image_url || (data.images?.[0] || ''),
      images: data.images || [],
      tagline: data.tagline || '',
      etsy_title: data.etsy_title || '',
      etsy_description: data.etsy_description || '',
      etsy_tags: data.etsy_tags || '',
      square_description: data.square_description || '',
      ebay_title: data.ebay_title || '',
      ebay_description: data.ebay_description || '',
      etsy_url: data.etsy_url || '',
      square_url: data.square_url || '',
      ebay_url: data.ebay_url || '',
      notes: data.notes || '',
    };
    await shire.entities.Product.create(payload);
    setSaving(false);
    toast.success('Product saved!');
    navigate('/products');
  };

  const etsyListing = `${data.etsy_title || ''}\n\n${data.etsy_description || ''}\n\nTags: ${data.etsy_tags || ''}`;
  const ebayListing = `${data.ebay_title || ''}\n\n${data.ebay_description || ''}`;

  const fmt = (n) => n ? `$${Number(n).toFixed(2)}` : '—';

  return (
    <div className="space-y-5">
      {/* Product card */}
      <div className="bg-white rounded-2xl border border-gray-100 shadow-md overflow-hidden">
        {data.image_url && (
          <img src={data.image_url} alt={data.title} className="w-full h-48 object-cover" />
        )}
        <div className="p-5 space-y-2">
          <p className="text-xs font-medium text-orange-500 uppercase tracking-wider">{data.category}</p>
          <h2 className="text-lg font-bold text-gray-900">{data.title || 'Untitled Product'}</h2>
          {data.tagline && <p className="text-sm text-gray-500 italic">"{data.tagline}"</p>}

          <div className="grid grid-cols-3 gap-3 pt-3">
            {[
              { label: '🛍 Etsy', val: fmt(data.etsy_price) },
              { label: '🟩 Square', val: fmt(data.square_price) },
              { label: '🔵 eBay', val: fmt(data.ebay_price) },
            ].map(({ label, val }) => (
              <div key={label} className="text-center bg-gray-50 rounded-lg py-2">
                <p className="text-xs text-gray-500">{label}</p>
                <p className="font-bold text-gray-800 text-sm">{val}</p>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Copy buttons */}
      <div className="space-y-2">
        <p className="text-xs font-semibold text-gray-600 uppercase tracking-wide">Copy Listing Content</p>
        <div className="flex flex-wrap gap-2">
          <CopyButton label="Copy Etsy Listing" text={etsyListing} />
          <CopyButton label="Copy Square Description" text={data.square_description} />
          <CopyButton label="Copy eBay Listing" text={ebayListing} />
        </div>
      </div>

      {/* Content preview */}
      {data.etsy_title && (
        <div className="bg-gray-50 rounded-xl p-4 space-y-2">
          <p className="text-xs font-semibold text-gray-500 uppercase">Etsy Title Preview</p>
          <p className="text-sm text-gray-800">{data.etsy_title}</p>
        </div>
      )}

      {/* Save */}
      <button
        onClick={handleSave}
        disabled={saving || !data.title}
        className="w-full py-3.5 rounded-xl text-white font-bold text-sm flex items-center justify-center gap-2 transition-all disabled:opacity-50"
        style={{ background: '#f97316' }}
      >
        {saving ? (
          <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Saving…</>
        ) : (
          <><Save size={16} /> Save Product</>
        )}
      </button>
    </div>
  );
}