'use client'

import type { EntityVersionWithAuthor } from '@admin/actions/entity-versions'
import { EntityVersionsButton } from '@admin/components/shared/entity-versions/entity-versions-button'
import { Badge } from '@admin/components/ui/badge'
import { Separator } from '@admin/components/ui/separator'
import { format } from 'date-fns'

interface EntityMetadataData {
  id: string | null
  createdAt: Date | string
  updatedAt: Date | string
  createdByUser?: {
    id: string
    name: string
    email: string
  } | null
  updatedByUser?: {
    id: string
    name: string
    email: string
  } | null
  published?: boolean | null
}

interface EntityMetadataProps {
  data: EntityMetadataData
  entityType: string
  entityId: string | null
  getVersionsAction: (entityId: string) => Promise<EntityVersionWithAuthor[]>
  restoreVersionAction: (versionId: string) => Promise<unknown>
}

export function EntityMetadata({
  data,
  entityType,
  entityId,
  getVersionsAction,
  restoreVersionAction
}: EntityMetadataProps) {
  const updated = new Date(data.updatedAt)
  const created = new Date(data.createdAt)
  const fullFmt = 'PPpp'
  const createdBy = data.createdByUser?.name || data.createdByUser?.email || 'System'
  const updatedBy = data.updatedByUser?.name || data.updatedByUser?.email || 'System'
  const status =
    typeof data.published === 'boolean' ? (data.published ? 'Published' : 'Draft') : null

  return (
    <div className="flex w-full flex-wrap items-center justify-between gap-3 text-sm text-muted-foreground">
      <div className="flex flex-wrap items-center gap-3">
        <div className="flex items-center gap-1">
          <span>ID</span>
          <span className="text-foreground">{data.id}</span>
        </div>

        <Separator orientation="vertical" className="my-auto h-4 rotate-20" />

        <div className="flex items-center gap-1">
          <span>Created by</span>
          <span className="text-foreground">{createdBy}</span>
          <span>on</span>
          <span className="text-foreground">{format(created, fullFmt)}</span>
        </div>

        <Separator orientation="vertical" className="my-auto h-4 rotate-20" />

        <div className="flex items-center gap-1">
          <span>Last edited by</span>
          <span className="text-foreground">{updatedBy}</span>
          <span>on</span>
          <span className="text-foreground">{format(updated, fullFmt)}</span>
        </div>

        {status ? (
          <Badge variant="outline" className="h-6">
            {status}
          </Badge>
        ) : null}
      </div>
      {entityId ? (
        <EntityVersionsButton
          entityType={entityType}
          entityId={entityId}
          updatedAt={data.updatedAt}
          updatedByUser={data.updatedByUser ?? null}
          getVersionsAction={getVersionsAction}
          restoreVersionAction={restoreVersionAction}
        />
      ) : null}
    </div>
  )
}
