'use client'

import type { EntityVersionWithAuthor } from '@admin/actions/entity-versions'
import {
  Drawer,
  DrawerContent,
  DrawerDescription,
  DrawerHeader,
  DrawerTitle
} from '@admin/components/ui/drawer'
import { ScrollArea } from '@admin/components/ui/scroll-area'
import { EntityVersionItem } from './entity-version-item'
import { EntityVersionsCurrentRow } from './entity-versions-current-row'

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

interface EntityVersionsDrawerProps {
  open: boolean
  onOpenChange: (open: boolean) => void
  entityType: string
  versions: EntityVersionWithAuthor[]
  isPending: boolean
  currentUpdatedAt: Date | string
  currentAuthor: EntityVersionsDrawerAuthor | null
  restoreVersionAction: (versionId: string) => Promise<unknown>
  onRestored: () => void
}

export function EntityVersionsDrawer({
  open,
  onOpenChange,
  entityType,
  versions,
  isPending,
  currentUpdatedAt,
  currentAuthor,
  restoreVersionAction,
  onRestored
}: EntityVersionsDrawerProps) {
  return (
    <Drawer swipeDirection="right" open={open} onOpenChange={onOpenChange} modal>
      <DrawerContent className="h-full max-w-lg">
        <DrawerHeader>
          <DrawerTitle>Versions</DrawerTitle>
          <DrawerDescription>
            Review previous {entityType} versions and restore a saved state.
          </DrawerDescription>
        </DrawerHeader>
        <ScrollArea className="min-h-0 flex-1">
          <div className="flex flex-col gap-1 px-6">
            <EntityVersionsCurrentRow updatedAt={currentUpdatedAt} author={currentAuthor} />
            {isPending ? (
              <p className="rounded-sm border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
                Loading versions…
              </p>
            ) : null}
            {!isPending && versions.length === 0 ? (
              <p className="rounded-sm border border-dashed border-border px-3 py-6 text-center text-sm text-muted-foreground">
                No previous versions yet.
              </p>
            ) : null}
            {versions.map((version) => (
              <EntityVersionItem
                key={version.id}
                version={version}
                restoreVersionAction={restoreVersionAction}
                onRestored={onRestored}
              />
            ))}
          </div>
        </ScrollArea>
      </DrawerContent>
    </Drawer>
  )
}
