'use client'

import { useState, useEffect } from 'react'
import * as Dialog from '@radix-ui/react-dialog'
import { X, RotateCcw, Clock, User, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { cmsApi } from '../lib/api.js'
import { adminPortalContainer } from '../lib/portal-container.js'

interface Version {
  id: string
  changeType: string
  createdAt: string
  data: Record<string, unknown>
  changedBy?: {
    id: string
    name?: string
    email?: string
  }
}

export interface VersionHistoryProps {
  collectionSlug: string
  documentId: string
  open: boolean
  onClose: () => void
  onRestore?: (data: Record<string, unknown>) => void
}

function timeAgo(dateStr: string): string {
  const diff = Date.now() - new Date(dateStr).getTime()
  const minutes = Math.floor(diff / 60_000)
  if (minutes < 1) return 'just now'
  if (minutes < 60) return `${minutes}m ago`
  const hours = Math.floor(minutes / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.floor(hours / 24)
  if (days < 30) return `${days}d ago`
  return new Date(dateStr).toLocaleDateString()
}

const CHANGE_TYPE_LABELS: Record<string, { label: string; color: string }> = {
  CREATE: { label: 'Created', color: 'bg-success/15 text-success' },
  UPDATE: { label: 'Updated', color: 'bg-primary/15 text-primary' },
  DELETE: { label: 'Deleted', color: 'bg-destructive/15 text-destructive' },
  RESTORE: { label: 'Restored', color: 'bg-accent text-accent-foreground' },
}

export function VersionHistory({
  collectionSlug,
  documentId,
  open,
  onClose,
  onRestore,
}: VersionHistoryProps) {
  const [versions, setVersions] = useState<Version[]>([])
  const [loading, setLoading] = useState(false)
  const [restoring, setRestoring] = useState<string | null>(null)

  useEffect(() => {
    if (open) fetchVersions()
  }, [open, collectionSlug, documentId])

  async function fetchVersions() {
    setLoading(true)
    const res = await cmsApi<{ versions: Version[]; total: number }>(
      `/collections/${collectionSlug}/${documentId}/versions?pageSize=50`,
    )
    if (res.data) {
      setVersions((res.data as any).versions ?? [])
    }
    setLoading(false)
  }

  async function handleRestore(version: Version) {
    setRestoring(version.id)
    const res = await cmsApi<any>(
      `/collections/${collectionSlug}/${documentId}/versions/${version.id}/restore`,
      { method: 'POST' },
    )
    if (res.error) {
      toast.error(res.error)
    } else {
      toast.success('Version restored')
      if (onRestore && version.data) {
        onRestore(version.data)
      }
      fetchVersions()
    }
    setRestoring(null)
  }

  return (
    <Dialog.Root open={open} onOpenChange={(next) => !next && onClose()}>
      <Dialog.Portal container={adminPortalContainer()}>
        <Dialog.Overlay className="fixed inset-0 z-50 bg-black/30" />
        <Dialog.Content
          aria-describedby={undefined}
          className="bg-card text-card-foreground border-border animate-in slide-in-from-right fixed inset-y-0 right-0 z-50 flex w-full max-w-md flex-col border-l shadow-xl focus:outline-none"
        >
          <div className="border-border flex items-center justify-between border-b px-4 py-3">
            <div className="flex items-center gap-2">
              <Clock className="text-muted-foreground h-5 w-5" aria-hidden />
              <Dialog.Title className="text-foreground text-lg font-medium">
                Version History
              </Dialog.Title>
            </div>
            <Dialog.Close asChild>
              <button
                type="button"
                aria-label="Close version history"
                className="text-muted-foreground hover:bg-accent hover:text-foreground focus-visible:ring-ring rounded-lg p-1.5 transition-colors focus-visible:ring-2 focus-visible:outline-none"
              >
                <X className="h-5 w-5" aria-hidden />
              </button>
            </Dialog.Close>
          </div>

          <div className="flex-1 overflow-y-auto">
            {loading ? (
              <div className="flex items-center justify-center py-16">
                <Loader2 className="text-muted-foreground h-6 w-6 animate-spin" aria-hidden />
              </div>
            ) : versions.length === 0 ? (
              <div className="text-muted-foreground py-16 text-center text-sm">
                No version history available
              </div>
            ) : (
              <div className="divide-border divide-y">
                {versions.map((version, index) => {
                  const typeInfo = CHANGE_TYPE_LABELS[version.changeType] ?? {
                    label: version.changeType,
                    color: 'bg-muted text-muted-foreground',
                  }
                  const isLatest = index === 0

                  return (
                    <div
                      key={version.id}
                      className="hover:bg-accent/50 px-4 py-3 transition-colors"
                    >
                      <div className="flex items-start justify-between gap-3">
                        <div className="min-w-0 flex-1">
                          <div className="mb-1 flex items-center gap-2">
                            <span
                              className={`inline-flex rounded-full px-2 py-0.5 text-xs font-medium ${typeInfo.color}`}
                            >
                              {typeInfo.label}
                            </span>
                            {isLatest && (
                              <span className="text-muted-foreground text-xs font-medium">
                                Current
                              </span>
                            )}
                          </div>
                          <div className="text-muted-foreground flex items-center gap-3 text-xs">
                            {version.changedBy && (
                              <span className="flex items-center gap-1">
                                <User className="h-3 w-3" aria-hidden />
                                {version.changedBy.name ?? version.changedBy.email ?? 'Unknown'}
                              </span>
                            )}
                            <span title={new Date(version.createdAt).toLocaleString()}>
                              {timeAgo(version.createdAt)}
                            </span>
                          </div>
                        </div>
                        {!isLatest && (
                          <button
                            type="button"
                            onClick={() => handleRestore(version)}
                            disabled={restoring === version.id}
                            className="bg-primary/10 text-primary hover:bg-primary/20 flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-xs font-medium transition-colors disabled:opacity-50"
                          >
                            {restoring === version.id ? (
                              <Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden />
                            ) : (
                              <RotateCcw className="h-3.5 w-3.5" aria-hidden />
                            )}
                            Restore
                          </button>
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </Dialog.Content>
      </Dialog.Portal>
    </Dialog.Root>
  )
}
