'use client'

import { useState, useEffect, useCallback, useMemo } from 'react'
import { useTranslations } from 'next-intl'
import { useAuthUser } from '@/hooks/useAuthUser'
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 { 
  Play, 
  Database, 
  Plus,
  Clock,
  CheckCircle2,
  XCircle,
  AlertCircle,
  Eye,
  RefreshCw,
  Zap,
  DollarSign,
  Copy,
  BarChart3
} from 'lucide-react'
import Link from 'next/link'
import { formatDistanceToNow } from 'date-fns'
import { zhCN, enUS } from 'date-fns/locale'
import { useLocale } from 'next-intl'

interface SimulatorRun {
  id: string
  name: string
  status: string
  userInput: string
  output?: string
  error?: string
  createdAt: string
  completedAt?: string
  prompt: {
    id: string
    name: string
  }
  model: {
    id: string
    name: string
    provider: string
  }
  inputTokens?: number
  outputTokens?: number
  totalCost?: number
  duration?: number
}

interface PaginationInfo {
  page: number
  limit: number
  total: number
  totalPages: number
}

export default function SimulatorPage() {
  const { user, loading: authLoading } = useAuthUser()
  const t = useTranslations('simulator')
  const locale = useLocale()
  
  const [runs, setRuns] = useState<SimulatorRun[]>([])
  const [pagination, setPagination] = useState<PaginationInfo>({
    page: 1,
    limit: 20,
    total: 0,
    totalPages: 0
  })
  const [isLoading, setIsLoading] = useState(true)
  const [statusFilter, setStatusFilter] = useState<string>('')
  const [duplicatingRunId, setDuplicatingRunId] = useState<string | null>(null)
  
  const fetchRuns = useCallback(async () => {
    try {
      setIsLoading(true)
      const params = new URLSearchParams({
        page: pagination.page.toString(),
        limit: pagination.limit.toString(),
        ...(statusFilter && { status: statusFilter })
      })
      
      const response = await fetch(`/api/simulator?${params}`)
      if (response.ok) {
        const data = await response.json()
        setRuns(data.runs)
        setPagination(data.pagination)
      }
    } catch (error) {
      console.error('Error fetching simulator runs:', error)
    } finally {
      setIsLoading(false)
    }
  }, [pagination.page, pagination.limit, statusFilter])

  useEffect(() => {
    if (!authLoading && user) {
      fetchRuns()
    }
  }, [user, authLoading, pagination.page, statusFilter, fetchRuns])

  const handleDuplicateRun = async (runId: string) => {
    if (!confirm(t('duplicateRunConfirm'))) {
      return
    }

    setDuplicatingRunId(runId)
    try {
      const response = await fetch(`/api/simulator/${runId}/duplicate`, {
        method: 'POST',
      })

      if (response.ok) {
        // 刷新列表
        await fetchRuns()
        // 可以添加一个成功提示
        console.log(t('duplicateRunSuccess'))
      } else {
        console.error('Error duplicating run:', await response.text())
      }
    } catch (error) {
      console.error('Error duplicating run:', error)
    } finally {
      setDuplicatingRunId(null)
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'pending':
        return <Clock className="h-4 w-4" />
      case 'running':
        return <RefreshCw className="h-4 w-4 animate-spin" />
      case 'completed':
        return <CheckCircle2 className="h-4 w-4" />
      case 'failed':
        return <XCircle className="h-4 w-4" />
      default:
        return <Clock className="h-4 w-4" />
    }
  }

  const getStatusColor = (status: string) => {
    switch (status) {
      case 'pending':
        return 'bg-yellow-50 text-yellow-700 border-yellow-200 dark:bg-yellow-900/20 dark:text-yellow-400 dark:border-yellow-800'
      case 'running':
        return 'bg-blue-50 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-400 dark:border-blue-800'
      case 'completed':
        return 'bg-green-50 text-green-700 border-green-200 dark:bg-green-900/20 dark:text-green-400 dark:border-green-800'
      case 'failed':
        return 'bg-red-50 text-red-700 border-red-200 dark:bg-red-900/20 dark:text-red-400 dark:border-red-800'
      default:
        return 'bg-gray-50 text-gray-700 border-gray-200 dark:bg-gray-900/20 dark:text-gray-400 dark:border-gray-800'
    }
  }

  const stats = useMemo(() => {
    const total = runs.length
    const completed = runs.filter(run => run.status === 'completed').length
    const running = runs.filter(run => run.status === 'running').length
    const failed = runs.filter(run => run.status === 'failed').length
    
    // Calculate total tokens and cost
    const totalInputTokens = runs.reduce((sum, run) => sum + (run.inputTokens || 0), 0)
    const totalOutputTokens = runs.reduce((sum, run) => sum + (run.outputTokens || 0), 0)
    const totalTokens = totalInputTokens + totalOutputTokens
    const totalCost = runs.reduce((sum, run) => sum + (run.totalCost || 0), 0)
    
    return { total, completed, running, failed, totalTokens, totalCost }
  }, [runs])

  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">{t('loadingRuns')}</p>
        </div>
      </div>
    )
  }

  if (!user) {
    return null
  }


  return (
    <div className="min-h-screen">
      <Header />
      
      <div className="container mx-auto px-4 sm:px-6 py-6 sm:py-8 max-w-7xl">
      {/* Header */}
      <div className="mb-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4 sm:gap-0">
          <div className="min-w-0">
            <h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-2">{t('title')}</h1>
            <p className="text-muted-foreground text-sm sm:text-base">
              {t('description')}
            </p>
          </div>
          <Link href="/simulator/new" className="self-start sm:self-auto">
            <Button className="flex items-center space-x-2 w-full sm:w-auto">
              <Plus className="h-4 w-4 flex-shrink-0" />
              <span>{t('newRun')}</span>
            </Button>
          </Link>
        </div>

        {/* Stats */}
        {runs.length > 0 && (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 sm:gap-4 mt-6">
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <Database className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold">{stats.total}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('allRuns')}</div>
                </div>
              </div>
            </Card>
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <CheckCircle2 className="h-4 w-4 text-green-500 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold">{stats.completed}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('completed')}</div>
                </div>
              </div>
            </Card>
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <RefreshCw className="h-4 w-4 text-blue-500 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold">{stats.running}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('running')}</div>
                </div>
              </div>
            </Card>
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <XCircle className="h-4 w-4 text-red-500 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold">{stats.failed}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('failed')}</div>
                </div>
              </div>
            </Card>
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <BarChart3 className="h-4 w-4 text-purple-500 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold truncate">{stats.totalTokens.toLocaleString()}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('totalTokens')}</div>
                </div>
              </div>
            </Card>
            <Card className="p-3 sm:p-4">
              <div className="flex items-center space-x-2">
                <DollarSign className="h-4 w-4 text-green-600 flex-shrink-0" />
                <div className="min-w-0">
                  <div className="text-lg sm:text-2xl font-bold truncate">${stats.totalCost.toFixed(4)}</div>
                  <div className="text-xs text-muted-foreground truncate">{t('totalCost')}</div>
                </div>
              </div>
            </Card>
          </div>
        )}
      </div>

      {/* Filters */}
      <Card className="p-4 sm:p-6 mb-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0 mb-4">
          <h2 className="text-lg font-semibold">Filter Runs</h2>
          <Button
            variant="outline"
            size="sm"
            className="self-start sm:self-auto"
            onClick={() => {
              setStatusFilter('')
              setPagination(prev => ({ ...prev, page: 1 }))
            }}
          >
            Clear Filters
          </Button>
        </div>
        <div className="flex flex-wrap gap-2">
          <Button
            variant={statusFilter === '' ? 'default' : 'outline'}
            size="sm"
            onClick={() => {
              setStatusFilter('')
              setPagination(prev => ({ ...prev, page: 1 }))
            }}
          >
            {t('allRuns')}
          </Button>
          <Button
            variant={statusFilter === 'completed' ? 'default' : 'outline'}
            size="sm"
            onClick={() => {
              setStatusFilter('completed')
              setPagination(prev => ({ ...prev, page: 1 }))
            }}
          >
            {t('completed')}
          </Button>
          <Button
            variant={statusFilter === 'running' ? 'default' : 'outline'}
            size="sm"
            onClick={() => {
              setStatusFilter('running')
              setPagination(prev => ({ ...prev, page: 1 }))
            }}
          >
            {t('running')}
          </Button>
          <Button
            variant={statusFilter === 'failed' ? 'default' : 'outline'}
            size="sm"
            onClick={() => {
              setStatusFilter('failed')
              setPagination(prev => ({ ...prev, page: 1 }))
            }}
          >
            {t('failed')}
          </Button>
        </div>
      </Card>

      {/* Runs List */}
      <Card className="p-4 sm:p-6">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-0 mb-6">
          <div>
            <h2 className="text-xl font-semibold text-foreground">
              Simulation Runs
            </h2>
            <p className="text-sm text-muted-foreground">
              {pagination.total} runs total
            </p>
          </div>
        </div>
        
        {isLoading ? (
          <div className="text-center py-8">
            <LoadingSpinner size="lg" />
            <p className="mt-4 text-muted-foreground">{t('loadingRuns')}</p>
          </div>
        ) : runs.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 text-foreground mb-2">{t('noRuns')}</h3>
            <p className="text-muted-foreground mb-6">
              {t('noRunsDescription')}
            </p>
            <Link href="/simulator/new">
              <Button>
                <Play className="h-4 w-4 mr-2" />
                {t('createFirstRun')}
              </Button>
            </Link>
          </div>
        ) : (
          <div className="space-y-4">
            {runs.map(run => (
              <div 
                key={run.id} 
                className="border border-border rounded-lg p-4 sm:p-6 hover:shadow-md transition-shadow"
              >
                <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 lg:gap-6">
                  <div className="flex-1 min-w-0">
                    <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-3 mb-3">
                      <h3 className="font-semibold text-foreground truncate">{run.name}</h3>
                      <Badge className={`border ${getStatusColor(run.status)} self-start sm:self-auto`}>
                        <div className="flex items-center space-x-1">
                          {getStatusIcon(run.status)}
                          <span className="whitespace-nowrap">{t(`status.${run.status}`)}</span>
                        </div>
                      </Badge>
                    </div>
                    
                    <div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-sm text-muted-foreground mb-3">
                      <span className="flex items-center">
                        <Zap className="h-3 w-3 mr-1 flex-shrink-0" />
                        <span className="truncate">{run.model.provider} {run.model.name}</span>
                      </span>
                      <span className="truncate">
                        {formatDistanceToNow(new Date(run.createdAt), {
                          addSuffix: true,
                          locale: locale === 'zh' ? zhCN : enUS
                        })}
                      </span>
                      {run.inputTokens && run.outputTokens && (
                        <span className="whitespace-nowrap">
                          {(run.inputTokens + run.outputTokens).toLocaleString()} tokens
                        </span>
                      )}
                      {run.totalCost && (
                        <span className="flex items-center whitespace-nowrap">
                          <DollarSign className="h-3 w-3 mr-1 flex-shrink-0" />
                          ${run.totalCost.toFixed(4)}
                        </span>
                      )}
                    </div>
                    
                    <div className="space-y-3">
                      <div className="min-w-0">
                        <h4 className="text-sm font-medium text-foreground mb-1">
                          {t('userInput')}
                        </h4>
                        <div className="text-sm text-muted-foreground bg-muted/50 rounded-md p-2 border">
                          <p className="line-clamp-2 break-words overflow-hidden">
                            {run.userInput.length > 100 ? `${run.userInput.substring(0, 100)}...` : run.userInput}
                          </p>
                        </div>
                      </div>
                      
                      {run.output && (
                        <div className="min-w-0">
                          <h4 className="text-sm font-medium text-foreground mb-1">
                            {t('output')}
                          </h4>
                          <div className="text-sm text-muted-foreground bg-muted/50 rounded-md p-2 border">
                            <p className="line-clamp-3 break-words overflow-hidden">
                              {run.output.length > 150 ? `${run.output.substring(0, 150)}...` : run.output}
                            </p>
                          </div>
                        </div>
                      )}
                      
                      {run.error && (
                        <div className="min-w-0">
                          <h4 className="text-sm font-medium text-red-600 dark:text-red-400 mb-1 flex items-center">
                            <AlertCircle className="h-4 w-4 mr-1 flex-shrink-0" />
                            {t('error')}
                          </h4>
                          <div className="text-sm text-red-600 dark:text-red-400 bg-red-50 dark:bg-red-950/30 rounded-md p-2 border border-red-200 dark:border-red-800">
                            <p className="line-clamp-2 break-words overflow-hidden">
                              {run.error.length > 120 ? `${run.error.substring(0, 120)}...` : run.error}
                            </p>
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                  
                  <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:gap-2 lg:ml-6 mt-4 lg:mt-0">
                    <Button
                      size="sm"
                      variant="outline"
                      className="w-full sm:w-auto"
                      onClick={() => handleDuplicateRun(run.id)}
                      disabled={duplicatingRunId === run.id}
                    >
                      {duplicatingRunId === run.id ? (
                        <LoadingSpinner size="sm" />
                      ) : (
                        <Copy className="h-4 w-4 mr-1 flex-shrink-0" />
                      )}
                      <span className="truncate">{t('duplicateRun')}</span>
                    </Button>
                    <Link href={`/simulator/${run.id}`} className="w-full sm:w-auto">
                      <Button size="sm" variant="outline" className="w-full">
                        <Eye className="h-4 w-4 mr-1 flex-shrink-0" />
                        <span className="truncate">{t('viewDetails')}</span>
                      </Button>
                    </Link>
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>

      {/* Pagination */}
      {pagination.totalPages > 1 && (
        <div className="flex flex-wrap items-center justify-center gap-2 mt-8 px-4">
          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page <= 1}
            onClick={() => setPagination(prev => ({ ...prev, page: prev.page - 1 }))}
            className="min-w-0"
          >
            <span className="hidden sm:inline">{t('previous')}</span>
            <span className="sm:hidden">‹</span>
          </Button>
          
          <div className="flex items-center gap-1">
            {[...Array(Math.min(5, pagination.totalPages))].map((_, i) => {
              const page = Math.max(1, Math.min(pagination.totalPages - 4, pagination.page - 2)) + i
              if (page > pagination.totalPages) return null
              return (
                <Button
                  key={page}
                  size="sm"
                  variant={pagination.page === page ? 'default' : 'outline'}
                  onClick={() => setPagination(prev => ({ ...prev, page }))}
                  className="min-w-[2.5rem] px-2"
                >
                  {page}
                </Button>
              )
            })}
          </div>
          
          <Button
            variant="outline"
            size="sm"
            disabled={pagination.page >= pagination.totalPages}
            onClick={() => setPagination(prev => ({ ...prev, page: prev.page + 1 }))}
            className="min-w-0"
          >
            <span className="hidden sm:inline">{t('next')}</span>
            <span className="sm:hidden">›</span>
          </Button>
        </div>
      )}
      </div>
      
      <Footer />
    </div>
  )
}