import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api/apiClient';
import { showSuccess, handleError } from '@/lib/services/errorHandler';

// Query Keys
export const adminProjectKeys = {
  all: ['admin', 'projects'] as const,
  lists: () => [...adminProjectKeys.all, 'list'] as const,
  list: (filters: Record<string, unknown>) => [...adminProjectKeys.lists(), filters] as const,
  details: () => [...adminProjectKeys.all, 'detail'] as const,
  detail: (id: string) => [...adminProjectKeys.details(), id] as const,
};

// Types - Frontend Interfaces (apiClient automatically converts snake_case to camelCase)
export interface AdminProject {
  id: string;
  name: string;
  description?: string;
  type: 'video' | 'comic';
  status: 'active' | 'archived' | 'deleted';
  ownerId: string;
  ownerEmail?: string;
  ownerName?: string;
  progress?: number;
  createdAt: string;
  updatedAt: string;
  assetsCount: number;
  episodesCount: number;
  storyboardsCount: number;
}

export interface AdminProjectDetail extends AdminProject {
  assets: Array<{ id: string; name: string; type: string; desc?: string }>;
  episodes: Array<{ id: string; title: string; order: number; status: string }>;
  storyboards: Array<{ id: string; shot: string; order: number; type: string }>;
}

export interface AdminProjectsResponse {
  items: AdminProject[];
  pagination: {
    page: number;
    page_size: number;
    total: number;
    total_pages: number;
  };
}

export interface AdminProjectFilters {
  page?: number;
  page_size?: number;
  status?: string;
  user_id?: string;
  search?: string;
  [key: string]: undefined | number | string;
}

// Hooks
export function useAdminProjects(filters: AdminProjectFilters = {}) {
  const { page = 1, page_size = 20, status, user_id, search } = filters;

  return useQuery({
    queryKey: adminProjectKeys.list(filters),
    queryFn: async () => {
      const params = new URLSearchParams();
      params.append('page', String(page));
      params.append('page_size', String(page_size));
      if (status) params.append('status', status);
      if (user_id) params.append('user_id', user_id);
      if (search) params.append('search', search);

      const response = await api.get(`/api/v1/admin/projects?${params.toString()}`);
      // Backend returns: { code, data: { items, pagination }, meta }
      // apiClient automatically converts snake_case to camelCase
      const data = response.data?.data ?? response.data;
      return {
        items: (data as any)?.items || [],
        pagination: (data as any)?.pagination || {}
      } as AdminProjectsResponse;
    },
    staleTime: 30 * 1000, // 30 seconds
  });
}

export function useAdminProject(projectId: string | null) {
  return useQuery({
    queryKey: adminProjectKeys.detail(projectId || ''),
    queryFn: async () => {
      if (!projectId) return null;
      const response = await api.get(`/api/v1/admin/projects/${projectId}`);
      // apiClient automatically converts snake_case to camelCase
      const data = response.data?.data ?? response.data;
      // Map backend response to frontend AdminProjectDetail format
      if (data) {
        return {
          ...data,
          assetsCount: data.assetsCount || data.assets?.length || 0,
          episodesCount: data.episodesCount || data.episodes?.length || 0,
          storyboardsCount: data.storyboardsCount || data.storyboards?.length || 0,
        } as AdminProjectDetail;
      }
      return null;
    },
    enabled: !!projectId,
    staleTime: 60 * 1000,
  });
}

export function useDeleteAdminProject() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (projectId: string) => {
      await api.delete(`/api/v1/admin/projects/${projectId}`);
      return projectId;
    },
    onSuccess: () => {
      showSuccess('删除成功', '项目已成功删除');
      queryClient.invalidateQueries({ queryKey: adminProjectKeys.all });
    },
    onError: (error) => {
      handleError(error, 'DeleteAdminProject', {
        customMessage: '删除项目失败，请重试',
      });
    },
  });
}
