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

export default function EtsyConnectButton() {
  const [connected, setConnected] = useState(false);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);

  const checkStatus = async () => {
    try {
      const res = await shire.functions.invoke('etsyAuth', { action: 'status' });
      setConnected((res.data && res.data.connected) || false);
    } catch {
      setConnected(false);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { checkStatus(); }, []);

  const handleConnect = async () => {
    setActionLoading(true);
    try {
      const redirectUri = window.location.origin + '/etsy/callback';
      const res = await shire.functions.invoke('etsyAuth', { action: 'get_auth_url', redirect_uri: redirectUri });
      if (res.data && res.data.auth_url) {
        window.location.href = res.data.auth_url;
      } else {
        toast.error('Failed to get Etsy authorization URL.');
      }
    } catch (err) {
      toast.error((err && err.response && err.response.data && err.response.data.error) || (err && err.message) || 'Failed to connect Etsy.');
    } finally {
      setActionLoading(false);
    }
  };

  const handleDisconnect = async () => {
    if (!window.confirm('Disconnect Etsy from SHIRE 3D Manager? This removes the local encrypted token.')) return;
    setActionLoading(true);
    try {
      await shire.functions.invoke('etsyAuth', { action: 'disconnect', approved: true });
      setConnected(false);
      toast.success('Etsy account disconnected.');
    } catch (err) {
      toast.error((err && err.response && err.response.data && err.response.data.error) || (err && err.message) || 'Failed to disconnect.');
    } finally {
      setActionLoading(false);
    }
  };

  if (loading) {
    return <div className="w-6 h-6 border-2 border-gray-200 border-t-gray-400 rounded-full animate-spin" />;
  }

  if (connected) {
    return (
      <div className="flex items-center gap-3">
        <span className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-semibold bg-green-50 text-green-700 border border-green-200">
          <span className="w-2 h-2 rounded-full bg-green-500" /> Etsy Connected
        </span>
        <button onClick={handleDisconnect} disabled={actionLoading}
          className="px-3 py-1.5 rounded-lg text-xs font-semibold text-red-600 border border-red-200 hover:bg-red-50 transition-colors disabled:opacity-50">
          {actionLoading ? 'Disconnecting…' : 'Disconnect'}
        </button>
      </div>
    );
  }

  return (
    <button onClick={handleConnect} disabled={actionLoading}
      className="inline-flex items-center gap-2 px-4 py-2 rounded-lg text-white text-sm font-semibold transition-all hover:opacity-90 disabled:opacity-60"
      style={{ background: '#f97316' }}>
      {actionLoading ? (
        <><div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> Redirecting…</>
      ) : (
        <>🔗 Connect Etsy Account</>
      )}
    </button>
  );
}
