import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { shire } from '@/api/shireClient';

export default function EtsyCallback() {
  const navigate = useNavigate();
  const [status, setStatus] = useState('loading');
  const [errorMsg, setErrorMsg] = useState('');

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code');
    const state = params.get('state');

    if (!code || !state) {
      setStatus('error');
      setErrorMsg('Missing authorization code or state parameter from Etsy.');
      return;
    }

    const redirectUri = window.location.origin + '/etsy/callback';

    shire.functions.invoke('etsyAuth', {
      action: 'exchange',
      code,
      state,
      redirect_uri: redirectUri,
    }).then(res => {
      if (res.data && res.data.success) {
        setStatus('success');
        setTimeout(() => navigate('/settings'), 2500);
      } else {
        setStatus('error');
        setErrorMsg((res.data && res.data.error) || 'Failed to connect Etsy account.');
      }
    }).catch(err => {
      setStatus('error');
      setErrorMsg((err && err.response && err.response.data && err.response.data.error) || (err && err.message) || 'Failed to connect Etsy account.');
    });
  }, [navigate]);

  return (
    <div className="min-h-screen flex items-center justify-center p-4" style={{ background: 'linear-gradient(135deg, #1a0a2e, #0d0d1a)' }}>
      <div className="bg-white rounded-2xl p-8 max-w-md w-full shadow-2xl text-center">
        {status === 'loading' && (
          <>
            <div className="w-12 h-12 border-4 border-orange-200 border-t-orange-500 rounded-full animate-spin mx-auto mb-4" />
            <h1 className="text-lg font-bold text-gray-900">Connecting Etsy…</h1>
            <p className="text-sm text-gray-500 mt-1">Exchanging authorization code</p>
          </>
        )}
        {status === 'success' && (
          <>
            <div className="text-5xl mb-3">✅</div>
            <h1 className="text-lg font-bold text-gray-900">Etsy Connected!</h1>
            <p className="text-sm text-gray-500 mt-1">Redirecting to settings…</p>
          </>
        )}
        {status === 'error' && (
          <>
            <div className="text-5xl mb-3">⚠️</div>
            <h1 className="text-lg font-bold text-gray-900">Connection Failed</h1>
            <p className="text-sm text-red-500 mt-2 break-words">{errorMsg}</p>
            <button onClick={() => navigate('/settings')}
              className="mt-4 px-4 py-2 rounded-lg text-white text-sm font-semibold" style={{ background: '#f97316' }}>
              Back to Settings
            </button>
          </>
        )}
      </div>
    </div>
  );
}