'use client'

import type { EntityVersionWithAuthor } from '@admin/actions/entity-versions'
import { Avatar, AvatarFallback, AvatarImage } from '@admin/components/ui/avatar'
import { Badge } from '@admin/components/ui/badge'
import { Tooltip, TooltipContent, TooltipTrigger } from '@admin/components/ui/tooltip'
import { getUserInitials } from '@admin/utils/user/get-user-initials'
import { format, formatDistanceToNow } from 'date-fns'
import { EntityVersionRestoreDialog } from './entity-version-restore-dialog'

interface EntityVersionItemProps {
  version: EntityVersionWithAuthor
  restoreVersionAction: (versionId: string) => Promise<unknown>
  onRestored: () => void
}

export function EntityVersionItem({
  version,
  restoreVersionAction,
  onRestored
}: EntityVersionItemProps) {
  const createdDate = new Date(version.createdAt)
  const author = version.createdByUser
  const authorLabel = author?.name || author?.email || 'System'

  return (
    <div className="flex items-center justify-between gap-3 rounded-sm border border-border px-3 py-3 shadow-input">
      <div className="flex min-w-0 items-center gap-3">
        <Avatar size="sm">
          {author?.image ? <AvatarImage src={author.image} alt={authorLabel} /> : null}
          <AvatarFallback>{getUserInitials(authorLabel)}</AvatarFallback>
        </Avatar>
        <div className="min-w-0">
          <div className="flex items-center gap-2">
            <p className="truncate font-medium text-foreground">{authorLabel}</p>
            <Badge variant="secondary">v{version.version}</Badge>
          </div>
          <Tooltip>
            <TooltipTrigger render={<p className="w-fit text-xs text-muted-foreground" />}>
              Saved {formatDistanceToNow(createdDate, { addSuffix: true })}
            </TooltipTrigger>
            <TooltipContent>{format(createdDate, 'PPpp')}</TooltipContent>
          </Tooltip>
        </div>
      </div>
      <EntityVersionRestoreDialog
        version={version}
        restoreVersionAction={restoreVersionAction}
        onRestored={onRestored}
      />
    </div>
  )
}
