'use client';

import { useEffect, useState } from 'react';
import KindBadge from '@/app/components/ui/marketplace/kind-badge.jsx';
import ConnectionSetupModal from './connection-setup-modal.jsx';
import ConnectionScopeBadge from './connection-scope-badge.jsx';

/**
 * Status pill for a connection card. Mirrors the existing admin-pill styles
 * but with status-specific tones so the card surfaces ready/warn/danger
 * without a separate component.
 */
function ConnectionStatusPill({ status }) {
  if (!status) return null;
  return <span className={`connection-status ${status.status}`}>{status.label}</span>;
}

/**
 * Body of a connection-kind marketplace card. Replaces the install toggle
 * with a Configure / Manage button and a chip-list of scoped installs.
 *
 * @param {{
 *   item: any,
 *   status: { status: string, label: string, footer: string|null },
 *   prefillScope?: { scope, project_id, agent_id }|null,
 * }} props
 */
export default function ConnectionCard({ item, status, prefillScope = null }) {
  const [open, setOpen] = useState(false);
  const [activePrefill, setActivePrefill] = useState(prefillScope);
  const [labelMap, setLabelMap] = useState({ projects: {}, agents: {} });

  const connection = item.connection || item.manifest || {};
  const unlocks = Array.isArray(connection.unlocks_tool_slugs) ? connection.unlocks_tool_slugs : [];
  const engines = Array.isArray(connection.engines) ? connection.engines : [];
  const installs = Array.isArray(item.installs) ? item.installs : [];
  const isConnected = status?.status === 'connected' || installs.length > 0;

  // Open on mount if a deep-link prefill was provided.
  useEffect(() => {
    if (prefillScope?.scope) {
      setActivePrefill(prefillScope);
      setOpen(true);
    }
  }, [prefillScope?.scope, prefillScope?.project_id, prefillScope?.agent_id]);

  // Fetch label maps for scope badges (project name / agent name).
  useEffect(() => {
    if (installs.length === 0) return;
    const needsProjects = installs.some(i => i.scope === 'project' && i.project_id);
    const needsAgents = installs.some(i => i.scope === 'agent' && i.agent_id);
    if (!needsProjects && !needsAgents) return;
    let cancelled = false;
    async function load() {
      try {
        const promises = [];
        promises.push(needsProjects ? fetch('/api/projects').then(r => r.json()) : Promise.resolve({ projects: [] }));
        promises.push(needsAgents ? fetch('/api/state').then(r => r.json()) : Promise.resolve({ agents: [] }));
        const [projRes, stateRes] = await Promise.all(promises);
        if (cancelled) return;
        const projects = {};
        for (const p of (projRes?.projects || [])) projects[p.id] = p.name;
        const agents = {};
        for (const a of (stateRes?.agents || [])) agents[a.id] = a.name || a.id;
        setLabelMap({ projects, agents });
      } catch {
        // best-effort — badges fall back to ids
      }
    }
    load();
    return () => { cancelled = true; };
  }, [installs.length]);

  function openWithScope(prefill = null) {
    setActivePrefill(prefill);
    setOpen(true);
  }

  return (
    <li className={`mkt-card kind-connection ${isConnected ? 'on' : ''}`}>
      <div className="mkt-card-head">
        <span className="mkt-chip-tile kind-connection" aria-hidden="true">
          <ConnectionGlyph glyph={connection.logo_glyph || item.slug} />
        </span>
        <KindBadge kind="connection" />
        <ConnectionStatusPill status={status} />
      </div>

      <div className="mkt-card-body">
        <h3 className="mkt-card-title">{item.title}</h3>
        <p className="mkt-card-desc">{item.description}</p>
      </div>

      <div className="mkt-card-meta">
        {engines.length ? (
          <span>Engine <b>{engines.join(' · ')}</b></span>
        ) : null}
        {unlocks.length ? (
          <span>Unlocks <b>{unlocks.length} tool{unlocks.length === 1 ? '' : 's'}</b></span>
        ) : null}
        {connection.setup_kind ? (
          <span>Setup <b>{labelForSetupKind(connection.setup_kind)}</b></span>
        ) : null}
        {item.risk_summary ? (
          <span>Risk <b>{item.risk_summary.length > 40 ? item.risk_summary.slice(0, 40) + '…' : item.risk_summary}</b></span>
        ) : null}
      </div>

      {installs.length > 0 ? (
        <ul className="connection-card-installs">
          {installs.map(install => (
            <li key={`${install.scope}:${install.project_id || ''}:${install.agent_id || ''}`}>
              <ConnectionScopeBadge
                install={install}
                projectName={install.project_id ? labelMap.projects[install.project_id] : null}
                agentName={install.agent_id ? labelMap.agents[install.agent_id] : null}
              />
            </li>
          ))}
          <li>
            <button
              type="button"
              className="connection-card-add"
              onClick={() => openWithScope({ scope: 'global', project_id: null, agent_id: null })}
            >
              + Add another
            </button>
          </li>
        </ul>
      ) : null}

      <div className="mkt-card-foot">
        <span className="mkt-availability">
          {status?.footer || (isConnected ? 'Ready to use' : 'Not configured yet')}
        </span>
        <button
          type="button"
          className={`admin-button${isConnected ? ' secondary' : ''}`}
          onClick={() => openWithScope(null)}
        >
          {isConnected ? 'Manage' : 'Configure'}
        </button>
      </div>
      <ConnectionSetupModal
        open={open}
        onClose={() => { setOpen(false); setActivePrefill(null); }}
        connection={item}
        prefillScope={activePrefill}
      />
    </li>
  );
}

function labelForSetupKind(kind) {
  if (kind === 'qr_pair') return 'QR pairing';
  if (kind === 'binary_detect') return 'Local binary';
  return 'API key';
}

function ConnectionGlyph({ glyph }) {
  const letter = String(glyph || '?').slice(0, 1).toUpperCase();
  return (
    <svg viewBox="0 0 20 20" width="20" height="20" aria-hidden="true">
      <rect x="0" y="0" width="20" height="20" rx="5" fill="currentColor" opacity="0.08" />
      <text
        x="10"
        y="14"
        textAnchor="middle"
        fontSize="11"
        fontWeight="600"
        fontFamily="'IBM Plex Mono', monospace"
        fill="currentColor"
      >
        {letter}
      </text>
    </svg>
  );
}
