"use client"
import { useCompetition } from "@/contexts/competition-context"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Users, Bot, Trophy, TrendingUp, Eye, Heart, MessageSquare, Award, Activity, Loader2 } from "lucide-react"
import { useState, useEffect } from "react"

interface DashboardStats {
  totalUsers: number
  activeUsers: number
  totalApps: number
  totalCompetitions: number
  totalReviews: number
  totalViews: number
  totalLikes: number
  newAppsThisMonth: number
  activeCompetitions: number
  growthRate: number
}

interface RecentActivity {
  id: string
  type: string
  message: string
  time: string
  icon: string
  color: string
}

interface TopApp {
  id: string
  name: string
  description: string
  views: number
  likes: number
  rating: number
  category: string
  created_at: string
}

interface AdminDashboardProps {
  onPageChange?: (page: string) => void
}

export function AdminDashboard({ onPageChange }: AdminDashboardProps) {
  const { competitions } = useCompetition()
  const [stats, setStats] = useState<DashboardStats>({
    totalUsers: 0,
    activeUsers: 0,
    totalApps: 0,
    totalCompetitions: 0,
    totalReviews: 0,
    totalViews: 0,
    totalLikes: 0,
    newAppsThisMonth: 0,
    activeCompetitions: 0,
    growthRate: 0
  })
  const [recentActivities, setRecentActivities] = useState<RecentActivity[]>([])
  const [topApps, setTopApps] = useState<TopApp[]>([])
  const [isLoading, setIsLoading] = useState(true)

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

  const loadDashboardData = async () => {
    try {
      setIsLoading(true)
      const response = await fetch('/api/admin/dashboard')
      const data = await response.json()
      
      if (data.success) {
        setStats(data.data.stats)
        setRecentActivities(data.data.recentActivities)
        setTopApps(data.data.topApps)
      }
    } catch (error) {
      console.error('載入儀表板數據錯誤:', error)
    } finally {
      setIsLoading(false)
    }
  }

  const getActivityIcon = (iconName: string) => {
    const iconMap: { [key: string]: any } = {
      'Users': Users,
      'Bot': Bot,
      'Trophy': Trophy,
      'Activity': Activity,
      'Eye': Eye,
      'Heart': Heart,
      'MessageSquare': MessageSquare,
      'Award': Award
    }
    return iconMap[iconName] || Activity
  }

  const handleQuickAction = (page: string) => {
    if (onPageChange) {
      onPageChange(page)
    }
  }

  return (
    <div className="space-y-6">
      {/* Welcome Section */}
      <div>
        <h1 className="text-3xl font-bold text-gray-900 mb-2">管理儀表板</h1>
        <p className="text-gray-600">歡迎回到 AI 展示平台管理後台</p>
      </div>

      {/* Stats Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">總用戶數</CardTitle>
            <Users className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center space-x-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                <span className="text-sm">載入中...</span>
              </div>
            ) : (
              <>
                <div className="text-2xl font-bold">{stats.totalUsers}</div>
                <p className="text-xs text-muted-foreground">活躍用戶 {stats.activeUsers} 人</p>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">AI 應用數</CardTitle>
            <Bot className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center space-x-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                <span className="text-sm">載入中...</span>
              </div>
            ) : (
              <>
                <div className="text-2xl font-bold">{stats.totalApps}</div>
                <p className="text-xs text-muted-foreground">本月新增 {stats.newAppsThisMonth} 個應用</p>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">競賽活動</CardTitle>
            <Trophy className="h-4 w-4 text-purple-600" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center space-x-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                <span className="text-sm">載入中...</span>
              </div>
            ) : (
              <>
                <div className="text-2xl font-bold">{stats.totalCompetitions}</div>
                <p className="text-xs text-muted-foreground">{stats.activeCompetitions} 個進行中</p>
              </>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">總瀏覽量</CardTitle>
            <TrendingUp className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center space-x-2">
                <Loader2 className="h-4 w-4 animate-spin" />
                <span className="text-sm">載入中...</span>
              </div>
            ) : (
              <>
                <div className="text-2xl font-bold">{stats.totalViews.toLocaleString()}</div>
                <p className="text-xs text-muted-foreground">
                  {stats.growthRate > 0 ? `比上月增長 ${stats.growthRate}%` : '與上月持平'}
                </p>
              </>
            )}
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Recent Activities */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Activity className="w-5 h-5" />
              <span>最新活動</span>
            </CardTitle>
            <CardDescription>系統最新動態</CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin" />
                <span className="ml-2">載入中...</span>
              </div>
            ) : recentActivities.length > 0 ? (
              <div className="space-y-4">
                {recentActivities.map((activity) => {
                  const IconComponent = getActivityIcon(activity.icon)
                  return (
                    <div key={activity.id} className="flex items-center space-x-3">
                      <div className={`p-2 rounded-full bg-gray-100 ${activity.color}`}>
                        <IconComponent className="w-4 h-4" />
                      </div>
                      <div className="flex-1">
                        <p className="text-sm font-medium">{activity.message}</p>
                        <p className="text-xs text-gray-500">{activity.time}</p>
                      </div>
                    </div>
                  )
                })}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Activity className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>暫無最新活動</p>
              </div>
            )}
          </CardContent>
        </Card>

        {/* Top Performing Apps */}
        <Card>
          <CardHeader>
            <CardTitle className="flex items-center space-x-2">
              <Award className="w-5 h-5" />
              <span>熱門應用</span>
            </CardTitle>
            <CardDescription>表現最佳的 AI 應用</CardDescription>
          </CardHeader>
          <CardContent>
            {isLoading ? (
              <div className="flex items-center justify-center py-8">
                <Loader2 className="h-6 w-6 animate-spin" />
                <span className="ml-2">載入中...</span>
              </div>
            ) : topApps.length > 0 ? (
              <div className="space-y-4">
                {topApps.map((app, index) => (
                  <div key={app.id} className="flex items-center justify-between">
                    <div className="flex-1">
                      <p className="font-medium">{app.name}</p>
                      <p className="text-xs text-gray-500 mb-1">{app.description}</p>
                      <div className="flex items-center space-x-4 text-sm text-gray-500">
                        <div className="flex items-center space-x-1">
                          <Eye className="w-3 h-3" />
                          <span>{app.views}</span>
                        </div>
                        <div className="flex items-center space-x-1">
                          <Heart className="w-3 h-3" />
                          <span>{app.likes}</span>
                        </div>
                        <div className="text-xs text-gray-400">
                          {app.category}
                        </div>
                      </div>
                    </div>
                    <Badge variant="secondary">{app.rating} ⭐</Badge>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-8 text-gray-500">
                <Award className="w-8 h-8 mx-auto mb-2 opacity-50" />
                <p>暫無應用數據</p>
              </div>
            )}
          </CardContent>
        </Card>
      </div>

      {/* Quick Actions */}
      <Card>
        <CardHeader>
          <CardTitle>快速操作</CardTitle>
          <CardDescription>常用管理功能</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
            <Button 
              className="h-20 flex flex-col space-y-2"
              onClick={() => handleQuickAction('users')}
            >
              <Users className="w-6 h-6" />
              <span>管理用戶</span>
            </Button>
            <Button 
              className="h-20 flex flex-col space-y-2 bg-transparent" 
              variant="outline"
              onClick={() => handleQuickAction('apps')}
            >
              <Bot className="w-6 h-6" />
              <span>新增應用</span>
            </Button>
            <Button 
              className="h-20 flex flex-col space-y-2 bg-transparent" 
              variant="outline"
              onClick={() => handleQuickAction('competitions')}
            >
              <Trophy className="w-6 h-6" />
              <span>創建競賽</span>
            </Button>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}
