'use client'

import { useState, useEffect, useImperativeHandle, forwardRef, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { Button } from '@/components/ui/button'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import {
  History,
  Eye,
  RotateCcw,
  AlertTriangle
} from 'lucide-react'

interface PromptVersion {
  id: string
  version: number
  content: string
  changelog: string
  createdAt: string
}

interface VersionTimelineProps {
  promptId: string
  userId: string
  currentVersion?: PromptVersion | null
  hasUnsavedChanges?: boolean
  onVersionSelect: (version: PromptVersion) => void
  onVersionRestore: (version: PromptVersion) => void
}

interface UserLimits {
  versionLimit: number
  maxVersionLimit: number
  subscribePlan: string
}

export interface VersionTimelineRef {
  refreshVersions: () => Promise<void>
}

export const VersionTimeline = forwardRef<VersionTimelineRef, VersionTimelineProps>(({ 
  promptId, 
  userId, 
  currentVersion,
  hasUnsavedChanges = false,
  onVersionSelect,
  onVersionRestore
}, ref) => {
  const t = useTranslations('studio')
  const [versions, setVersions] = useState<PromptVersion[]>([])
  const [loading, setLoading] = useState(true)
  const [selectedVersionId, setSelectedVersionId] = useState<string | null>(null)
  const [restoring, setRestoring] = useState<string | null>(null)
  const [showWarning, setShowWarning] = useState(false)
  const [pendingVersionId, setPendingVersionId] = useState<string | null>(null)
  const [userLimits, setUserLimits] = useState<UserLimits | null>(null)

  useEffect(() => {
    fetchVersions()
    fetchUserLimits()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [promptId, userId])

  useEffect(() => {
    if (currentVersion) {
      setSelectedVersionId(currentVersion.id)
    }
  }, [currentVersion])

  const fetchVersions = useCallback(async () => {
    try {
      setLoading(true)
      const response = await fetch(`/api/prompts/${promptId}/versions?userId=${userId}`)
      if (response.ok) {
        const data = await response.json()
        setVersions(data)
        if (data.length > 0 && !selectedVersionId) {
          setSelectedVersionId(data[0].id)
        }
      }
    } catch (error) {
      console.error('Error fetching versions:', error)
    } finally {
      setLoading(false)
    }
  }, [promptId, userId, selectedVersionId])

  // 暴露刷新函数给父组件
  useImperativeHandle(ref, () => ({
    refreshVersions: fetchVersions
  }), [fetchVersions])

  const fetchUserLimits = async () => {
    try {
      const response = await fetch(`/api/users/profile?userId=${userId}`)
      if (response.ok) {
        const userData = await response.json()
        setUserLimits({
          versionLimit: userData.versionLimit,
          maxVersionLimit: userData.maxVersionLimit,
          subscribePlan: userData.subscribePlan
        })
      }
    } catch (error) {
      console.error('Error fetching user limits:', error)
    }
  }

  const handleVersionSelect = (version: PromptVersion) => {
    if (hasUnsavedChanges && version.id !== selectedVersionId) {
      setShowWarning(true)
      setPendingVersionId(version.id)
      return
    }
    
    setSelectedVersionId(version.id)
    onVersionSelect(version)
  }

  const confirmVersionSwitch = () => {
    if (pendingVersionId) {
      const version = versions.find(v => v.id === pendingVersionId)
      if (version) {
        setSelectedVersionId(version.id)
        onVersionSelect(version)
      }
    }
    setShowWarning(false)
    setPendingVersionId(null)
  }

  const cancelVersionSwitch = () => {
    setShowWarning(false)
    setPendingVersionId(null)
  }

  const handleRestoreVersion = async (version: PromptVersion) => {
    if (restoring) return
    
    try {
      setRestoring(version.id)
      await onVersionRestore(version)
      await fetchVersions()
      setSelectedVersionId(version.id)
    } catch (error) {
      console.error('Error restoring version:', error)
    } finally {
      setRestoring(null)
    }
  }

  const formatDate = (dateString: string) => {
    const date = new Date(dateString)
    const now = new Date()
    const diff = now.getTime() - date.getTime()
    const hours = Math.floor(diff / (1000 * 60 * 60))
    const days = Math.floor(hours / 24)

    if (days === 0) {
      if (hours === 0) {
        const minutes = Math.floor(diff / (1000 * 60))
        return minutes <= 0 ? 'Just now' : `${minutes}m ago`
      }
      return `${hours}h ago`
    } else if (days < 7) {
      return `${days}d ago`
    } else {
      return new Intl.DateTimeFormat('default', {
        month: 'short',
        day: 'numeric'
      }).format(date)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center p-8">
        <LoadingSpinner size="lg" />
      </div>
    )
  }

  return (
    <>
      <div className="space-y-4">
        {/* Header */}
        <div className="space-y-3">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <History className="h-4 w-4 text-muted-foreground" />
              <h3 className="font-semibold text-foreground">{t('versionHistory')}</h3>
            </div>
            <span className="text-xs font-medium text-muted-foreground bg-muted px-2 py-1 rounded-full">
              {versions.length} {versions.length === 1 ? 'version' : 'versions'}
            </span>
          </div>
          {userLimits && (
            <div className="bg-muted/50 rounded-lg p-3 space-y-2">
              <div className="flex items-center justify-between text-xs">
                <span className="font-medium text-muted-foreground">Storage used</span>
                <div className="flex items-center space-x-2">
                  <span className="font-medium text-foreground">{versions.length}/{userLimits.maxVersionLimit}</span>
                  <span className="text-primary bg-primary/10 px-1.5 py-0.5 rounded text-xs font-semibold capitalize">
                    {userLimits.subscribePlan}
                  </span>
                </div>
              </div>
              <div className="w-full bg-background rounded-full h-2 overflow-hidden">
                <div 
                  className={`h-full rounded-full transition-all duration-300 ${
                    versions.length >= userLimits.versionLimit 
                      ? 'bg-gradient-to-r from-orange-500 to-red-500' 
                      : 'bg-gradient-to-r from-primary to-primary/70'
                  }`}
                  style={{ width: `${Math.min(100, (versions.length / userLimits.maxVersionLimit) * 100)}%` }}
                ></div>
              </div>
            </div>
          )}
        </div>

        {/* Timeline */}
        <div className="relative">
          {/* Timeline line */}
          <div className="absolute left-4 top-0 bottom-0 w-0.5 bg-gradient-to-b from-primary/20 via-border to-transparent"></div>
          
          <div className="space-y-2">
            {versions.map((version, index) => {
              const isSelected = selectedVersionId === version.id
              const isLatest = index === 0
              const isCurrentVersion = currentVersion?.id === version.id

              return (
                <div
                  key={version.id}
                  className={`group relative pl-10 pr-3 py-3 rounded-lg cursor-pointer transition-all duration-200 hover:bg-muted/70 hover:shadow-sm border border-transparent ${
                    isSelected 
                      ? 'bg-primary/5 border-primary/20 shadow-sm' 
                      : 'hover:border-border/50'
                  }`}
                  onClick={() => handleVersionSelect(version)}
                >
                  {/* Timeline dot */}
                  <div className={`absolute left-2.5 top-5 w-3.5 h-3.5 rounded-full transition-all duration-200 ${
                    isCurrentVersion && hasUnsavedChanges 
                      ? 'bg-orange-500 ring-2 ring-orange-200 dark:ring-orange-900 animate-pulse' 
                      : isSelected 
                        ? 'bg-primary ring-2 ring-primary/20 scale-110' 
                        : isLatest 
                          ? 'bg-green-500 ring-2 ring-green-200 dark:ring-green-900' 
                          : 'bg-muted-foreground/60 group-hover:bg-muted-foreground group-hover:scale-105'
                  }`}>
                    {/* Inner highlight for selected */}
                    {isSelected && (
                      <div className="absolute inset-1 bg-background rounded-full"></div>
                    )}
                  </div>

                  <div className="space-y-2">
                    {/* Version header */}
                    <div className="flex items-start justify-between">
                      <div className="flex items-center space-x-2 min-w-0 flex-1">
                        <span className={`text-sm font-semibold transition-colors ${
                          isSelected ? 'text-primary' : 'text-foreground'
                        }`}>
                          Version {version.version}
                        </span>
                        <div className="flex items-center space-x-1">
                          {isLatest && (
                            <span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold bg-green-500/10 text-green-700 dark:text-green-400 rounded-full border border-green-200 dark:border-green-800">
                              Latest
                            </span>
                          )}
                          {isCurrentVersion && hasUnsavedChanges && (
                            <span className="inline-flex items-center px-2 py-0.5 text-xs font-semibold bg-orange-500/10 text-orange-700 dark:text-orange-400 rounded-full border border-orange-200 dark:border-orange-800">
                              Modified
                            </span>
                          )}
                        </div>
                      </div>
                      <span className="text-xs font-medium text-muted-foreground whitespace-nowrap ml-2">
                        {formatDate(version.createdAt)}
                      </span>
                    </div>

                    {/* Changelog */}
                    <div className="pl-0">
                      <p className={`text-xs leading-relaxed transition-colors ${
                        isSelected ? 'text-muted-foreground' : 'text-muted-foreground/80'
                      } line-clamp-2`}>
                        {version.changelog || 'No changes recorded'}
                      </p>
                    </div>

                    {/* Action buttons - show on hover or when selected */}
                    <div className={`flex items-center space-x-2 pt-1 transition-all duration-200 ${
                      isSelected || 'group-hover' ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'
                    }`}>
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={(e) => {
                          e.stopPropagation()
                          onVersionSelect(version)
                        }}
                        className="h-7 px-2 text-xs font-medium hover:bg-primary/10 hover:text-primary"
                      >
                        <Eye className="h-3 w-3 mr-1" />
                        View
                      </Button>
                      {!isLatest && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={(e) => {
                            e.stopPropagation()
                            handleRestoreVersion(version)
                          }}
                          disabled={restoring === version.id}
                          className="h-7 px-2 text-xs font-medium hover:bg-blue-50 hover:text-blue-600 dark:hover:bg-blue-950/30 dark:hover:text-blue-400"
                        >
                          {restoring === version.id ? (
                            <LoadingSpinner size="sm" />
                          ) : (
                            <RotateCcw className="h-3 w-3 mr-1" />
                          )}
                          Restore
                        </Button>
                      )}
                    </div>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        {versions.length === 0 && (
          <div className="text-center py-12">
            <div className="bg-muted/30 rounded-full w-16 h-16 flex items-center justify-center mx-auto mb-4">
              <History className="h-8 w-8 text-muted-foreground" />
            </div>
            <h4 className="font-medium text-foreground mb-1">No version history</h4>
            <p className="text-sm text-muted-foreground">Versions will appear here as you save changes</p>
          </div>
        )}
      </div>

      {/* Warning Modal */}
      {showWarning && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
          <div className="bg-background border border-border rounded-xl shadow-2xl p-6 max-w-md w-full mx-4 animate-in fade-in-0 zoom-in-95 duration-200">
            <div className="flex items-start space-x-4">
              <div className="flex-shrink-0 w-10 h-10 bg-orange-100 dark:bg-orange-900/30 rounded-full flex items-center justify-center">
                <AlertTriangle className="h-5 w-5 text-orange-600 dark:text-orange-400" />
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="font-semibold text-foreground mb-2">
                  Unsaved Changes Detected
                </h3>
                <p className="text-sm text-muted-foreground mb-6 leading-relaxed">
                  You currently have unsaved changes that will be lost if you switch to a different version. Would you like to continue?
                </p>
                <div className="flex items-center justify-end space-x-3">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={cancelVersionSwitch}
                    className="font-medium"
                  >
                    Keep Editing
                  </Button>
                  <Button
                    variant="destructive"
                    size="sm"
                    onClick={confirmVersionSwitch}
                    className="font-medium"
                  >
                    Switch Version
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </>
  )
})

VersionTimeline.displayName = 'VersionTimeline'