/**
 * Connections tab — list account connections (X, LinkedIn, GitHub, Newsletter).
 * Migrated from src/connections/ConnectionsPanel.tsx (titlebar dropdown).
 *
 * NewsletterSetupModal + ConnectionConfigModal remain modals (they overlay
 * the whole app, not the rail). Only the panel chrome moves.
 *
 * adr: adr/right-rail.md
 */
import { useEffect, useRef, useState } from 'react';
import type { JSX } from 'react';
import NewsletterSetupModal from '../../connections/NewsletterSetupModal';
import ConnectionConfigModal from '../../connections/ConnectionConfigModal';
import type { RightRailTabProps } from '../types';

interface Connection {
  id: string;
  provider: string;
  display_name?: string;
  status: string;
  domain?: string;
  from_name?: string;
  created_at: string;
}

const ALL_PROVIDERS = [
  { id: 'x', label: 'X (Twitter)', oauth: true },
  { id: 'linkedin', label: 'LinkedIn', oauth: true },
  { id: 'newsletter', label: 'Newsletter', oauth: false },
] as const;

function providerIcon(provider: string): JSX.Element {
  switch (provider) {
    case 'x': return (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
      </svg>
    );
    case 'linkedin': return (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
        <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z"/>
      </svg>
    );
    case 'newsletter': return (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <rect x="2" y="4" width="20" height="16" rx="2" />
        <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
      </svg>
    );
    default: return (
      <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <circle cx="12" cy="12" r="10" />
      </svg>
    );
  }
}

function statusDot(status: string): string {
  if (status === 'active') return 'connections-status--active';
  if (status === 'expired') return 'connections-status--expired';
  if (status === 'revoked') return 'connections-status--revoked';
  return 'connections-status--pending';
}

export default function ConnectionsTab(_props: RightRailTabProps) {
  const [connections, setConnections] = useState<Connection[]>([]);
  const [authenticated, setAuthenticated] = useState<boolean | null>(null);
  const [confirmDelete, setConfirmDelete] = useState<string | null>(null);
  const [connecting, setConnecting] = useState<string | null>(null);
  const [showSetup, setShowSetup] = useState<'new' | 'edit' | null>(null);
  const [configConnection, setConfigConnection] = useState<{ id: string; provider: string; display_name: string } | null>(null);
  const pollRef = useRef<ReturnType<typeof setInterval> | null>(null);

  async function fetchConnections(): Promise<Connection[]> {
    try {
      const r = await fetch('/api/connections');
      const data = await r.json();
      setAuthenticated(data.authenticated !== false);
      const conns = (data.connections || []).filter((c: any) => c && c.id && c.provider);
      setConnections(conns);
      return conns;
    } catch {
      return [];
    }
  }

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

  useEffect(() => () => { if (pollRef.current) clearInterval(pollRef.current); }, []);

  async function startOAuth(provider: string) {
    setConnecting(provider);
    try {
      const res = await fetch(`/api/connections/oauth/${provider}/start`, { method: 'POST' });
      const data = await res.json();
      if (!res.ok || !data.url) {
        setConnecting(null);
        return;
      }
      window.open(data.url, '_blank', 'width=600,height=700');
      pollRef.current = setInterval(async () => {
        try {
          const statusRes = await fetch(`/api/connections/oauth/${provider}/status/${data.state}`);
          const statusData = await statusRes.json();
          if (statusData.status === 'completed') {
            if (pollRef.current) clearInterval(pollRef.current);
            pollRef.current = null;
            setConnecting(null);
            const conns = await fetchConnections();
            if (provider === 'x') {
              const xConn = conns.find((c) => c.provider === 'x' && c.status === 'active');
              if (xConn?.display_name) {
                const handle = xConn.display_name.replace('@', '');
                localStorage.setItem('ow-x-handle', handle);
                window.dispatchEvent(new StorageEvent('storage', { key: 'ow-x-handle', newValue: handle }));
              }
            }
          } else if (statusData.status === 'failed') {
            if (pollRef.current) clearInterval(pollRef.current);
            pollRef.current = null;
            setConnecting(null);
          }
        } catch { /* keep polling */ }
      }, 2000);
    } catch {
      setConnecting(null);
    }
  }

  async function handleDelete(id: string) {
    try {
      const res = await fetch(`/api/connections/${id}`, { method: 'DELETE' });
      if (!res.ok) {
        const data = await res.json().catch(() => ({ error: 'Delete failed' }));
        console.error('[Connections] Delete failed:', data.error);
      }
    } catch (err) {
      console.error('[Connections] Delete error:', err);
    }
    setConfirmDelete(null);
    await fetchConnections();
  }

  const connectionsByProvider = new Map<string, Connection>();
  const allConnectionsByProvider = new Map<string, Connection[]>();
  for (const conn of connections) {
    if (!connectionsByProvider.has(conn.provider)) {
      connectionsByProvider.set(conn.provider, conn);
    }
    const list = allConnectionsByProvider.get(conn.provider) || [];
    list.push(conn);
    allConnectionsByProvider.set(conn.provider, list);
  }

  // Providers that support multiple connections per account (one row per connection + an "add another" button)
  const MULTI_PROVIDERS = new Set<string>();

  const isDisabled = authenticated === false;

  return (
    <div className="connections-tab">
      {configConnection && (
        <ConnectionConfigModal
          connectionId={configConnection.id}
          provider={configConnection.provider}
          displayName={configConnection.display_name}
          onClose={() => setConfigConnection(null)}
          onSaved={() => fetchConnections()}
        />
      )}
      {showSetup && (
        <NewsletterSetupModal
          existingConnection={showSetup === 'edit' ? connectionsByProvider.get('newsletter') : null}
          onClose={() => setShowSetup(null)}
          onSaved={() => fetchConnections()}
        />
      )}
      {isDisabled ? (
        <div className="connections-dropdown__upsell">
          <p>Connect your X, LinkedIn, and other accounts to publish directly from OpenWriter.</p>
          <p>Set up the <strong>Publish</strong> plugin to get started.</p>
        </div>
      ) : (
        <div className="connections-dropdown__list">
          {ALL_PROVIDERS.flatMap((p) => {
            const isMulti = MULTI_PROVIDERS.has(p.id);
            const conns = allConnectionsByProvider.get(p.id) || [];

            const renderConnected = (conn: Connection) => {
              if (confirmDelete === conn.id) {
                return (
                  <div key={conn.id} className="connections-dropdown__confirm">
                    <span>Disconnect {conn.display_name || p.label}?</span>
                    <div className="connections-dropdown__confirm-btns">
                      <button onClick={() => handleDelete(conn.id)}>Yes</button>
                      <button onClick={() => setConfirmDelete(null)}>No</button>
                    </div>
                  </div>
                );
              }
              return (
                <div key={conn.id} className="connections-dropdown__item">
                  <div className="connections-dropdown__icon">{providerIcon(p.id)}</div>
                  <div className="connections-dropdown__info">
                    <div className="connections-dropdown__name">
                      {conn.display_name || conn.domain || p.label}
                    </div>
                    <div className="connections-dropdown__type">
                      <span className={`connections-status ${statusDot(conn.status)}`} />
                      Connected
                    </div>
                  </div>
                  <div className="connections-dropdown__actions">
                    <button
                      className="connections-dropdown__action-btn"
                      onClick={() => {
                        if (p.id === 'newsletter') {
                          setShowSetup('edit');
                        } else {
                          setConfigConnection({ id: conn.id, provider: p.id, display_name: conn.display_name || p.label });
                        }
                      }}
                      title="Settings"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                        <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>
                        <circle cx="12" cy="12" r="3"/>
                      </svg>
                    </button>
                    <button
                      className="connections-dropdown__action-btn connections-dropdown__action-btn--delete"
                      onClick={() => setConfirmDelete(conn.id)}
                      title="Disconnect"
                    >
                      &times;
                    </button>
                  </div>
                </div>
              );
            };

            const rows: JSX.Element[] = conns.map(renderConnected);

            if (isMulti) {
              // GitHub & co. — render every connection plus a dashed "+ Add" button
              rows.push(
                <div key={`${p.id}__add`} className="connections-dropdown__add-row">
                  <button
                    className="connections-dropdown__add-btn"
                    onClick={() => startOAuth(p.id)}
                    disabled={connecting !== null}
                  >
                    {connecting === p.id ? 'Connecting…' : `+ Add ${p.label} repo`}
                  </button>
                </div>
              );
              return rows;
            }

            if (conns.length > 0) return rows;

            if (p.oauth) {
              return [(
                <div key={p.id} className="connections-dropdown__item connections-dropdown__item--disconnected">
                  <div className="connections-dropdown__icon">{providerIcon(p.id)}</div>
                  <div className="connections-dropdown__info">
                    <div className="connections-dropdown__name">{p.label}</div>
                    <div className="connections-dropdown__type">Not connected</div>
                  </div>
                  <button
                    className="connections-dropdown__connect-inline-btn"
                    onClick={() => startOAuth(p.id)}
                    disabled={connecting !== null}
                  >
                    {connecting === p.id ? 'Connecting…' : 'Connect'}
                  </button>
                </div>
              )];
            }

            return [(
              <div key={p.id} className="connections-dropdown__item connections-dropdown__item--disconnected">
                <div className="connections-dropdown__icon">{providerIcon(p.id)}</div>
                <div className="connections-dropdown__info">
                  <div className="connections-dropdown__name">{p.label}</div>
                  <div className="connections-dropdown__type">Built-in · Not configured</div>
                </div>
                <button
                  className="connections-dropdown__connect-inline-btn"
                  onClick={() => setShowSetup('new')}
                >
                  Configure
                </button>
              </div>
            )];
          })}
        </div>
      )}
    </div>
  );
}
