'use client'

import { useEffect, useState, useRef } from 'react'
import { useTranslations } from 'next-intl'
import { useAuth } from '@/hooks/useAuth'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/layout/Header'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { LoadingRing } from '@/components/ui/loading-ring'
import { VersionTimeline, VersionTimelineRef } from '@/components/studio/VersionTimeline'
import { PermissionToggle } from '@/components/studio/PermissionToggle'
import {
  Save,
  ArrowLeft,
  FileText,
  Clock,
  Files,
  Clipboard
} from 'lucide-react'

interface PromptPageProps {
  params: Promise<{ id: string }>
}

interface PromptData {
  id: string
  name: string
  description: string | null
  content: string
  tags: string[]
  createdAt: string
  updatedAt: string
  lastUsed?: string | null
  currentVersion?: number
  usage?: number
  permissions?: 'private' | 'public'
  visibility?: 'under_review' | 'published' | null
}

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

export default function PromptPage({ params }: PromptPageProps) {
  const [promptId, setPromptId] = useState<string>('')

  useEffect(() => {
    params.then(p => setPromptId(p.id))
  }, [params])

  const { user, loading } = useAuth()
  const router = useRouter()
  const t = useTranslations('studio')
  const tCommon = useTranslations('common')

  const [prompt, setPrompt] = useState<PromptData | null>(null)
  const [promptContent, setPromptContent] = useState('')
  const [promptTitle, setPromptTitle] = useState('')
  const [isSaving, setIsSaving] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [currentVersion, setCurrentVersion] = useState<PromptVersion | null>(null)
  const [originalContent, setOriginalContent] = useState('')
  const [originalTitle, setOriginalTitle] = useState('')
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  const [isDuplicating, setIsDuplicating] = useState(false)
  const versionTimelineRef = useRef<VersionTimelineRef>(null)

  useEffect(() => {
    if (!loading && !user) {
      router.push('/signin')
      return
    }

    if (!user || !promptId) return

    const fetchPrompt = async () => {
      try {
        setIsLoading(true)
        const response = await fetch(`/api/prompts/${promptId}?userId=${user.id}`)
        if (response.ok) {
          const data = await response.json()
          // 确保tags是字符串数组
          const processedData = {
            ...data,
            tags: Array.isArray(data.tags)
              ? data.tags.map((tag: string | { name: string }) => typeof tag === 'string' ? tag : tag.name || '')
              : []
          }
          setPrompt(processedData)
          setPromptContent(data.content)
          setPromptTitle(data.name)
          setOriginalContent(data.content)
          setOriginalTitle(data.name)
          
          // 获取当前版本信息
          const versionResponse = await fetch(`/api/prompts/${promptId}/versions?userId=${user.id}&limit=1`)
          if (versionResponse.ok) {
            const versionData = await versionResponse.json()
            if (versionData.length > 0) {
              setCurrentVersion(versionData[0])
            }
          }
        } else {
          router.push('/studio')
        }
      } catch (error) {
        console.error('Error fetching prompt:', error)
        router.push('/studio')
      } finally {
        setIsLoading(false)
      }
    }

    fetchPrompt()
  }, [user, loading, router, promptId])

  // 检测未保存的更改
  useEffect(() => {
    const hasChanges = promptContent !== originalContent || promptTitle !== originalTitle
    setHasUnsavedChanges(hasChanges)
  }, [promptContent, promptTitle, originalContent, originalTitle])




  const handleUpdatePermissions = async (newPermissions: 'private' | 'public') => {
    if (!user || !promptId) return

    try {
      const response = await fetch(`/api/prompts/${promptId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          permissions: newPermissions,
          userId: user.id
        })
      })

      if (response.ok) {
        const updatedPrompt = await response.json()
        setPrompt(updatedPrompt)
      } else {
        throw new Error('Failed to update permissions')
      }
    } catch (error) {
      console.error('Error updating permissions:', error)
      throw error
    }
  }

  const handleSavePrompt = async () => {
    if (!user || !promptId) return

    setIsSaving(true)
    
    try {
      const response = await fetch(`/api/prompts/${promptId}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: promptTitle,
          content: promptContent,
          userId: user.id
        })
      })

      if (response.ok) {
        const updatedPrompt = await response.json()
        setPrompt(updatedPrompt)
        setOriginalContent(promptContent)
        setOriginalTitle(promptTitle)
        
        // 获取新的版本信息
        const versionResponse = await fetch(`/api/prompts/${promptId}/versions?userId=${user.id}&limit=1`)
        if (versionResponse.ok) {
          const versionData = await versionResponse.json()
          if (versionData.length > 0) {
            setCurrentVersion(versionData[0])
          }
        }
        
        // 刷新版本历史列表
        if (versionTimelineRef.current) {
          await versionTimelineRef.current.refreshVersions()
        }
      }
    } catch (error) {
      console.error('Failed to save prompt:', error)
    } finally {
      setIsSaving(false)
    }
  }

  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      // Could add toast notification here in the future
      console.log('Content copied to clipboard')
    } catch (error) {
      console.error('Failed to copy to clipboard:', error)
      // Fallback for older browsers
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
    }
  }

  const handleVersionSelect = (version: PromptVersion) => {
    setPromptContent(version.content)
    setOriginalContent(version.content)
    setCurrentVersion(version)
    
    // 重置保存状态
    setHasUnsavedChanges(false)
  }

  const handleVersionRestore = async (version: PromptVersion) => {
    if (!user || !promptId) return

    try {
      const response = await fetch(`/api/prompts/${promptId}/versions/${version.id}/restore`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: user.id })
      })

      if (response.ok) {
        const updatedPrompt = await response.json()
        setPrompt(updatedPrompt)
        setPromptContent(version.content)
        setOriginalContent(version.content)
        setCurrentVersion(version)
        
        // 刷新版本历史列表
        if (versionTimelineRef.current) {
          await versionTimelineRef.current.refreshVersions()
        }
      }
    } catch (error) {
      console.error('Error restoring version:', error)
      throw error
    }
  }

  const handleDuplicatePrompt = async () => {
    if (!user || !prompt) return

    setIsDuplicating(true)
    
    try {
      // 创建新的prompt，使用当前显示的内容
      const duplicatedPrompt = {
        name: `${promptTitle} 副本`,
        content: promptContent,
        description: prompt.description,
        tags: prompt.tags,
        userId: user.id
      }

      const response = await fetch('/api/prompts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(duplicatedPrompt)
      })

      if (response.ok) {
        const newPrompt = await response.json()
        router.push(`/studio/${newPrompt.id}`)
      } else {
        console.error('Failed to duplicate prompt')
      }
    } catch (error) {
      console.error('Error duplicating prompt:', error)
    } finally {
      setIsDuplicating(false)
    }
  }

  if (loading) {
    return null
  }

  if (!user) {
    return null
  }

  return (
    <div className="min-h-screen bg-background">
      <Header />

      {/* Top Navigation */}
      <div className="border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
        <div className="max-w-7xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button
                variant="ghost"
                size="sm"
                onClick={() => router.push('/studio')}
                className="flex items-center space-x-2"
              >
                <ArrowLeft className="h-4 w-4" />
                <span>{t('backToList')}</span>
              </Button>
              <div className="h-6 w-px bg-border" />
              <div className="flex items-center space-x-3">
                <div className="flex items-center space-x-2">
                  <FileText className="h-5 w-5 text-muted-foreground" />
                  <div>
                    {isLoading ? (
                      <div className="flex items-center space-x-2">
                        <LoadingRing size="sm" />
                        <span className="text-muted-foreground">Loading...</span>
                      </div>
                    ) : (
                      <>
                        <h1 className="font-semibold text-foreground">{prompt?.name || 'Loading...'}</h1>
                        <p className="text-xs text-muted-foreground">Version {prompt?.currentVersion || 1} • {prompt?.usage || 0} uses</p>
                      </>
                    )}
                  </div>
                </div>
              </div>
            </div>

            <div className="flex items-center space-x-3">
              <Button 
                variant="outline" 
                size="sm" 
                onClick={handleDuplicatePrompt}
                disabled={!prompt || isLoading || isDuplicating}
                className="flex items-center space-x-2 hover:bg-blue-50 hover:border-blue-200 dark:hover:bg-blue-950/30"
                title={t('duplicateThisPrompt')}
              >
                {isDuplicating ? (
                  <LoadingSpinner size="sm" className="mr-1" />
                ) : (
                  <Files className="h-4 w-4" />
                )}
                <span className="hidden sm:inline">{t('duplicateThisPrompt')}</span>
              </Button>
            </div>
          </div>
        </div>
      </div>

      <div className="max-w-7xl mx-auto p-4">
        {isLoading ? (
          /* Loading State */
          <div className="flex items-center justify-center py-16">
            <div className="text-center">
              <LoadingRing size="lg" className="mb-4" />
              <p className="text-muted-foreground">{t('loadingStudio')}</p>
            </div>
          </div>
        ) : !prompt ? (
          /* No Prompt State */
          <div className="text-center py-16">
            <p className="text-muted-foreground">Prompt not found</p>
          </div>
        ) : (
          <>
            {/* Mobile Layout (stacked) */}
            <div className="lg:hidden space-y-6">
              {/* 1. Prompt Editor (Mobile First) */}
              <div className="bg-card rounded-lg border border-border">
                <div className="p-4 border-b border-border">
                  <div className="flex items-center justify-between">
                    <h3 className="font-semibold text-foreground">{t('promptEditor')}</h3>
                    <div className="flex items-center space-x-1 text-xs text-muted-foreground">
                      <span>{promptContent.length} characters</span>
                    </div>
                  </div>
                </div>
                <div className="p-4">
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="promptTitle" className="text-sm font-medium">
                        {t('promptName')}
                      </Label>
                      <Input
                        id="promptTitle"
                        value={promptTitle}
                        onChange={(e) => setPromptTitle(e.target.value)}
                        className="mt-1"
                      />
                    </div>
                    <div>
                      <Label htmlFor="promptContent" className="text-sm font-medium">
                        {t('promptContent')}
                      </Label>
                      <Textarea
                        id="promptContent"
                        value={promptContent}
                        onChange={(e) => setPromptContent(e.target.value)}
                        className="mt-1 min-h-[300px] font-mono text-sm resize-none"
                        placeholder="Write your prompt here..."
                      />
                    </div>
                  </div>
                </div>
              </div>

          {/* Permissions (Mobile) */}
          <PermissionToggle
            permissions={prompt?.permissions || 'private'}
            visibility={prompt?.visibility}
            onUpdate={handleUpdatePermissions}
            disabled={isLoading}
            size="md"
            variant="card"
          />

          {/* Action Bar (Mobile) */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4">
            <div className="flex items-center space-x-3">
              <Button
                onClick={handleSavePrompt}
                disabled={isSaving}
                className="flex items-center space-x-2 flex-1 sm:flex-none"
              >
                {isSaving ? (
                  <LoadingSpinner size="sm" className="mr-2" />
                ) : (
                  <Save className="h-4 w-4 mr-2" />
                )}
                {tCommon('save')}
              </Button>

              <div className="h-6 w-px bg-border hidden sm:block"></div>

              <Button
                variant="outline"
                onClick={() => copyToClipboard(promptContent)}
                className="flex items-center space-x-2 hover:bg-green-50 hover:border-green-200 dark:hover:bg-green-950/30"
                size="sm"
                title={t('copyPromptContent')}
              >
                <Clipboard className="h-4 w-4" />
                <span className="hidden sm:inline ml-2">{t('copyPromptContent')}</span>
              </Button>
            </div>

            <div className="flex items-center justify-center space-x-2 text-sm">
              {hasUnsavedChanges ? (
                <>
                  <div className="w-2 h-2 rounded-full bg-orange-500 animate-pulse"></div>
                  <span className="text-orange-600 dark:text-orange-400">Unsaved changes</span>
                </>
              ) : (
                <>
                  <Clock className="h-4 w-4 text-muted-foreground" />
                  <span className="text-muted-foreground">All changes saved</span>
                </>
              )}
            </div>
          </div>

          {/* 2. Version History (Mobile Second) */}
          <div className="bg-card rounded-lg border border-border p-4">
            <VersionTimeline
              ref={versionTimelineRef}
              promptId={promptId}
              userId={user.id}
              currentVersion={currentVersion}
              hasUnsavedChanges={hasUnsavedChanges}
              onVersionSelect={handleVersionSelect}
              onVersionRestore={handleVersionRestore}
            />
          </div>

          {/* 3. Prompt Info (Mobile Third) */}
          <div className="bg-card rounded-lg border border-border p-4">
            <h3 className="font-semibold text-foreground mb-3">Prompt Info</h3>
            <div className="grid grid-cols-2 gap-3 text-sm">
              <div className="flex flex-col">
                <span className="text-muted-foreground text-xs">Created</span>
                <span className="text-foreground font-medium">{prompt?.createdAt ? new Date(prompt.createdAt).toLocaleDateString() : '-'}</span>
              </div>
              <div className="flex flex-col">
                <span className="text-muted-foreground text-xs">Updated</span>
                <span className="text-foreground font-medium">{prompt?.updatedAt ? new Date(prompt.updatedAt).toLocaleDateString() : '-'}</span>
              </div>
              <div className="flex flex-col">
                <span className="text-muted-foreground text-xs">Last used</span>
                <span className="text-foreground font-medium">{prompt?.lastUsed ? new Date(prompt.lastUsed).toLocaleDateString() : 'Never'}</span>
              </div>
              <div className="flex flex-col">
                <span className="text-muted-foreground text-xs">Usage count</span>
                <span className="text-foreground font-medium">{prompt?.usage || 0}</span>
              </div>
            </div>
            <div className="pt-3 border-t border-border mt-3">
              <div className="flex flex-wrap gap-1">
                {prompt?.tags?.map((tag: string | { name: string }) => {
                  const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                  return (
                    <span
                      key={tagName}
                      className="inline-flex items-center px-2 py-1 text-xs font-medium bg-muted text-muted-foreground rounded-full"
                    >
                      {tagName}
                    </span>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {/* Desktop Layout (optimized) */}
        <div className="hidden lg:block">
          <div className="grid grid-cols-3 gap-8">
            {/* Left Column - Prompt Editor (Desktop) */}
            <div className="col-span-2 space-y-6">
              {/* Action Bar */}
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <Button
                    onClick={handleSavePrompt}
                    disabled={isSaving}
                    className="flex items-center space-x-2"
                  >
                    {isSaving ? (
                      <LoadingSpinner size="sm" className="mr-2" />
                    ) : (
                      <Save className="h-4 w-4 mr-2" />
                    )}
                    {tCommon('save')}
                  </Button>

                  <div className="h-6 w-px bg-border"></div>

                  <Button
                    variant="outline"
                    onClick={() => copyToClipboard(promptContent)}
                    className="flex items-center space-x-2 hover:bg-green-50 hover:border-green-200 dark:hover:bg-green-950/30"
                    title={t('copyPromptContent')}
                  >
                    <Clipboard className="h-4 w-4 mr-2" />
                    {t('copyPromptContent')}
                  </Button>
                </div>

                <div className="flex items-center space-x-2 text-sm">
                  {hasUnsavedChanges ? (
                    <>
                      <div className="w-2 h-2 rounded-full bg-orange-500 animate-pulse"></div>
                      <span className="text-orange-600 dark:text-orange-400">Unsaved changes</span>
                    </>
                  ) : (
                    <>
                      <Clock className="h-4 w-4 text-muted-foreground" />
                      <span className="text-muted-foreground">All changes saved</span>
                    </>
                  )}
                </div>
              </div>

              {/* Prompt Editor */}
              <div className="bg-card rounded-lg border border-border">
                <div className="p-6 border-b border-border">
                  <div className="flex items-center justify-between">
                    <h3 className="text-lg font-semibold text-foreground">{t('promptEditor')}</h3>
                    <div className="flex items-center space-x-1 text-sm text-muted-foreground">
                      <span>{promptContent.length} characters</span>
                    </div>
                  </div>
                </div>
                <div className="p-6">
                  <div className="space-y-6">
                    <div>
                      <Label htmlFor="promptTitle" className="text-sm font-medium">
                        {t('promptName')}
                      </Label>
                      <Input
                        id="promptTitle"
                        value={promptTitle}
                        onChange={(e) => setPromptTitle(e.target.value)}
                        className="mt-2"
                      />
                    </div>

                    <div>
                      <Label htmlFor="promptContent" className="text-sm font-medium">
                        {t('promptContent')}
                      </Label>
                      <Textarea
                        id="promptContent"
                        value={promptContent}
                        onChange={(e) => setPromptContent(e.target.value)}
                        className="mt-2 min-h-[500px] font-mono text-sm resize-none"
                        placeholder="Write your prompt here..."
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* Right Column - Version History & Prompt Info */}
            <div className="col-span-1 space-y-6">
              {/* Version History */}
              <div className="bg-card rounded-lg border border-border p-4">
                <VersionTimeline
                  ref={versionTimelineRef}
                  promptId={promptId}
                  userId={user.id}
                  currentVersion={currentVersion}
                  hasUnsavedChanges={hasUnsavedChanges}
                  onVersionSelect={handleVersionSelect}
                  onVersionRestore={handleVersionRestore}
                />
              </div>

              {/* Prompt Info */}
              <div className="bg-card rounded-lg border border-border p-4">
                <h3 className="font-semibold text-foreground mb-4">Prompt Info</h3>
                <div className="space-y-4 text-sm">
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">Created</span>
                    <span className="text-foreground font-medium">{prompt?.createdAt ? new Date(prompt.createdAt).toLocaleDateString() : '-'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">Updated</span>
                    <span className="text-foreground font-medium">{prompt?.updatedAt ? new Date(prompt.updatedAt).toLocaleDateString() : '-'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">Last used</span>
                    <span className="text-foreground font-medium">{prompt?.lastUsed ? new Date(prompt.lastUsed).toLocaleDateString() : 'Never'}</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-muted-foreground">Usage count</span>
                    <span className="text-foreground font-medium">{prompt?.usage || 0}</span>
                  </div>
                  <div className="pt-3 border-t border-border">
                    <div className="flex flex-wrap gap-1">
                      {prompt?.tags?.map((tag: string | { name: string }) => {
                        const tagName = typeof tag === 'string' ? tag : tag?.name || '';
                        return (
                          <span
                            key={tagName}
                            className="inline-flex items-center px-2 py-1 text-xs font-medium bg-muted text-muted-foreground rounded-full"
                          >
                            {tagName}
                          </span>
                        );
                      })}
                    </div>
                  </div>
                </div>
              </div>

              {/* Permissions (Desktop) */}
              <PermissionToggle
                permissions={prompt?.permissions || 'private'}
                visibility={prompt?.visibility}
                onUpdate={handleUpdatePermissions}
                disabled={isLoading}
                size="md"
                variant="card"
              />
            </div>
          </div>
        </div>
          </>
        )}
      </div>
    </div>
  )
}