'use client'

import * as React from 'react'
import type { EntityVersionWithAuthor } from '@admin/actions/entity-versions'
import { EntityVersionsDrawer } from '@admin/components/shared/entity-versions/entity-versions-drawer'
import { Button } from '@admin/components/ui/button'
import { Spinner } from '@admin/components/ui/spinner'
import { useEntityVersions } from '@admin/hooks/use-entity-versions'
import { History } from 'lucide-react'

interface EntityVersionsButtonAuthor {
  name: string
  email: string
  image?: string | null
}

interface EntityVersionsButtonProps {
  entityType: string
  entityId: string
  updatedAt: Date | string
  updatedByUser: EntityVersionsButtonAuthor | null
  getVersionsAction: (entityId: string) => Promise<EntityVersionWithAuthor[]>
  restoreVersionAction: (versionId: string) => Promise<unknown>
}

export function EntityVersionsButton({
  entityType,
  entityId,
  updatedAt,
  updatedByUser,
  getVersionsAction,
  restoreVersionAction
}: EntityVersionsButtonProps) {
  const [open, setOpen] = React.useState(false)
  const { versions, isPending, load } = useEntityVersions({
    entityId,
    getVersionsAction
  })

  const handleOpenChange = React.useCallback(
    (nextOpen: boolean) => {
      setOpen(nextOpen)
      if (nextOpen) {
        load()
      }
    },
    [load]
  )

  return (
    <>
      <Button
        type="button"
        variant="ghost"
        size="sm"
        onClick={() => handleOpenChange(true)}
        disabled={isPending}
        aria-busy={isPending}
        className="ml-auto shrink-0"
      >
        {isPending ? <Spinner className="size-4" /> : <History className="size-4" />}
        {isPending ? 'Loading Versions…' : 'Versions'}
      </Button>
      <EntityVersionsDrawer
        open={open}
        onOpenChange={handleOpenChange}
        entityType={entityType}
        versions={versions}
        isPending={isPending}
        currentUpdatedAt={updatedAt}
        currentAuthor={updatedByUser}
        restoreVersionAction={restoreVersionAction}
        onRestored={load}
      />
    </>
  )
}
