'use client'

import { useState, useEffect } from 'react'
import { X, RotateCcw, Clock, User, Loader2 } from 'lucide-react'
import { toast } from 'sonner'
import { cmsApi } from '../lib/api.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-green-100 text-green-800' },
  UPDATE: { label: 'Updated', color: 'bg-blue-100 text-blue-800' },
  DELETE: { label: 'Deleted', color: 'bg-red-100 text-red-800' },
  RESTORE: { label: 'Restored', color: 'bg-purple-100 text-purple-800' },
}

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)
  }

  if (!open) return null

  return (
    <div className="fixed inset-0 z-50 flex justify-end">
      <div className="fixed inset-0 bg-black/30" onClick={onClose} />
      <div className="animate-in slide-in-from-right relative flex w-full max-w-md flex-col bg-white shadow-xl">
        <div className="flex items-center justify-between border-b border-gray-200 px-4 py-3">
          <div className="flex items-center gap-2">
            <Clock className="h-5 w-5 text-gray-600" />
            <h2 className="text-lg font-semibold text-gray-900">Version History</h2>
          </div>
          <button
            onClick={onClose}
            className="rounded-lg p-1.5 transition-colors hover:bg-gray-100"
          >
            <X className="h-5 w-5 text-gray-500" />
          </button>
        </div>

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

                return (
                  <div key={version.id} className="px-4 py-3 transition-colors hover:bg-gray-50">
                    <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-xs font-medium text-gray-400">Current</span>
                          )}
                        </div>
                        <div className="flex items-center gap-3 text-xs text-gray-500">
                          {version.changedBy && (
                            <span className="flex items-center gap-1">
                              <User className="h-3 w-3" />
                              {version.changedBy.name ?? version.changedBy.email ?? 'Unknown'}
                            </span>
                          )}
                          <span title={new Date(version.createdAt).toLocaleString()}>
                            {timeAgo(version.createdAt)}
                          </span>
                        </div>
                      </div>
                      {!isLatest && (
                        <button
                          onClick={() => handleRestore(version)}
                          disabled={restoring === version.id}
                          className="flex items-center gap-1.5 rounded-lg bg-blue-50 px-2.5 py-1.5 text-xs font-medium text-blue-700 transition-colors hover:bg-blue-100 disabled:opacity-50"
                        >
                          {restoring === version.id ? (
                            <Loader2 className="h-3.5 w-3.5 animate-spin" />
                          ) : (
                            <RotateCcw className="h-3.5 w-3.5" />
                          )}
                          Restore
                        </button>
                      )}
                    </div>
                  </div>
                )
              })}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
