// @design-system: domain/HealthFindingRow
/**
 * HealthFindingRow - single row in the system health findings table.
 *
 * Shows entity type, entity id (linked to the admin detail page when applicable),
 * detail text, first-seen, last-seen, and a "Re-arm" action button.
 *
 * Props:
 *   finding      — a system_health_findings row
 *   onRearmDone  — callback called after a successful re-arm POST
 *
 * Tones: warning when unresolved.
 * a11y: button with descriptive aria-label, status role on result flash.
 */

import { useState } from 'react';
import { cn } from '@/lib/cn';
import { useT, useLocale } from '@/lib/i18n/react';
import { formatDateTime } from '@/lib/format';
import { fetchWithRefresh } from '@/lib/api/refresh-on-401';

export interface HealthFindingRowData {
  id: string;
  kind: string;
  entityType: string;
  entityId: string;
  detail: string | null;
  firstSeenAt: string;
  lastSeenAt: string;
}

export interface HealthFindingRowProps {
  finding: HealthFindingRowData;
  /** Called with the finding id after a successful re-arm. */
  onRearmDone: (id: string) => void;
}

/** Returns the admin detail URL for the entity, or null if none exists. */
function adminDetailUrl(entityType: string, entityId: string): string | null {
  switch (entityType) {
    case 'deal':
    case 'gold_window':
      return `/admin/deals/${entityId}`;
    case 'group_deal':
      return null; // no dedicated admin page yet
    case 'personal_offer':
      return null;
    case 'group_hold':
      return null;
    case 'scheduled_publish':
      return `/admin/layout?page=${encodeURIComponent(entityId)}`;
    default:
      return null;
  }
}

export function HealthFindingRow({ finding, onRearmDone }: HealthFindingRowProps) {
  const t = useT('admin_system_health');
  const { locale } = useLocale();
  const [state, setState] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [errorMsg, setErrorMsg] = useState('');

  const detailUrl = adminDetailUrl(finding.entityType, finding.entityId);

  async function handleRearm() {
    setState('loading');
    setErrorMsg('');
    try {
      const res = await fetchWithRefresh('/api/admin/system-health/rearm', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ entityType: finding.entityType, entityId: finding.entityId }),
      });
      const body = (await res.json()) as { ok: boolean; error?: string };
      if (res.ok && body.ok) {
        setState('success');
        setTimeout(() => onRearmDone(finding.id), 800);
      } else {
        setState('error');
        setErrorMsg(body.error ?? t('rearm_error'));
      }
    } catch (err) {
      setState('error');
      setErrorMsg(err instanceof Error ? err.message : t('rearm_error'));
    }
  }

  const isLoading = state === 'loading';

  return (
    <tr
      className={cn(
        'border-border-default bg-surface-default border-b text-sm',
        state === 'success' ? 'bg-success-50' : 'hover:bg-surface-raised',
      )}
    >
      {/* Entity type */}
      <td className="text-text-secondary px-3 py-2 font-mono text-xs">{finding.entityType}</td>

      {/* Entity ID */}
      <td className="px-3 py-2 font-mono text-xs">
        {detailUrl ? (
          <a
            href={detailUrl}
            className="text-brand-600 underline-offset-2 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2"
          >
            {finding.entityId}
          </a>
        ) : (
          <span className="text-text-secondary break-all">{finding.entityId}</span>
        )}
      </td>

      {/* Detail */}
      <td className="text-text-secondary max-w-xs truncate px-3 py-2">{finding.detail ?? '—'}</td>

      {/* First seen */}
      <td className="text-text-muted whitespace-nowrap px-3 py-2">
        <time dateTime={finding.firstSeenAt}>
          {formatDateTime(finding.firstSeenAt, locale)}
        </time>
      </td>

      {/* Last seen */}
      <td className="text-text-muted whitespace-nowrap px-3 py-2">
        <time dateTime={finding.lastSeenAt}>
          {formatDateTime(finding.lastSeenAt, locale)}
        </time>
      </td>

      {/* Action */}
      <td className="px-3 py-2">
        {state === 'success' ? (
          <span role="status" className="text-success-600 text-xs font-medium">
            {t('rearm_success')}
          </span>
        ) : (
          <div className="flex flex-col gap-1">
            <button
              type="button"
              disabled={isLoading}
              aria-label={`${t('rearm_button')} — ${finding.entityType} ${finding.entityId}`}
              onClick={handleRearm}
              className={cn(
                'inline-flex items-center justify-center gap-1.5',
                'rounded-md px-2.5 py-1 text-xs font-medium',
                'border-warning-500 bg-warning-50 text-warning-700 border',
                'transition-colors duration-[var(--duration-fast)]',
                'hover:bg-warning-100',
                'focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2',
                'disabled:cursor-not-allowed disabled:opacity-50',
              )}
            >
              {isLoading ? t('rearming') : t('rearm_button')}
            </button>
            {state === 'error' && (
              <span role="alert" className="text-danger-600 text-xs">
                {errorMsg}
              </span>
            )}
          </div>
        )}
      </td>
    </tr>
  );
}
