'use client';

import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api/apiClient';
import {
  PageContainer,
  PageHeader,
} from '@/components/admin/common';
import { StatsCards } from '@/components/admin/dashboard/StatsCards';
import { ActivityChart } from '@/components/admin/dashboard/ActivityChart';
import { RecentActivity } from '@/components/admin/dashboard/RecentActivity';

// Frontend interfaces (apiClient automatically converts snake_case to camelCase)
interface DashboardStats {
  totalUsers: number;
  totalProjects: number;
  totalTasks: number;
  activeTasks: number;
  pendingTasks: number;
  failedTasks: number;
  completedTasks: number;
}

interface ActivityDataPoint {
  date: string;
  users: number;
  projects: number;
  tasks: number;
}

// Backend API response format (after apiClient camelCase conversion)
interface BackendActivityItem {
  id: string;
  type: string;  // "user", "project", "task"
  action: string;  // "created", "status_changed"
  userId?: string;
  userName?: string;
  targetId?: string;
  targetType?: string;
  details?: Record<string, any>;
  createdAt: string;
}

// Frontend display format
interface ActivityItem {
  id: string;
  type: 'user_created' | 'project_created' | 'task_completed' | 'generation_started' | 'system' | 'error';
  title: string;
  description?: string;
  timestamp: string;
  user?: {
    id: string;
    username: string;
  };
}

interface DashboardData {
  stats: DashboardStats;
  activityData: ActivityDataPoint[];
  recentActivities: ActivityItem[];
}

interface ApiResponse<T> {
  code?: string;
  message?: string;
  data?: T;
}

async function fetchDashboardStats(): Promise<DashboardStats> {
  const response = await api.get<ApiResponse<DashboardStats>>('/api/v1/admin/dashboard/stats');
  const data = response.data?.data ?? response.data;
  if (!data || typeof data !== 'object') {
    throw new Error('Invalid stats response');
  }
  return data as DashboardStats;
}

async function fetchDashboardActivity(): Promise<Pick<DashboardData, 'activityData' | 'recentActivities'>> {
  const response = await api.get<ApiResponse<Pick<DashboardData, 'activityData' | 'recentActivities'>>>('/api/v1/admin/dashboard/activity');
  const data = response.data?.data ?? response.data;
  if (!data || typeof data !== 'object') {
    throw new Error('Invalid activity response');
  }

  // Transform backend activity items to frontend format
  const backendItems = ((data as any).items || []) as BackendActivityItem[];
  const transformedActivities: ActivityItem[] = backendItems.map((item: BackendActivityItem) => {
    // Map backend type+action to frontend type
    let frontendType: ActivityItem['type'] = 'system';
    let title = '';
    let description = '';

    if (item.type === 'user' && item.action === 'created') {
      frontendType = 'user_created';
      title = '新用户注册';
      description = item.userName || item.details?.email || '未知用户';
    } else if (item.type === 'project' && item.action === 'created') {
      frontendType = 'project_created';
      title = '新项目创建';
      description = item.details?.name || '未知项目';
    } else if (item.type === 'task') {
      if (item.details?.status === 'completed') {
        frontendType = 'task_completed';
        title = '任务完成';
        description = `类型：${item.details?.type || '未知'}`;
      } else {
        frontendType = 'generation_started';
        title = '生成任务开始';
        description = `类型：${item.details?.type || '未知'}, 状态：${item.details?.status || 'pending'}`;
      }
    } else if (item.type === 'system') {
      frontendType = 'system';
      title = '系统事件';
      description = item.details?.message || '';
    } else if (item.type === 'error') {
      frontendType = 'error';
      title = '错误事件';
      description = item.details?.error || '';
    }

    return {
      id: item.id,
      type: frontendType,
      title,
      description,
      timestamp: item.createdAt,
      user: item.userId ? {
        id: item.userId,
        username: item.userName || '未知用户',
      } : undefined,
    };
  });

  // Generate activity data for chart from activity items
  // Group activities by date and count users, projects, tasks
  const activityDataMap = new Map<string, { date: string; users: number; projects: number; tasks: number }>();

  for (const item of backendItems) {
    const date = item.createdAt.split('T')[0]; // Get YYYY-MM-DD
    const existing = activityDataMap.get(date) || { date, users: 0, projects: 0, tasks: 0 };

    if (item.type === 'user') {
      existing.users += 1;
    } else if (item.type === 'project') {
      existing.projects += 1;
    } else if (item.type === 'task') {
      existing.tasks += 1;
    }

    activityDataMap.set(date, existing);
  }

  // Convert map to array and sort by date
  const activityData = Array.from(activityDataMap.values()).sort((a, b) =>
    a.date.localeCompare(b.date)
  );

  return {
    activityData,
    recentActivities: transformedActivities,
  };
}

export default function AdminDashboardPage() {
  const { data: stats, isLoading: isStatsLoading } = useQuery({
    queryKey: ['admin', 'dashboard', 'stats'],
    queryFn: fetchDashboardStats,
    staleTime: 1000 * 60 * 5, // 5 minutes
  });

  const { data: activity, isLoading: isActivityLoading } = useQuery({
    queryKey: ['admin', 'dashboard', 'activity'],
    queryFn: fetchDashboardActivity,
    staleTime: 1000 * 60 * 5, // 5 minutes
  });

  return (
    <PageContainer>
      <PageHeader
        title="平台概览"
        description="查看系统概览和最近活动"
      />

      <StatsCards stats={stats} isLoading={isStatsLoading} />

      <div className="grid gap-6 lg:grid-cols-3">
        <div className="lg:col-span-2">
          <ActivityChart
            data={activity?.activityData}
            isLoading={isActivityLoading}
          />
        </div>
        <div>
          <RecentActivity
            activities={activity?.recentActivities}
            isLoading={isActivityLoading}
          />
        </div>
      </div>
    </PageContainer>
  );
}
