'use client';

import * as React from 'react';
import { useRouter } from 'next/navigation';
import AdminModal from '@/app/components/admin/admin-modal.jsx';
import ApiKeyStep from './connection-setup-steps/api-key-step.jsx';
import QrPairStep from './connection-setup-steps/qr-pair-step.jsx';
import BinaryDetectStep from './connection-setup-steps/binary-detect-step.jsx';

const STAGES = {
  BENEFIT: 'benefit',
  SETUP: 'setup',
  VERIFYING: 'verifying',
  DONE: 'done',
};

function setupKindFor(connection) {
  return connection?.connection?.setup_kind || connection?.manifest?.setup_kind || 'api_key';
}

function StatusPill({ status }) {
  if (!status) return null;
  return <span className={`connection-status ${status.status}`}>{status.label}</span>;
}

function labelForWarningField(field) {
  if (field === 'SUPABASE_ACCESS_TOKEN') return 'Personal access token';
  return field || 'Optional field';
}
function labelForWarningReason(reason) {
  if (reason === 'unauthorized') return 'rejected by the provider';
  if (reason === 'invalid_key') return 'invalid';
  if (reason === 'network') return 'network error';
  return reason || 'unknown';
}

export default function ConnectionSetupModal({ open, onClose, connection, prefillScope }) {
  const router = useRouter();
  const [stage, setStage] = React.useState(STAGES.BENEFIT);
  const [credentials, setCredentials] = React.useState({});
  const [scope, setScope] = React.useState({ scope: 'global', project_id: null, agent_id: null });
  const [error, setError] = React.useState(null);
  const [hint, setHint] = React.useState(null);
  const [summary, setSummary] = React.useState(null);
  const [warning, setWarning] = React.useState(null);
  const [busy, setBusy] = React.useState(false);

  // Reset state when the modal opens fresh or switches connection.
  React.useEffect(() => {
    if (!open) return;
    setStage(connection?.installed ? STAGES.DONE : STAGES.BENEFIT);
    setCredentials({});
    // Honor prefill from a deep-link (e.g. "Add connection for this agent" from /agents/:id).
    if (prefillScope?.scope) {
      setScope({
        scope: prefillScope.scope,
        project_id: prefillScope.project_id || null,
        agent_id: prefillScope.agent_id || null,
      });
    } else {
      setScope({ scope: 'global', project_id: null, agent_id: null });
    }
    setError(null);
    setHint(null);
    setWarning(null);
    setSummary(connection?.installed ? {
      account_label: connection.connection?.account_label,
      last_4: connection.connection?.last_4,
    } : null);
    setBusy(false);
  }, [open, connection?.id, prefillScope?.scope, prefillScope?.project_id, prefillScope?.agent_id]);

  if (!connection) return null;

  const meta = connection.connection || connection.manifest || {};
  const setupKind = setupKindFor(connection);
  const verifyEndpoint = meta.verify_endpoint;
  const verifySupported = Boolean(meta.verify_supported || verifyEndpoint);
  const deepLink = meta.deep_link;
  const unlocks = Array.isArray(meta.unlocks_tool_slugs) ? meta.unlocks_tool_slugs : [];
  const engines = Array.isArray(meta.engines) ? meta.engines : [];

  async function runVerify(payload) {
    if (!verifyEndpoint) {
      setError('This connection is missing its setup endpoint.');
      setStage(STAGES.SETUP);
      return;
    }

    setStage(STAGES.VERIFYING);
    setError(null);
    setHint(null);
    setWarning(null);
    setBusy(true);
    try {
      const res = await fetch(verifyEndpoint, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({
          credentials: payload || credentials,
          scope: scope.scope,
          project_id: scope.project_id || null,
          agent_id: scope.agent_id || null,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || !data?.ok) {
        setError(data?.error || 'We could not verify those credentials.');
        setHint(data?.hint || null);
        setStage(STAGES.SETUP);
        return;
      }
      setSummary(data.summary || null);
      setWarning(data.warning || null);
      setStage(STAGES.DONE);
      router.refresh();
    } catch {
      setError("We couldn't reach the service. Check your network and try again.");
      setStage(STAGES.SETUP);
    } finally {
      setBusy(false);
    }
  }

  async function disconnect() {
    if (!confirm(`Disconnect ${connection.title}? Stored credentials will be revoked.`)) return;
    setBusy(true);
    try {
      const res = await fetch(`/api/connections/${connection.slug}`, { method: 'DELETE' });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data?.error || 'Could not disconnect.');
        return;
      }
      setStage(STAGES.BENEFIT);
      setCredentials({});
      setSummary(null);
      router.refresh();
      onClose();
    } finally {
      setBusy(false);
    }
  }

  function renderSetupStep() {
    if (setupKind === 'qr_pair') {
      return (
        <QrPairStep
          connection={connection}
          onPaired={() => runVerify({})}
        />
      );
    }
    if (setupKind === 'binary_detect') {
      return (
        <BinaryDetectStep
          connection={connection}
          credentials={credentials}
          onChange={setCredentials}
          onSubmit={(next) => runVerify(next)}
          onCancel={onClose}
          busy={busy}
        />
      );
    }
    return (
      <ApiKeyStep
        connection={connection}
        credentials={credentials}
        onChange={setCredentials}
        scope={scope}
        onScopeChange={setScope}
        onSubmit={(next) => runVerify(next)}
        onCancel={onClose}
        error={error}
        hint={hint}
        busy={busy}
      />
    );
  }

  return (
    <AdminModal
      open={open}
      onClose={onClose}
      eyebrow="Marketplace · Connection"
      title={`Connect ${connection.title}`}
    >
      <div className="connection-setup">
        {stage === STAGES.BENEFIT ? (
          <section className="connection-setup-step connection-setup-step-benefit">
            <p className="connection-setup-benefit">
              {meta.benefit || connection.description}
            </p>
            {unlocks.length || engines.length ? (
              <ul className="connection-setup-unlocks">
                {engines.length ? (
                  <li>
                    <b>Engine:</b> {engines.join(', ')}
                  </li>
                ) : null}
                {unlocks.length ? (
                  <li>
                    <b>Unlocks {unlocks.length} tool{unlocks.length === 1 ? '' : 's'}:</b>{' '}
                    {unlocks.slice(0, 6).join(', ')}
                    {unlocks.length > 6 ? `, +${unlocks.length - 6} more` : ''}
                  </li>
                ) : null}
              </ul>
            ) : null}
            {connection.risk_summary ? (
              <p className="connection-setup-risk"><b>Heads up:</b> {connection.risk_summary}</p>
            ) : null}
            <div className="connection-setup-actions">
              <button
                type="button"
                className="admin-button secondary"
                onClick={onClose}
                disabled={busy}
              >
                Cancel
              </button>
              <button
                type="button"
                className="admin-button"
                onClick={() => setStage(STAGES.SETUP)}
                disabled={busy}
              >
                Continue
              </button>
            </div>
          </section>
        ) : null}

        {stage === STAGES.SETUP ? renderSetupStep() : null}

        {stage === STAGES.VERIFYING ? (
          <section className="connection-setup-step connection-setup-step-verify">
            <p>Verifying with {connection.title}…</p>
          </section>
        ) : null}

        {stage === STAGES.DONE ? (
          <section className="connection-setup-step connection-setup-step-done">
            <div className="connection-setup-done-head">
              <StatusPill status={{ status: 'connected', label: 'Connected' }} />
              <h3>{connection.title} is connected</h3>
            </div>
            {summary?.account_label || summary?.last_4 ? (
              <p className="connection-setup-summary">
                {summary.account_label ? <span>Account: {summary.account_label}</span> : null}
                {summary.last_4 ? <span> · Key ends in ••• {summary.last_4}</span> : null}
              </p>
            ) : (
              <p className="connection-setup-summary">Credentials stored in your local vault.</p>
            )}
            {warning ? (
              <p className="connection-setup-warning">
                <b>Warning:</b> {labelForWarningField(warning.field)} could not be verified ({labelForWarningReason(warning.reason)}). Other credentials were saved.
              </p>
            ) : null}
            {unlocks.length ? (
              <p className="connection-setup-unlocked">
                {unlocks.length} tool{unlocks.length === 1 ? '' : 's'} now available in the marketplace.
              </p>
            ) : null}
            {deepLink ? (
              <p className="connection-setup-deeplink">
                <a href={deepLink} className="admin-link">Open {connection.title} operations →</a>
              </p>
            ) : null}
            <div className="connection-setup-actions">
              <button
                type="button"
                className="admin-button secondary"
                onClick={disconnect}
                disabled={busy}
              >
                Disconnect
              </button>
              <button
                type="button"
                className="admin-button"
                onClick={onClose}
                disabled={busy}
              >
                Done
              </button>
            </div>
          </section>
        ) : null}
      </div>
    </AdminModal>
  );
}
