'use client'

/**
 * SnapshotHistoryList — Check-Historie aus gespeicherten Snapshots.
 *
 * Neuester Snapshot oben + farblich abgesetzt. Klick → Detail-Seite mit den
 * Ergebnissen (/sdk/agent/snapshots/{id}). `refreshKey` neu setzen, um nach
 * einem frisch gelaufenen Compliance-Check neu zu laden.
 */

import React, { useEffect, useState } from 'react'
import Link from 'next/link'

interface SnapMeta {
  id: string
  check_id?: string
  site_domain?: string
  site_label?: string
  created_at?: string
}

export function SnapshotHistoryList(
  { refreshKey = 0, limit = 50 }: { refreshKey?: number; limit?: number },
) {
  const [snaps, setSnaps] = useState<SnapMeta[]>([])
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    setLoading(true)
    fetch(`/api/sdk/v1/agent/snapshots?limit=${limit}`)
      .then(r => r.json())
      .then(d => { if (!cancelled) setSnaps(d.snapshots || []) })
      .catch(() => { if (!cancelled) setSnaps([]) })
      .finally(() => { if (!cancelled) setLoading(false) })
    return () => { cancelled = true }
  }, [refreshKey, limit])

  return (
    <div className="space-y-2">
      <div className="flex items-baseline justify-between">
        <h2 className="text-sm font-semibold text-gray-900">Historie</h2>
        {!loading && snaps.length > 0 && (
          <span className="text-xs text-gray-400">{snaps.length} Checks</span>
        )}
      </div>

      {loading ? (
        <div className="text-sm text-gray-500">Lade Historie…</div>
      ) : snaps.length === 0 ? (
        <div className="text-sm text-gray-400 border border-dashed border-gray-200 rounded-lg px-4 py-6 text-center">
          Noch keine Checks — starte oben einen Compliance-Check.
        </div>
      ) : (
        <div className="border rounded-lg divide-y divide-gray-100 overflow-hidden">
          {snaps.map((s, i) => (
            <Link
              key={s.id}
              href={`/sdk/agent/snapshots/${s.id}`}
              className={`flex items-center gap-3 px-4 py-3 text-sm transition-colors ${
                i === 0 ? 'bg-purple-50 hover:bg-purple-100' : 'hover:bg-gray-50'
              }`}
            >
              {i === 0 && (
                <span className="px-1.5 py-0.5 rounded text-[10px] font-medium bg-purple-600 text-white shrink-0">
                  aktuellster
                </span>
              )}
              <span className={`font-medium w-44 truncate ${i === 0 ? 'text-purple-900' : 'text-gray-800'}`}>
                {s.site_label || s.site_domain || 'unbekannt'}
              </span>
              <span className="text-gray-500 flex-1 min-w-0 truncate">{s.site_domain}</span>
              <span className="text-xs text-gray-400 whitespace-nowrap">
                {(s.created_at || '').slice(0, 16).replace('T', ' ')}
              </span>
              <span className="text-gray-300">›</span>
            </Link>
          ))}
        </div>
      )}
    </div>
  )
}
