'use client';

import Link from 'next/link';
import { useEffect, useState } from 'react';
import type { Connection } from '@/features/integrations/api.client';
import { needsReconnect, type ConnectionState } from '@/lib/utils/connection';
import { getMyCalendar, getMyMailbox } from '../../api.client';
import { DialogHead, SetDialog } from '../settings-ui';
import { CONNECTORS, connectorSoon, type Connector } from './connections';
import { Icon, connectionLogo } from './icons';

type Mine = Partial<Record<'gmail' | 'google_calendar', ConnectionState | null>>;

/** Connected (for me, or for the account), needs reconnecting, or not connected yet. */
type ConnectorState = 'connected' | 'reconnect' | 'none';

function stateOf(c: Connector, rows: Connection[], mine: Mine): ConnectorState {
  if (c.key === 'gmail' || c.key === 'google_calendar') {
    // Each person connects their own: what matters is the current user's connection.
    const own = mine[c.key];
    if (!own?.connected) return 'none';
    return needsReconnect(own) ? 'reconnect' : 'connected';
  }
  // Slack and Google Sheets are installed once for the account.
  const row = rows.find((r) => r.appKey === c.key);
  if (!row || row.status === 'disconnected') return 'none';
  return row.status === 'needs_attention' ? 'reconnect' : 'connected';
}

/**
 * "Add more connections": our own connectors only (no marketplace). Each one links to where the
 * CRM connects it; one without a screen yet shows a disabled "Coming soon". One that is already
 * connected (the user's own Gmail / Google Calendar, the account's Slack / Google Sheets) shows
 * "Connected" instead of Connect (QA #427).
 */
export function AddConnectionsDialog({
  open,
  onClose,
  rows = [],
}: {
  open: boolean;
  onClose: () => void;
  /** The business's connections (Connected Apps list), for the account-level connectors. */
  rows?: Connection[];
}) {
  const [mine, setMine] = useState<Mine>({});

  // Read the user's own Gmail and Calendar each time the dialog opens (they may have just
  // connected one in another tab).
  useEffect(() => {
    if (!open) return;
    let live = true;
    getMyMailbox().then(
      (m) => live && setMine((cur) => ({ ...cur, gmail: m })),
      () => {},
    );
    getMyCalendar().then(
      (c) => live && setMine((cur) => ({ ...cur, google_calendar: c })),
      () => {},
    );
    return () => {
      live = false;
    };
  }, [open]);

  return (
    <SetDialog open={open} onClose={onClose} labelledBy="ca-add-title" id="ca-add-dialog">
      <DialogHead id="ca-add-title" title="Add more connections" onClose={onClose} />
      <div className="set-modal__body">
        <p className="crm-text-muted crm-fs-7 crm-mb-3">
          Connect the CRM to the apps your team uses.
        </p>
        <div className="ca-expired-list">
          {CONNECTORS.map((c) => {
            const logo = connectionLogo({ appKey: c.key, type: 'native' });
            const state = stateOf(c, rows, mine);
            return (
              <div key={c.key} className="ca-expired-row" data-connector={c.key} data-state={state}>
                <span className="su-app-row-logo" style={{ background: logo.bg, color: '#ffffff' }}>
                  <Icon name={logo.icon} size={16} />
                </span>
                <div className="ca-expired-copy">
                  <p>
                    <strong>{c.name}</strong>
                  </p>
                  <span className="crm-mb-0">{c.description}</span>
                </div>
                {state === 'connected' ? (
                  <span className="badge badge--success">
                    <span className="badge__dot" aria-hidden="true" />
                    Connected
                  </span>
                ) : state === 'reconnect' && c.href ? (
                  <Link className="btn-crm btn-crm--outline btn-crm--sm" href={c.href}>
                    Reconnect
                  </Link>
                ) : c.href ? (
                  <Link className="btn-crm btn-crm--primary btn-crm--sm" href={c.href}>
                    Connect
                  </Link>
                ) : (
                  <button
                    type="button"
                    className="btn-crm btn-crm--outline btn-crm--sm"
                    disabled
                    title={connectorSoon(c.name)}
                  >
                    Coming soon
                  </button>
                )}
              </div>
            );
          })}
        </div>
      </div>
      <div className="set-modal__foot">
        <button type="button" className="btn-crm btn-crm--outline" onClick={onClose}>
          Close
        </button>
      </div>
    </SetDialog>
  );
}
