'use client'

import { useState, useEffect, useCallback } from 'react'
import { useTranslations } from 'next-intl'
import { useBetterAuth } from '@/hooks/useBetterAuth'
import { useRouter } from 'next/navigation'
import { Header } from '@/components/layout/Header'
import { Footer } from '@/components/layout/Footer'
import { Button } from '@/components/ui/button'
import { Card } from '@/components/ui/card'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { 
  ArrowLeft, 
  Play,
  Settings,
  Zap,
  DollarSign,
  ChevronRight,
  ChevronDown,
  Edit
} from 'lucide-react'
import Link from 'next/link'

interface Prompt {
  id: string
  name: string
  content: string
  versions: Array<{
    id: string
    version: number
    content: string
  }>
}

// 生成模式枚举
type GenerationMode = 'text' | 'image'

// 支持的图像生成模型ID映射
const SUPPORTED_IMAGE_MODELS = {
  'gpt-image-1': {
    id: 'gpt-image-1',
    name: 'GPT Image 1',
    adapter: 'gpt-image-1'
  },
  'google/gemini-2.5-flash-image-preview': {
    id: 'google/gemini-2.5-flash-image-preview',
    name: 'Gemini 2.5 Flash Image Preview', 
    adapter: 'gemini-image'
  }
} as const

interface Model {
  id: string
  modelId: string
  name: string
  provider: string
  serviceProvider: string
  outputType: string
  description?: string
  maxTokens?: number
  inputCostPer1k?: number
  outputCostPer1k?: number
  supportedFeatures?: Record<string, unknown>
}

export default function NewSimulatorRunPage() {
  const { user, loading: authLoading } = useBetterAuth()
  const router = useRouter()
  const t = useTranslations('simulator')
  
  const [prompts, setPrompts] = useState<Prompt[]>([])
  const [models, setModels] = useState<Model[]>([])
  const [selectedPromptId, setSelectedPromptId] = useState('')
  const [selectedVersionId, setSelectedVersionId] = useState('')
  const [selectedModelId, setSelectedModelId] = useState('')
  const [userInput, setUserInput] = useState('')
  const [isLoading, setIsLoading] = useState(true)
  const [isCreating, setIsCreating] = useState(false)
  const [showAdvanced, setShowAdvanced] = useState(false)
  const [editablePromptContent, setEditablePromptContent] = useState('')
  const [isEditingPrompt, setIsEditingPrompt] = useState(false)
  
  // 新增状态
  const [simulatorName, setSimulatorName] = useState('')
  const [promptInputMode, setPromptInputMode] = useState<'select' | 'create'>('select') // 选择模式：选择现有提示词 或 创建新提示词
  
  // 生成模式相关状态
  const [generationMode, setGenerationMode] = useState<GenerationMode>('text')
  const [filteredModels, setFilteredModels] = useState<Model[]>([])
  
  // Advanced settings
  const [temperature, setTemperature] = useState('0.7')
  const [maxTokens, setMaxTokens] = useState('')
  const [topP, setTopP] = useState('1')
  const [frequencyPenalty, setFrequencyPenalty] = useState('0')
  const [presencePenalty, setPresencePenalty] = useState('0')

  // 模型过滤逻辑
  const filterModelsByMode = useCallback((allModels: Model[], mode: GenerationMode) => {
    if (mode === 'text') {
      // 文本模式：显示所有outputType为text的模型
      return allModels.filter(model => model.outputType === 'text')
    } else if (mode === 'image') {
      // 图像模式：只显示已适配的图像生成模型
      return allModels.filter(model => 
        model.outputType === 'image' && 
        Object.keys(SUPPORTED_IMAGE_MODELS).includes(model.modelId)
      )
    }
    return []
  }, [])

  // 当生成模式改变时更新模型列表
  useEffect(() => {
    const filtered = filterModelsByMode(models, generationMode)
    setFilteredModels(filtered)
    
    // 重置已选择的模型，选择第一个可用模型
    if (filtered.length > 0) {
      setSelectedModelId(filtered[0].id)
    } else {
      setSelectedModelId('')
    }
  }, [models, generationMode, filterModelsByMode])

  const fetchData = useCallback(async () => {
    if (!user) return
    
    try {
      setIsLoading(true)
      
      const [promptsResponse, modelsResponse] = await Promise.all([
        fetch('/api/simulator/prompts?limit=100'),
        fetch('/api/simulator/models')
      ])

      if (promptsResponse.ok) {
        const promptsData = await promptsResponse.json()
        setPrompts(promptsData.prompts || [])
      }

      if (modelsResponse.ok) {
        const modelsData = await modelsResponse.json()
        setModels(modelsData.models || [])
        // 模型选择逻辑现在由useEffect处理
      }
    } catch (error) {
      console.error('Error fetching data:', error)
    } finally {
      setIsLoading(false)
    }
  }, [user])

  const selectedPrompt = prompts.find(p => p.id === selectedPromptId)
  const selectedModel = models.find(m => m.id === selectedModelId)

  useEffect(() => {
    if (!authLoading && user) {
      fetchData()
    }
  }, [user, authLoading, fetchData])

  const handlePromptChange = (promptId: string) => {
    setSelectedPromptId(promptId)
    setSelectedVersionId('')
    setIsEditingPrompt(false)
    
    // Auto-select latest version
    const prompt = prompts.find(p => p.id === promptId)
    if (prompt && prompt.versions.length > 0) {
      const latestVersion = prompt.versions.reduce((latest, current) => 
        current.version > latest.version ? current : latest
      )
      setSelectedVersionId(latestVersion.id)
      setEditablePromptContent(latestVersion.content)
    } else if (prompt) {
      setEditablePromptContent(prompt.content)
    }
    
    // 自动填充名称（如果当前名称为空）
    if (!simulatorName && prompt) {
      setSimulatorName(`${prompt.name} 模拟运行`)
    }
  }

  const handleVersionChange = (versionId: string) => {
    setSelectedVersionId(versionId)
    setIsEditingPrompt(false)
    
    const selectedPrompt = prompts.find(p => p.id === selectedPromptId)
    if (versionId && selectedPrompt) {
      const version = selectedPrompt.versions.find(v => v.id === versionId)
      if (version) {
        setEditablePromptContent(version.content)
      }
    } else if (selectedPrompt) {
      // Use latest version if no specific version selected
      setEditablePromptContent(selectedPrompt.content)
    }
  }

  const handleEditPrompt = () => {
    setIsEditingPrompt(true)
  }

  const handleSavePromptEdit = () => {
    setIsEditingPrompt(false)
  }

  const handleCancelPromptEdit = () => {
    setIsEditingPrompt(false)
    // Reset to original content
    const selectedPrompt = prompts.find(p => p.id === selectedPromptId)
    if (selectedVersionId && selectedPrompt) {
      const version = selectedPrompt.versions.find(v => v.id === selectedVersionId)
      if (version) {
        setEditablePromptContent(version.content)
      }
    } else if (selectedPrompt) {
      setEditablePromptContent(selectedPrompt.content)
    }
  }

  const getCustomPromptContent = () => {
    // Get original content for comparison
    const selectedPrompt = prompts.find(p => p.id === selectedPromptId)
    let originalContent = ''
    
    if (selectedVersionId && selectedPrompt) {
      const version = selectedPrompt.versions.find(v => v.id === selectedVersionId)
      originalContent = version?.content || ''
    } else if (selectedPrompt) {
      originalContent = selectedPrompt.content
    }
    
    // Only return custom content if it's different from original
    return editablePromptContent !== originalContent ? editablePromptContent : undefined
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 验证必填字段
    if (!selectedModelId || !userInput.trim() || !simulatorName.trim()) {
      return
    }
    
    // 在创建模式下，需要有提示词内容
    if (promptInputMode === 'create' && !editablePromptContent.trim()) {
      return
    }
    
    // 在选择模式下，需要选择提示词
    if (promptInputMode === 'select' && !selectedPromptId) {
      return
    }

    setIsCreating(true)
    try {
      const requestBody: {
        name: string;
        modelId: string;
        userInput: string;
        temperature: number;
        maxTokens?: number;
        topP: number;
        frequencyPenalty: number;
        presencePenalty: number;
        generationMode: GenerationMode;
        createNewPrompt?: boolean;
        newPromptName?: string;
        newPromptContent?: string;
        promptId?: string;
        promptVersionId?: string;
        promptContent?: string;
      } = {
        name: simulatorName,
        modelId: selectedModelId,
        userInput,
        temperature: parseFloat(temperature),
        maxTokens: maxTokens ? parseInt(maxTokens) : undefined,
        topP: parseFloat(topP),
        frequencyPenalty: parseFloat(frequencyPenalty),
        presencePenalty: parseFloat(presencePenalty),
        generationMode,
      }

      if (promptInputMode === 'create') {
        // 创建新提示词模式
        requestBody.createNewPrompt = true
        requestBody.newPromptName = simulatorName.replace(' 模拟运行', '')
        requestBody.newPromptContent = editablePromptContent
      } else {
        // 选择现有提示词模式
        requestBody.promptId = selectedPromptId
        requestBody.promptVersionId = selectedVersionId || undefined
        requestBody.promptContent = getCustomPromptContent()
      }

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

      if (response.ok) {
        const run = await response.json()
        router.push(`/simulator/${run.id}`)
      } else {
        console.error('Error creating run:', await response.text())
      }
    } catch (error) {
      console.error('Error creating run:', error)
    } finally {
      setIsCreating(false)
    }
  }

  if (authLoading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <LoadingSpinner size="lg" />
          <p className="mt-4 text-muted-foreground">Loading...</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return null
  }

  return (
    <div className="min-h-screen">
      <Header />
      
      <div className="container mx-auto px-4 py-8 max-w-4xl">
      {/* Header */}
      <div className="mb-8">
        <div className="flex items-center space-x-4 mb-4">
          <Link href="/simulator">
            <Button variant="outline" size="sm">
              <ArrowLeft className="h-4 w-4 mr-2" />
              {t('backToList')}
            </Button>
          </Link>
        </div>
        <h1 className="text-3xl font-bold text-foreground mb-2">{t('newRun')}</h1>
        <p className="text-muted-foreground">
          {t('newRunDescription')}
        </p>
      </div>

      {isLoading ? (
        <div className="text-center py-12">
          <LoadingSpinner size="lg" />
          <p className="mt-4 text-muted-foreground">Loading data...</p>
        </div>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-6">
          {/* Generation Mode Selection */}
          <Card className="p-6">
            <div className="mb-6">
              <h2 className="text-xl font-semibold mb-2 flex items-center">
                <Settings className="h-5 w-5 mr-2" />
                生成模式
              </h2>
              <p className="text-muted-foreground mb-4">
                选择生成模式：文本生成或图像生成
              </p>
              
              <div className="flex space-x-1 p-1 bg-muted rounded-lg max-w-md">
                <button
                  type="button"
                  className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                    generationMode === 'text'
                      ? 'bg-background text-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                  onClick={() => setGenerationMode('text')}
                >
                  📝 文本生成
                </button>
                <button
                  type="button"
                  className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                    generationMode === 'image'
                      ? 'bg-background text-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                  onClick={() => setGenerationMode('image')}
                >
                  🎨 图像生成
                </button>
              </div>
              
              {generationMode === 'image' && filteredModels.length === 0 && (
                <div className="mt-4 p-3 bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-md">
                  <p className="text-sm text-yellow-800 dark:text-yellow-200">
                    当前没有可用的图像生成模型。支持的模型：{Object.values(SUPPORTED_IMAGE_MODELS).map(m => m.name).join(', ')}
                  </p>
                </div>
              )}
            </div>
          </Card>

          {/* Prompt Configuration */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-xl font-semibold mb-2 flex items-center">
                  <Zap className="h-5 w-5 mr-2" />
                  提示词配置
                </h2>
                <p className="text-muted-foreground">
                  选择现有提示词或直接输入新的提示词内容
                </p>
              </div>
            </div>
            
            {/* 模式切换 */}
            <div className="mb-6">
              <div className="flex space-x-1 p-1 bg-muted rounded-lg">
                <button
                  type="button"
                  className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                    promptInputMode === 'select'
                      ? 'bg-background text-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                  onClick={() => {
                    setPromptInputMode('select')
                    setEditablePromptContent('')
                  }}
                >
                  选择现有提示词
                </button>
                <button
                  type="button"
                  className={`flex-1 px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                    promptInputMode === 'create'
                      ? 'bg-background text-foreground shadow-sm'
                      : 'text-muted-foreground hover:text-foreground'
                  }`}
                  onClick={() => {
                    setPromptInputMode('create')
                    setSelectedPromptId('')
                    setSelectedVersionId('')
                    if (!simulatorName) {
                      setSimulatorName('新模拟运行')
                    }
                  }}
                >
                  直接输入提示词
                </button>
              </div>
            </div>
            
            <div className="space-y-4">
              {promptInputMode === 'select' && (
                <>
                  <div>
                    <Label htmlFor="prompt" className="text-sm font-medium">{t('prompt')}</Label>
                    <select
                      id="prompt"
                      value={selectedPromptId}
                      onChange={(e) => handlePromptChange(e.target.value)}
                      className="w-full mt-1 bg-background border border-input rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-ring"
                      required
                    >
                      <option value="">{t('selectPromptPlaceholder')}</option>
                      {prompts.map(prompt => (
                        <option key={prompt.id} value={prompt.id}>
                          {prompt.name}
                        </option>
                      ))}
                    </select>
                  </div>

                  {selectedPrompt && selectedPrompt.versions.length > 0 && (
                    <div>
                      <Label htmlFor="version" className="text-sm font-medium">{t('version')}</Label>
                      <select
                        id="version"
                        value={selectedVersionId}
                        onChange={(e) => handleVersionChange(e.target.value)}
                        className="w-full mt-1 bg-background border border-input rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-ring"
                      >
                        <option value="">{t('useLatestVersion')}</option>
                        {selectedPrompt.versions
                          .sort((a, b) => b.version - a.version)
                          .map(version => (
                            <option key={version.id} value={version.id}>
                              v{version.version}
                            </option>
                          ))}
                      </select>
                    </div>
                  )}
                </>
              )}
              
              {/* 名称输入框 - 在提示词选择下方 */}
              <div>
                <Label htmlFor="simulatorName" className="text-sm font-medium">运行名称</Label>
                <Input
                  id="simulatorName"
                  type="text"
                  value={simulatorName}
                  onChange={(e) => setSimulatorName(e.target.value)}
                  placeholder="输入模拟运行的名称"
                  className="mt-1"
                  required
                />
                <p className="text-xs text-muted-foreground mt-1">
                  为此次模拟运行设置一个易于识别的名称
                </p>
              </div>
              
              {promptInputMode === 'create' && (
                <div>
                  <p className="text-xs text-muted-foreground mb-2">
                    💡 系统将自动创建一个新的提示词并关联到此模拟运行
                  </p>
                </div>
              )}

              {/* 提示词内容显示/编辑 */}
              {(editablePromptContent || promptInputMode === 'create') && (
                <div>
                  <div className="flex items-center justify-between mb-2">
                    <Label className="text-sm font-medium">
                      {promptInputMode === 'create' ? '提示词内容' : t('promptContent')}
                    </Label>
                    {promptInputMode === 'select' && (
                      <div className="flex items-center space-x-2">
                        {!isEditingPrompt && (
                          <Button
                            type="button"
                            variant="outline"
                            size="sm"
                            onClick={handleEditPrompt}
                          >
                            <Edit className="h-3 w-3 mr-1" />
                            {t('edit')}
                          </Button>
                        )}
                        {isEditingPrompt && (
                          <>
                            <Button
                              type="button"
                              variant="outline"
                              size="sm"
                              onClick={handleCancelPromptEdit}
                            >
                              {t('cancel')}
                            </Button>
                            <Button
                              type="button"
                              variant="default"
                              size="sm"
                              onClick={handleSavePromptEdit}
                            >
                              {t('save')}
                            </Button>
                          </>
                        )}
                      </div>
                    )}
                  </div>
                  
                  {(isEditingPrompt || promptInputMode === 'create') ? (
                    <Textarea
                      value={editablePromptContent}
                      onChange={(e) => setEditablePromptContent(e.target.value)}
                      className="min-h-32 font-mono text-sm"
                      placeholder={promptInputMode === 'create' ? "请输入提示词内容..." : t('promptContentPlaceholder')}
                      required={promptInputMode === 'create'}
                    />
                  ) : (
                    <div className="mt-1 p-4 bg-muted rounded-md border max-h-48 overflow-y-auto">
                      <pre className="text-sm text-foreground whitespace-pre-wrap font-mono">
                        {editablePromptContent}
                      </pre>
                    </div>
                  )}
                  {getCustomPromptContent() && (
                    <p className="text-xs text-muted-foreground mt-2">
                      ⚠️ {t('promptContentModified')}
                    </p>
                  )}
                </div>
              )}
            </div>
          </Card>

          {/* Select Model */}
          <Card className="p-6">
            <div className="flex items-center justify-between mb-6">
              <div>
                <h2 className="text-xl font-semibold mb-2">{t('selectModel')}</h2>
                <p className="text-muted-foreground">
                  {generationMode === 'text' 
                    ? '选择用于文本生成的AI模型' 
                    : '选择用于图像生成的AI模型（仅显示已适配的模型）'
                  }
                </p>
              </div>
            </div>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {filteredModels.map(model => (
                <div
                  key={model.id}
                  className={`border rounded-lg p-4 cursor-pointer transition-all ${
                    selectedModelId === model.id
                      ? 'border-primary bg-primary/5 shadow-sm'
                      : 'border-border hover:border-border/80 hover:bg-accent/50'
                  }`}
                  onClick={() => setSelectedModelId(model.id)}
                >
                  <div className="flex items-center justify-between mb-2">
                    <h3 className="font-semibold text-foreground">{model.name}</h3>
                    <div className="flex items-center space-x-2">
                      <Badge variant="outline" className="text-xs">
                        {model.outputType === 'text' ? '📝' : '🎨'} {model.outputType}
                      </Badge>
                      <Badge variant="outline" className="text-xs">
                        {model.provider}
                      </Badge>
                    </div>
                  </div>
                  {model.description && (
                    <p className="text-sm text-muted-foreground mb-3 line-clamp-2">
                      {model.description}
                    </p>
                  )}
                  <div className="flex items-center space-x-4 text-xs text-muted-foreground">
                    {model.maxTokens && (
                      <span className="flex items-center">
                        <Zap className="h-3 w-3 mr-1" />
                        {model.maxTokens.toLocaleString()} tokens
                      </span>
                    )}
                    {model.inputCostPer1k && (
                      <span className="flex items-center">
                        <DollarSign className="h-3 w-3 mr-1" />
                        ${model.inputCostPer1k}/1K
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>
          </Card>

          {/* User Input */}
          <Card className="p-6">
            <div className="mb-6">
              <h2 className="text-xl font-semibold mb-2">{t('userInput')}</h2>
              <p className="text-muted-foreground">
                Enter the input you want to test with your prompt
              </p>
            </div>
            
            <Textarea
              value={userInput}
              onChange={(e) => setUserInput(e.target.value)}
              placeholder={t('userInputPlaceholder')}
              className="min-h-32 resize-none"
              required
            />
          </Card>

          {/* Advanced Settings */}
          <Card className="p-6">
            <div
              className="flex items-center justify-between cursor-pointer"
              onClick={() => setShowAdvanced(!showAdvanced)}
            >
              <div className="flex items-center">
                <Settings className="h-5 w-5 mr-2" />
                <h2 className="text-xl font-semibold">{t('advancedSettings')}</h2>
              </div>
              {showAdvanced ? (
                <ChevronDown className="h-5 w-5" />
              ) : (
                <ChevronRight className="h-5 w-5" />
              )}
            </div>
            
            {showAdvanced && (
              <div className="mt-6 space-y-4">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="temperature" className="text-sm font-medium">
                        {t('temperature')}: {temperature}
                      </Label>
                      <Input
                        id="temperature"
                        type="number"
                        value={temperature}
                        onChange={(e) => setTemperature(e.target.value)}
                        min="0"
                        max="2"
                        step="0.1"
                        className="mt-1"
                      />
                      <p className="text-xs text-muted-foreground mt-1">
                        {t('temperatureDescription')}
                      </p>
                    </div>

                    <div>
                      <Label htmlFor="topP" className="text-sm font-medium">
                        {t('topP')}: {topP}
                      </Label>
                      <Input
                        id="topP"
                        type="number"
                        value={topP}
                        onChange={(e) => setTopP(e.target.value)}
                        min="0"
                        max="1"
                        step="0.1"
                        className="mt-1"
                      />
                    </div>

                    <div>
                      <Label htmlFor="maxTokens" className="text-sm font-medium">
                        {t('maxTokens')}
                      </Label>
                      <Input
                        id="maxTokens"
                        type="number"
                        value={maxTokens}
                        onChange={(e) => setMaxTokens(e.target.value)}
                        placeholder={selectedModel?.maxTokens?.toString() || "2048"}
                        min="1"
                        max={selectedModel?.maxTokens || 4096}
                        className="mt-1"
                      />
                    </div>
                  </div>

                  <div className="space-y-4">
                    <div>
                      <Label htmlFor="frequencyPenalty" className="text-sm font-medium">
                        {t('frequencyPenalty')}: {frequencyPenalty}
                      </Label>
                      <Input
                        id="frequencyPenalty"
                        type="number"
                        value={frequencyPenalty}
                        onChange={(e) => setFrequencyPenalty(e.target.value)}
                        min="-2"
                        max="2"
                        step="0.1"
                        className="mt-1"
                      />
                    </div>

                    <div>
                      <Label htmlFor="presencePenalty" className="text-sm font-medium">
                        {t('presencePenalty')}: {presencePenalty}
                      </Label>
                      <Input
                        id="presencePenalty"
                        type="number"
                        value={presencePenalty}
                        onChange={(e) => setPresencePenalty(e.target.value)}
                        min="-2"
                        max="2"
                        step="0.1"
                        className="mt-1"
                      />
                    </div>
                  </div>
                </div>
              </div>
            )}
          </Card>

          {/* Submit */}
          <div className="flex items-center justify-end space-x-4">
            <Link href="/simulator">
              <Button type="button" variant="outline">
                {t('cancel')}
              </Button>
            </Link>
            <Button 
              type="submit" 
              disabled={
                isCreating || 
                !selectedModelId || 
                !userInput.trim() || 
                !simulatorName.trim() ||
                (promptInputMode === 'select' && !selectedPromptId) ||
                (promptInputMode === 'create' && !editablePromptContent.trim())
              }
            >
              {isCreating ? (
                <>
                  <LoadingSpinner size="sm" />
                  <span className="ml-2">{t('creating')}</span>
                </>
              ) : (
                <>
                  <Play className="h-4 w-4 mr-2" />
                  {t('createRun')}
                </>
              )}
            </Button>
          </div>
        </form>
      )}
      </div>
      
      <Footer />
    </div>
  )
}