import type {
  CategoryKind,
  CategoryModeDto,
  ProviderControlAuditDto,
  ProviderIntegrationDto,
  ProviderIntegrationEnvironment,
  ProviderIntegrationSafetyWarning,
} from '@navi/types';
import { formatDate } from '@navi/ui';
import { AccessDenied } from '../../../components/AccessDenied';
import { EmptyState, Notice, PageHeader, StatusBadge } from '../../../components/DashboardPrimitives';
import { dashboardApi } from '../../../lib/api';
import { requireDashboardRoute } from '../../../lib/permissions';
import {
  createProviderIntegrationAction,
  disableProviderIntegrationAction,
  testProviderHealthAction,
  updateProviderIntegrationAction,
} from './actions';

const CATEGORY_KINDS: CategoryKind[] = ['STAY', 'ACTIVITY', 'FOOD', 'PHARMACY', 'GROCERY', 'SIM'];
const ENVIRONMENTS: ProviderIntegrationEnvironment[] = ['DEMO', 'SANDBOX', 'PRODUCTION'];

export default async function ProviderIntegrations({ searchParams }: { searchParams?: { status?: string; error?: string } }) {
  const gate = await requireDashboardRoute('/provider-integrations');
  if (!gate.allowed) return <AccessDenied required={gate.required} />;

  const integrations = (await dashboardApi<ProviderIntegrationDto[]>('/provider-control/provider-integrations')) ?? [];
  const categories = (await dashboardApi<CategoryModeDto[]>('/provider-control/category-modes')) ?? [];
  const auditLogs = (await dashboardApi<ProviderControlAuditDto[]>('/provider-control/audit-history?limit=100')) ?? [];
  const modeByKind = new Map(categories.map((category) => [category.kind, category.operatingMode]));

  return (
    <div className="stack">
      <PageHeader title="Provider integrations" eyebrow="Control Tower">
        <span className="muted">Only vault reference names are accepted. Raw API secrets are blocked by validation.</span>
      </PageHeader>

      {searchParams?.status ? <Notice tone="success" title="Provider control action saved" body="The API wrote the change and created a provider control audit entry." /> : null}
      {searchParams?.error ? <Notice tone="error" title="Provider control action failed" body="The request was blocked or failed. Check RBAC, validation, and API logs." /> : null}

      <section className="card stack">
        <h3 style={{ margin: 0 }}>Create provider integration</h3>
        <form action={createProviderIntegrationAction} className="stack">
          <div className="form-grid">
            <label className="form-field">
              <span className="form-label">Provider name</span>
              <input className="input" name="name" required placeholder="Example Hotel API" />
            </label>
            <label className="form-field">
              <span className="form-label">Category</span>
              <select className="input" name="categoryKind" required defaultValue="STAY">
                {CATEGORY_KINDS.map((kind) => <option key={kind} value={kind}>{kind}</option>)}
              </select>
            </label>
            <label className="form-field">
              <span className="form-label">Environment</span>
              <select className="input" name="environment" required defaultValue="DEMO">
                {ENVIRONMENTS.map((environment) => <option key={environment} value={environment}>{environment}</option>)}
              </select>
            </label>
            <label className="form-field">
              <span className="form-label">API base URL</span>
              <input className="input" name="apiBaseUrl" placeholder="https://sandbox.provider.example" />
            </label>
            <label className="form-field">
              <span className="form-label">Webhook URL</span>
              <input className="input" name="webhookUrl" placeholder="https://provider.example/webhooks/navi" />
            </label>
            <label className="form-field">
              <span className="form-label">Vault secret ref</span>
              <input className="input" name="vaultSecretRef" placeholder="doppler/navi/provider/example" />
            </label>
          </div>
          <div className="check-grid">
            {['enabled', 'bookingEnabled', 'paymentEnabled', 'refundEnabled', 'commissionEnabled', 'inquiryOnly', 'sandboxReady', 'liveReady'].map((name) => (
              <label key={name} className="check-label">
                <input type="checkbox" name={name} defaultChecked={name === 'inquiryOnly'} />
                {name.replace(/([A-Z])/g, ' $1')}
              </label>
            ))}
          </div>
          <div>
            <button className="btn-primary" type="submit">Create integration</button>
          </div>
        </form>
      </section>

      <section className="stack">
        {integrations.length ? integrations.map((integration) => {
          const operatingMode = modeByKind.get(integration.categoryKind) ?? 'DISABLED';
          const integrationAudit = auditLogs.filter((log) => log.resourceId === integration.id).slice(0, 4);
          return (
          <article key={integration.id} className="card stack">
            <div className="page-header" style={{ marginBottom: 0 }}>
              <div>
                <h3 style={{ margin: 0 }}>{integration.name}</h3>
                <p className="muted" style={{ margin: '6px 0 0' }}>
                  {integration.categoryKind} · {operatingMode.replace(/_/g, ' ')} · {integration.environment} · created {formatDate(integration.createdAt)}
                </p>
              </div>
              <div className="page-actions">
                <StatusBadge value={integration.enabled ? 'ENABLED' : 'DISABLED'} />
                <StatusBadge value={integration.healthStatus} />
                <StatusBadge value={operatingMode} />
              </div>
            </div>
            <SafetyWarnings warnings={integration.safetyWarnings} />
            <div className="field-grid">
              <ReadinessField label="Provider" value={integration.name} />
              <ReadinessField label="Category" value={integration.categoryKind} badge />
              <ReadinessField label="Operating mode" value={operatingMode} badge />
              <ReadinessField label="Environment" value={integration.environment} badge />
              <ReadinessField label="Enabled" value={integration.enabled ? 'Enabled' : 'Disabled'} badge />
              <ReadinessField label="Health status" value={integration.healthStatus} badge />
              <ReadinessField label="Booking" value={integration.bookingEnabled ? 'Enabled' : 'Disabled'} badge />
              <ReadinessField label="Payment" value={integration.paymentEnabled ? 'Enabled' : 'Disabled'} badge />
              <ReadinessField label="Refund" value={integration.refundEnabled ? 'Enabled' : 'Disabled'} badge />
              <ReadinessField label="Commission" value={integration.commissionEnabled ? 'Enabled' : 'Disabled'} badge />
              <ReadinessField label="Inquiry only" value={integration.inquiryOnly ? 'Yes' : 'No'} badge />
              <ReadinessField label="Sandbox ready" value={integration.sandboxReady ? 'Yes' : 'No'} badge />
              <ReadinessField label="Live ready" value={integration.liveReady ? 'Yes' : 'No'} badge />
              <ReadinessField label="Last sync" value={integration.lastSyncAt ? formatDate(integration.lastSyncAt) : 'No sync yet'} />
              <ReadinessField label="Last health check" value={integration.lastHealthCheckAt ? formatDate(integration.lastHealthCheckAt) : 'Not checked'} />
              <ReadinessField label="Vault secret ref" value={integration.vaultSecretRef ?? 'Missing vault reference'} mono warning={!integration.vaultSecretRef} />
              <ReadinessField label="Webhook URL" value={integration.webhookUrl ?? 'Not configured'} mono />
              <ReadinessField label="API base URL" value={integration.apiBaseUrl ?? 'Not configured'} mono />
              <ReadinessField label="Created by" value={integration.createdById ?? 'System or seed'} mono />
              <ReadinessField label="Updated by" value={integration.updatedById ?? 'System or seed'} mono />
              <ReadinessField label="Error message" value={integration.errorMessage ?? 'No error'} />
            </div>
            <form id={`update-${integration.id}`} action={updateProviderIntegrationAction} className="stack">
              <input type="hidden" name="integrationId" value={integration.id} />
              <div className="form-grid">
                <label className="form-field">
                  <span className="form-label">Provider name</span>
                  <input className="input" name="name" defaultValue={integration.name} required />
                </label>
                <label className="form-field">
                  <span className="form-label">Category</span>
                  <select className="input" name="categoryKind" defaultValue={integration.categoryKind}>
                    {CATEGORY_KINDS.map((kind) => <option key={kind} value={kind}>{kind}</option>)}
                  </select>
                </label>
                <label className="form-field">
                  <span className="form-label">Environment</span>
                  <select className="input" name="environment" defaultValue={integration.environment}>
                    {ENVIRONMENTS.map((environment) => <option key={environment} value={environment}>{environment}</option>)}
                  </select>
                </label>
                <label className="form-field">
                  <span className="form-label">API base URL</span>
                  <input className="input" name="apiBaseUrl" defaultValue={integration.apiBaseUrl ?? ''} />
                </label>
                <label className="form-field">
                  <span className="form-label">Webhook URL</span>
                  <input className="input" name="webhookUrl" defaultValue={integration.webhookUrl ?? ''} />
                </label>
                <label className="form-field">
                  <span className="form-label">Vault secret ref</span>
                  <input className="input" name="vaultSecretRef" defaultValue={integration.vaultSecretRef ?? ''} />
                </label>
              </div>
              <div className="check-grid">
                {[
                  ['enabled', integration.enabled],
                  ['bookingEnabled', integration.bookingEnabled],
                  ['paymentEnabled', integration.paymentEnabled],
                  ['refundEnabled', integration.refundEnabled],
                  ['commissionEnabled', integration.commissionEnabled],
                  ['inquiryOnly', integration.inquiryOnly],
                  ['sandboxReady', integration.sandboxReady],
                  ['liveReady', integration.liveReady],
                ].map(([name, checked]) => (
                  <label key={String(name)} className="check-label">
                    <input type="checkbox" name={String(name)} defaultChecked={Boolean(checked)} />
                    {String(name).replace(/([A-Z])/g, ' $1')}
                  </label>
                ))}
              </div>
            </form>
            <div className="button-row">
              <button className="btn-primary" type="submit" form={`update-${integration.id}`}>Save changes</button>
              <form action={testProviderHealthAction}>
                <input type="hidden" name="integrationId" value={integration.id} />
                <button className="btn-secondary" type="submit">Run mock health check</button>
              </form>
              <form action={disableProviderIntegrationAction}>
                <input type="hidden" name="integrationId" value={integration.id} />
                <button className="btn-danger" type="submit">Disable</button>
              </form>
            </div>
            <p className="muted" style={{ margin: 0 }}>
              Last health check: {integration.lastHealthCheckAt ? formatDate(integration.lastHealthCheckAt) : 'Not checked'}.
              {integration.errorMessage ? ` ${integration.errorMessage}` : ''}
            </p>
            <AuditTimeline logs={integrationAudit} />
          </article>
        );
        }) : (
          <div className="card">
            <EmptyState title="No provider integrations configured" body="Create a demo, sandbox, or production configuration. This page does not use fake provider settings." />
          </div>
        )}
      </section>
    </div>
  );
}

function AuditTimeline({ logs }: { logs: ProviderControlAuditDto[] }) {
  return (
    <div className="field-card">
      <div className="field-label">Audit timeline</div>
      {logs.length ? (
        <div className="stack" style={{ gap: 10, marginTop: 10 }}>
          {logs.map((log) => (
            <div key={log.id} className="button-row">
              <StatusBadge value={log.action} />
              <span className="muted">{formatDate(log.createdAt)}</span>
              <span className="mono muted">{log.actorId ?? log.actorType}</span>
            </div>
          ))}
        </div>
      ) : (
        <p className="muted" style={{ margin: '8px 0 0' }}>
          No recent audit entries are visible here, or this dashboard role does not have provider audit read permission.
        </p>
      )}
    </div>
  );
}

function ReadinessField({
  label,
  value,
  badge = false,
  mono = false,
  warning = false,
}: {
  label: string;
  value: string;
  badge?: boolean;
  mono?: boolean;
  warning?: boolean;
}) {
  return (
    <div className={`field-card ${warning ? 'field-card-warning' : ''}`}>
      <div className="field-label">{label}</div>
      <div className={`field-value ${mono ? 'mono' : ''}`}>{badge ? <StatusBadge value={value.toUpperCase().replace(/\s/g, '_')} /> : value}</div>
    </div>
  );
}

function SafetyWarnings({ warnings }: { warnings: ProviderIntegrationSafetyWarning[] }) {
  if (!warnings.length) {
    return <Notice tone="success" title="No readiness warnings" body="This integration has no current safety blockers from the shared readiness rules." />;
  }

  const hasBlocker = warnings.some((warning) => warning.level === 'BLOCKER');
  return (
    <div className={`notice ${hasBlocker ? 'notice-error' : 'notice-info'}`}>
      <strong>{hasBlocker ? 'Readiness blockers' : 'Readiness labels'}</strong>
      <div className="button-row" style={{ marginTop: 10 }}>
        {warnings.map((warning) => (
          <span key={warning.code} title={warning.message}>
            <StatusBadge value={`${warning.level}_${warning.label}`.toUpperCase().replace(/\s/g, '_')} />
          </span>
        ))}
      </div>
    </div>
  );
}
