import { Link } from 'react-router-dom'
import type { Repository } from '../../types/api'
import { RepoAvatar } from '../../ui/RepoAvatar'

interface RepoCardProps {
  repo: Repository
}

export function RepoCard({ repo }: RepoCardProps) {
  const ago = timeAgo(repo.updatedAt)

  return (
    <Link
      to={`/repos/${repo.ownerName}/${repo.name}`}
      className="flex items-start gap-3 p-4 border border-[#DFE1E6] rounded hover:border-[#4C9AFF] hover:bg-[#FAFBFC] transition-colors group"
    >
      <RepoAvatar ownerName={repo.ownerName} name={repo.name} avatarUrl={repo.avatarUrl} size={36} />

      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="text-sm font-semibold text-[#0052CC] group-hover:underline truncate">
            {repo.name}
          </span>
          {repo.isPrivate && (
            <span className="text-[10px] font-medium px-1.5 py-0.5 rounded-full border border-[#DFE1E6] text-[#5E6C84] shrink-0">
              Private
            </span>
          )}
        </div>
        {repo.description && (
          <p className="text-xs text-[#5E6C84] mt-0.5 truncate">{repo.description}</p>
        )}
        <p className="text-xs text-[#5E6C84] mt-1">
          Updated {ago} · {repo.defaultBranch}
        </p>
      </div>
    </Link>
  )
}

function timeAgo(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const m = Math.floor(diff / 60000)
  if (m < 1) return 'just now'
  if (m < 60) return `${m}m ago`
  const h = Math.floor(m / 60)
  if (h < 24) return `${h}h ago`
  const d = Math.floor(h / 24)
  if (d < 30) return `${d}d ago`
  return new Date(iso).toLocaleDateString()
}
