'use client'

import * as React from 'react'
import type { EntityVersionWithAuthor } from '@admin/actions/entity-versions'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger
} from '@admin/components/ui/alert-dialog'
import { Button } from '@admin/components/ui/button'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'

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

export function EntityVersionRestoreDialog({
  version,
  restoreVersionAction,
  onRestored
}: EntityVersionRestoreDialogProps) {
  const router = useRouter()
  const [open, setOpen] = React.useState(false)
  const [isPending, startTransition] = React.useTransition()

  function handleRestore() {
    startTransition(async () => {
      try {
        await restoreVersionAction(version.id)
        toast.success(`Restored v${version.version}`)
        setOpen(false)
        onRestored()
        router.refresh()
      } catch (error) {
        toast.error(error instanceof Error ? error.message : 'Failed to restore version')
      }
    })
  }

  return (
    <AlertDialog open={open} onOpenChange={setOpen}>
      <AlertDialogTrigger render={<Button variant="outline" size="sm" />}>
        Restore
      </AlertDialogTrigger>
      <AlertDialogContent>
        <AlertDialogHeader>
          <AlertDialogTitle>Restore v{version.version}?</AlertDialogTitle>
          <AlertDialogDescription>
            This replaces the current content with v{version.version}. The current content is saved
            as a new version first.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel disabled={isPending}>Cancel</AlertDialogCancel>
          <AlertDialogAction
            variant="default"
            onClick={(event) => {
              event.preventDefault()
              handleRestore()
            }}
            disabled={isPending}
            aria-busy={isPending}
          >
            {isPending ? 'Restoring…' : `Restore v${version.version}`}
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  )
}
