import { useState } from 'react';
import { shire } from '@/api/shireClient';
import EtsyConnectButton from '@/components/etsy/EtsyConnectButton';

export default function Settings() {
  const [ebayUrls, setEbayUrls] = useState('');
  const [importing, setImporting] = useState(false);
  const [importResult, setImportResult] = useState(null);

  const handleEbayImport = async () => {
    setImporting(true);
    setImportResult(null);

    const lines = ebayUrls.split('\n').map(l => l.trim()).filter(l => l.length > 0 && l.startsWith('http'));

    if (lines.length === 0) {
      setImportResult({ matched: 0, unmatched: 0, errors: ['No valid URLs found.'] });
      setImporting(false);
      return;
    }

    // Fetch all products
    const products = await shire.entities.Product.list('-created_date', 500);

    // For each URL try to match by title similarity in the URL slug
    let matched = 0;
    let unmatched = 0;

    await Promise.all(
      lines.map(async url => {
        // Extract keywords from the URL
        const urlLower = url.toLowerCase();
        let bestProduct = null;
        let bestScore = 0;

        for (const p of products) {
          if (p.ebay_url) continue; // Already has a URL
          const words = (p.title || '').toLowerCase().split(/\s+/).filter(w => w.length > 2);
          const score = words.filter(w => urlLower.includes(w)).length;
          if (score > bestScore) {
            bestScore = score;
            bestProduct = p;
          }
        }

        if (bestProduct && bestScore >= 2) {
          await shire.entities.Product.update(bestProduct.id, { ebay_url: url });
          matched++;
        } else {
          unmatched++;
        }
      })
    );

    setImportResult({ matched, unmatched, total: lines.length });
    setImporting(false);
    if (matched > 0) setEbayUrls('');
  };

  return (
    <div className="p-6 md:p-8 max-w-2xl mx-auto space-y-8">
      <h1 className="text-2xl font-bold text-gray-900">Settings</h1>

      {/* Etsy Integration */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-gray-900">Etsy Integration</h2>
          <p className="text-sm text-gray-500 mt-1">
            Connect your Etsy shop to sync orders, pull live listings, and push new products as draft listings. 
            You'll need to register this app's callback URL in your <a href="https://www.etsy.com/developers/register" target="_blank" rel="noreferrer" className="text-orange-600 underline">Etsy developer app</a>:
          </p>
          <code className="block mt-2 bg-gray-100 px-3 py-2 rounded-lg text-xs text-gray-700 break-all">
            {typeof window !== 'undefined' ? window.location.origin + '/etsy/callback' : 'https://your-app-url/etsy/callback'}
          </code>
        </div>
        <div className="pt-1">
          <EtsyConnectButton />
        </div>
      </div>

      {/* Bulk eBay URL Import */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-4">
        <div>
          <h2 className="font-semibold text-gray-900">Bulk eBay URL Import</h2>
          <p className="text-sm text-gray-500 mt-1">
            Paste eBay listing URLs (one per line). The importer will try to match each URL to an existing product by title similarity and save the <code className="bg-gray-100 px-1 rounded text-xs">ebay_url</code>.
          </p>
        </div>

        <textarea
          value={ebayUrls}
          onChange={e => setEbayUrls(e.target.value)}
          rows={8}
          placeholder={"https://www.ebay.com.au/itm/...\nhttps://www.ebay.com.au/itm/...\nhttps://www.ebay.com.au/itm/..."}
          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 resize-none font-mono"
        />

        <button
          onClick={handleEbayImport}
          disabled={importing || !ebayUrls.trim()}
          className="px-5 py-2.5 rounded-lg text-white text-sm font-semibold transition-opacity disabled:opacity-60"
          style={{ background: '#f97316' }}
        >
          {importing ? 'Matching & Importing…' : 'Match & Import'}
        </button>

        {importResult && (
          <div className={`rounded-lg border p-4 text-sm ${importResult.matched > 0 ? 'bg-green-50 border-green-200 text-green-800' : 'bg-amber-50 border-amber-200 text-amber-800'}`}>
            {importResult.errors ? (
              <p>{importResult.errors.join(', ')}</p>
            ) : (
              <>
                <p><strong>{importResult.matched}</strong> URL{importResult.matched !== 1 ? 's' : ''} matched and saved.</p>
                {importResult.unmatched > 0 && (
                  <p className="mt-1 text-amber-700"><strong>{importResult.unmatched}</strong> URL{importResult.unmatched !== 1 ? 's' : ''} could not be matched (no title similarity found, or product already has an eBay URL).</p>
                )}
              </>
            )}
          </div>
        )}
      </div>

      {/* About */}
      <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-6 space-y-2">
        <h2 className="font-semibold text-gray-900">About</h2>
        <div className="text-sm text-gray-600 space-y-1">
          <p><span className="text-gray-400 w-28 inline-block">App</span> Shire 3D Manager</p>
          <p><span className="text-gray-400 w-28 inline-block">Version</span> 1.0.0</p>
          <p><span className="text-gray-400 w-28 inline-block">Owner</span> 3drays85@gmail.com</p>
          <p><span className="text-gray-400 w-28 inline-block">Marketplaces</span> Etsy · Square · eBay</p>
        </div>
      </div>
    </div>
  );
}