// app/(defaults)/ebay-settings/EbaySettingsClient.tsx
'use client';

import { useEffect, useMemo, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';

const OAUTH_ENDPOINT = 'https://ebay.backend.data4autos.com/api/ebay/oauth/login';

/**
 * This expects your backend to redirect back to this page with ?status=success
 * (or ?connected=1). If your backend uses a different param, adjust below.
 */
export default function EbaySettingsClient() {
  const router = useRouter();
  const searchParams = useSearchParams();

  const [connecting, setConnecting] = useState(false);
  const [connected, setConnected] = useState(false);
  const [toast, setToast] = useState<string>('');

  // Compute a clean return URL for after OAuth
  const returnUrl = useMemo(() => {
    if (typeof window === 'undefined') return '';
    // Send user back here after OAuth
    return `${window.location.origin}/ebay-settings?status=success`;
  }, []);

  // On load, detect success flags from query params
  useEffect(() => {
    const status = searchParams.get('status');
    const connectedFlag = searchParams.get('connected');

    if (status === 'success' || connectedFlag === '1') {
      setConnected(true);
      setToast('Connection successful');
      // Remove query params from the URL after showing success
      router.replace('/ebay-settings');
    }
  }, [router, searchParams]);

  const startOauth = () => {
    try {
      setConnecting(true);
      // If your backend supports a return/redirect param, include it:
      const url = `${OAUTH_ENDPOINT}?return_url=${encodeURIComponent(returnUrl)}`;
      // Open in the same window
      window.location.href = url;
    } catch (e) {
      setConnecting(false);
      setToast('Failed to start eBay connection. Please try again.');
    }
  };

  return (
    <div className="max-w-2xl mx-auto p-6">
      {/* Toast / popup */}
      {toast && (
        <div className="mb-4 rounded-md border border-green-300 bg-green-50 px-4 py-3 text-sm text-green-800">
          {toast}
        </div>
      )}

      <h1 className="text-2xl font-bold mb-4">eBay Settings</h1>
      <p className="text-gray-600 mb-6">
        Connect your eBay store to enable product sync, inventory updates, and order flow.
      </p>

      <button
        onClick={startOauth}
        disabled={connecting || connected}
        className={[
          'w-full py-2 px-4 font-semibold rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2',
          connected
            ? 'bg-green-600 text-white hover:bg-green-700 focus:ring-green-500'
            : 'bg-blue-600 text-white hover:bg-blue-700 focus:ring-blue-500',
          connecting ? 'opacity-70 cursor-not-allowed' : ''
        ].join(' ')}
      >
        {connected
          ? 'Connected to eBay'
          : connecting
          ? 'Redirecting to eBay…'
          : 'Connect your eBay store'}
      </button>

      <p className="mt-3 text-xs text-gray-500">
        You’ll be redirected to eBay to authorize access, then returned here automatically.
      </p>
    </div>
  );
}
