'use client'

import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { LoadingSpinner } from '@/components/ui/loading-spinner'
import { Badge } from '@/components/ui/badge'
import { 
  RefreshCw, 
  Database, 
  Plus,
  DollarSign,
  Cpu,
  Zap,
  Trash2,
  Eye,
  EyeOff,
  Search,
  CheckCircle2,
  Globe
} from 'lucide-react'

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>
  customLimits?: Record<string, unknown>
  isActive: boolean
  createdAt: string
  updatedAt: string
}

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

export default function AdminModelsPage() {
  const [models, setModels] = useState<Model[]>([])
  const [availableModels, setAvailableModels] = useState<AvailableModel[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [isFetching, setIsFetching] = useState(false)
  const [isAdding, setIsAdding] = useState(false)
  const [selectedModels, setSelectedModels] = useState<string[]>([])
  const [showAvailableModels, setShowAvailableModels] = useState(false)
  const [selectedServiceProvider, setSelectedServiceProvider] = useState<'openrouter' | 'replicate' | 'uniapi' | 'fal'>('openrouter')
  const [searchTerm, setSearchTerm] = useState('')
  const [filterProvider, setFilterProvider] = useState('')
  const [filterOutputType, setFilterOutputType] = useState('')

  useEffect(() => {
    loadInitialData()
  }, [])

  const loadInitialData = async () => {
    try {
      setIsLoading(true)
      
      const response = await fetch('/api/admin/models')
      if (response.ok) {
        const data = await response.json()
        setModels(data.models || [])
      }
    } catch (error) {
      console.error('Error loading models:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const fetchModelsFromProvider = async () => {
    try {
      setIsFetching(true)

      const response = await fetch('/api/admin/models', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'sync',
          serviceProvider: selectedServiceProvider
        })
      })

      if (response.ok) {
        const result = await response.json()
        setAvailableModels(result.availableModels || [])
        setShowAvailableModels(true)
        setSelectedModels([])
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error fetching models:', error)
      alert(`Failed to fetch models from ${selectedServiceProvider}`)
    } finally {
      setIsFetching(false)
    }
  }

  const addSelectedModels = async () => {
    if (selectedModels.length === 0) {
      alert('Please select models to add')
      return
    }

    try {
      setIsAdding(true)
      
      const selectedModelData = availableModels.filter(model => 
        selectedModels.includes(model.modelId)
      )
      
      const response = await fetch('/api/admin/models', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'add',
          selectedModels: selectedModelData
        })
      })

      if (response.ok) {
        const result = await response.json()
        await loadInitialData() // 重新加载数据
        setShowAvailableModels(false)
        setSelectedModels([])
        alert(`Successfully added ${result.models?.length || 0} models`)
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error adding models:', error)
      alert('Failed to add models')
    } finally {
      setIsAdding(false)
    }
  }

  const toggleModelStatus = async (modelId: string, currentStatus: boolean) => {
    try {
      const response = await fetch('/api/admin/models', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          modelId,
          isActive: !currentStatus
        })
      })

      if (response.ok) {
        await loadInitialData()
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error updating model status:', error)
      alert('Failed to update model status')
    }
  }

  const removeModel = async (modelId: string) => {
    if (!confirm('Are you sure you want to remove this model?')) {
      return
    }

    try {
      const response = await fetch(`/api/admin/models?id=${modelId}`, {
        method: 'DELETE'
      })

      if (response.ok) {
        await loadInitialData()
      } else {
        const error = await response.json()
        alert(`Error: ${error.error}`)
      }
    } catch (error) {
      console.error('Error removing model:', error)
      alert('Failed to remove model')
    }
  }

  const toggleModelSelection = (modelId: string) => {
    setSelectedModels(prev => 
      prev.includes(modelId) 
        ? prev.filter(id => id !== modelId)
        : [...prev, modelId]
    )
  }

  // 过滤和搜索逻辑
  const filteredModels = models.filter(model => {
    const matchesSearch = searchTerm === '' || 
      model.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      model.modelId.toLowerCase().includes(searchTerm.toLowerCase()) ||
      model.provider.toLowerCase().includes(searchTerm.toLowerCase())
    
    const matchesProvider = filterProvider === '' || model.provider === filterProvider
    const matchesOutputType = filterOutputType === '' || model.outputType === filterOutputType
    
    return matchesSearch && matchesProvider && matchesOutputType
  })

  // 获取所有可用的提供商和输出类型用于过滤器
  const allProviders = [...new Set(models.map(m => m.provider))].sort()
  const allOutputTypes = [...new Set(models.map(m => m.outputType))].sort()
  const serviceProviders = [...new Set(models.map(m => m.serviceProvider))].sort()

  // 统计信息
  const stats = {
    total: models.length,
    active: models.filter(m => m.isActive).length,
    inactive: models.filter(m => !m.isActive).length,
    byProvider: allProviders.reduce((acc, provider) => {
      acc[provider] = models.filter(m => m.provider === provider).length
      return acc
    }, {} as Record<string, number>),
    byServiceProvider: serviceProviders.reduce((acc, sp) => {
      acc[sp] = models.filter(m => m.serviceProvider === sp).length
      return acc
    }, {} as Record<string, number>)
  }

  if (isLoading) {
    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 AI models...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="container mx-auto px-4 py-8 max-w-7xl">
      {/* Header */}
      <div className="mb-8">
        <h1 className="text-3xl font-bold text-foreground mb-2">AI Models Management</h1>
        <p className="text-muted-foreground">
          Manage AI models across all subscription plans. All models are globally available with different cost multipliers.
        </p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total Models</CardTitle>
            <Database className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{stats.total}</div>
            <p className="text-xs text-muted-foreground">All configured models</p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Active Models</CardTitle>
            <CheckCircle2 className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">{stats.active}</div>
            <p className="text-xs text-muted-foreground">Currently available</p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Service Providers</CardTitle>
            <Globe className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{serviceProviders.length}</div>
            <p className="text-xs text-muted-foreground">Connected services</p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Model Providers</CardTitle>
            <Cpu className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{allProviders.length}</div>
            <p className="text-xs text-muted-foreground">Different AI providers</p>
          </CardContent>
        </Card>
      </div>

      {/* Add Models Section */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Plus className="h-5 w-5" />
            Add New Models
          </CardTitle>
          <CardDescription>
            Sync and add new AI models from supported service providers. All models will be available globally.
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* Service Provider Selection */}
          <div>
            <label className="block text-sm font-medium mb-2">Service Provider</label>
            <select
              value={selectedServiceProvider}
              onChange={(e) => {
                setSelectedServiceProvider(e.target.value as 'openrouter' | 'replicate' | 'uniapi' | 'fal')
                setShowAvailableModels(false)
                setSelectedModels([])
              }}
              className="w-full md:w-80 bg-background border border-input rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-ring"
            >
              <option value="openrouter">OpenRouter (Text & Chat Models)</option>
              <option value="replicate">Replicate (Image/Video/Audio Models)</option>
              <option value="uniapi">UniAPI (Multi-modal Models)</option>
              <option value="fal">Fal.ai (AI Generation Models)</option>
            </select>
          </div>

          {/* Fetch Models Button */}
          <div className="flex items-center space-x-4">
            <Button
              onClick={fetchModelsFromProvider}
              disabled={isFetching}
              className="flex items-center space-x-2"
            >
              <RefreshCw className={`h-4 w-4 ${isFetching ? 'animate-spin' : ''}`} />
              <span>{isFetching ? `Syncing ${selectedServiceProvider} models...` : `Fetch ${selectedServiceProvider} models`}</span>
            </Button>
            
            {showAvailableModels && (
              <div className="text-sm text-muted-foreground">
                {availableModels.length} models available • {selectedModels.length} selected
              </div>
            )}
          </div>

          {/* Available Models Selection */}
          {showAvailableModels && availableModels.length > 0 && (
            <div className="border border-border rounded-lg p-4">
              <div className="flex items-center justify-between mb-4">
                <h3 className="font-medium">Available Models ({availableModels.length})</h3>
                <Button
                  onClick={addSelectedModels}
                  disabled={selectedModels.length === 0 || isAdding}
                  size="sm"
                >
                  {isAdding ? (
                    <>
                      <LoadingSpinner size="sm" />
                      <span className="ml-2">Adding models...</span>
                    </>
                  ) : (
                    `Add Selected (${selectedModels.length})`
                  )}
                </Button>
              </div>
              
              <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 max-h-96 overflow-y-auto">
                {availableModels.map(model => {
                  const isSelected = selectedModels.includes(model.modelId)
                  const isAlreadyAdded = models.some(m => m.modelId === model.modelId)
                  
                  return (
                    <div
                      key={model.modelId}
                      className={`border rounded-lg p-4 cursor-pointer transition-all hover:shadow-sm ${
                        isAlreadyAdded 
                          ? 'border-yellow-300 bg-yellow-50 dark:bg-yellow-900/20' 
                          : isSelected 
                            ? 'border-primary bg-primary/5 shadow-sm' 
                            : 'border-border hover:bg-accent'
                      }`}
                      onClick={() => !isAlreadyAdded && toggleModelSelection(model.modelId)}
                    >
                      <div className="flex items-start justify-between">
                        <div className="flex-1 min-w-0">
                          <div className="mb-2">
                            <h4 className="font-medium text-sm truncate mb-2">{model.name || model.modelId}</h4>
                            <div className="flex flex-wrap gap-1">
                              <Badge variant="secondary" className="text-xs">
                                {model.provider}
                              </Badge>
                              <Badge variant="outline" className="text-xs">
                                {model.outputType}
                              </Badge>
                            </div>
                          </div>
                          <div className="flex items-center space-x-2 text-xs text-muted-foreground">
                            {model.maxTokens && (
                              <span className="flex items-center">
                                <Zap className="h-3 w-3 mr-1" />
                                {model.maxTokens.toLocaleString()}
                              </span>
                            )}
                            {model.inputCostPer1k && (
                              <span className="flex items-center">
                                <DollarSign className="h-3 w-3 mr-1" />
                                ${model.inputCostPer1k.toFixed(4)}
                              </span>
                            )}
                          </div>
                          {isAlreadyAdded && (
                            <div className="flex items-center mt-2 text-xs text-yellow-600 dark:text-yellow-400">
                              <CheckCircle2 className="h-3 w-3 mr-1" />
                              Already added
                            </div>
                          )}
                        </div>
                        
                        {!isAlreadyAdded && (
                          <input
                            type="checkbox"
                            checked={isSelected}
                            onChange={(e) => e.stopPropagation()}
                            className="h-4 w-4 text-primary focus:ring-primary border-input rounded"
                          />
                        )}
                      </div>
                    </div>
                  )
                })}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
      

      {/* Current Models List */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Database className="h-5 w-5" />
                Configured Models ({filteredModels.length})
              </CardTitle>
              <CardDescription>
                All AI models available across subscription plans with different cost multipliers
              </CardDescription>
            </div>
          </div>
          
          {/* Search and Filter Controls */}
          <div className="flex flex-col sm:flex-row gap-4 mt-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
              <input
                type="text"
                placeholder="Search models, providers, or IDs..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 bg-background border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring"
              />
            </div>
            
            <div className="flex gap-2">
              <select
                value={filterProvider}
                onChange={(e) => setFilterProvider(e.target.value)}
                className="bg-background border border-input rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-ring"
              >
                <option value="">All Providers</option>
                {allProviders.map(provider => (
                  <option key={provider} value={provider}>{provider}</option>
                ))}
              </select>
              
              <select
                value={filterOutputType}
                onChange={(e) => setFilterOutputType(e.target.value)}
                className="bg-background border border-input rounded-md px-3 py-2 focus:outline-none focus:ring-2 focus:ring-ring"
              >
                <option value="">All Types</option>
                {allOutputTypes.map(type => (
                  <option key={type} value={type}>{type}</option>
                ))}
              </select>
            </div>
          </div>
        </CardHeader>
        
        <CardContent>
          {filteredModels.length === 0 ? (
            <div className="text-center py-12">
              <Database className="h-16 w-16 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-semibold mb-2">No models found</h3>
              <p className="text-muted-foreground mb-4">
                {searchTerm || filterProvider || filterOutputType 
                  ? 'Try adjusting your search or filter criteria'
                  : 'Start by adding some models from the section above'
                }
              </p>
            </div>
          ) : (
            <div className="space-y-3">
              {filteredModels.map(model => (
                <div 
                  key={model.id} 
                  className="border border-border rounded-lg p-4 hover:shadow-sm transition-shadow"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex-1">
                      <div className="flex items-center space-x-3 mb-2">
                        <h3 className="font-semibold text-foreground">{model.name}</h3>
                        <Badge variant="secondary" className="text-xs">
                          {model.provider}
                        </Badge>
                        <Badge variant="outline" className="text-xs">
                          {model.outputType}
                        </Badge>
                        <Badge variant="outline" className="text-xs">
                          {model.serviceProvider}
                        </Badge>
                        <Badge
                          variant={model.isActive ? "default" : "outline"}
                          className={`text-xs ${model.isActive ? 'bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400' : ''}`}
                        >
                          {model.isActive ? 'Active' : 'Inactive'}
                        </Badge>
                      </div>
                      
                      <div className="flex items-center space-x-4 text-sm text-muted-foreground">
                        <span className="flex items-center">
                          <Cpu className="h-3 w-3 mr-1" />
                          {model.modelId}
                        </span>
                        {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.toFixed(6)}/1K in
                          </span>
                        )}
                        {model.outputCostPer1k && (
                          <span className="flex items-center">
                            <DollarSign className="h-3 w-3 mr-1" />
                            ${model.outputCostPer1k.toFixed(6)}/1K out
                          </span>
                        )}
                      </div>
                      
                      {model.description && (
                        <p className="text-sm text-muted-foreground mt-2 line-clamp-2">
                          {model.description}
                        </p>
                      )}
                    </div>
                    
                    <div className="flex items-center space-x-2 ml-4">
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => toggleModelStatus(model.id, model.isActive)}
                        title={model.isActive ? 'Disable model' : 'Enable model'}
                      >
                        {model.isActive ? (
                          <EyeOff className="h-4 w-4" />
                        ) : (
                          <Eye className="h-4 w-4" />
                        )}
                      </Button>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => removeModel(model.id)}
                        className="text-red-600 hover:text-red-700 hover:border-red-200"
                        title="Remove model"
                      >
                        <Trash2 className="h-4 w-4" />
                      </Button>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  )
}