'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import {
  projectsApi,
  creditsApi,
  billingApi,
  usersApi,
  templatesApi,
  dashboardApi,
  xTwitterApi,
  notificationsApi,
  adminApi,
  type Project,
  type CreateProjectPayload,
  type CreateFromTweetPayload,
  type CreateFromYoutubePayload,
  type CreateFromDocumentPayload,
  type ExtractDocumentTopicsPayload,
  type CreateFromExtractedTextPayload,
  type CreateFromTextPayload,
  type ExtractDocumentTopicsResponse,
  type Template,
  type PaginatedResponse,
} from '@/lib/api/api-service';
import { toaster as toast } from '@/components/ui/feedback/toaster';

// ═══════════════════════════════════════════════════════
// Query Keys — React Query cache yönetimi
// ═══════════════════════════════════════════════════════

export const queryKeys = {
  projects: {
    all: ['projects'] as const,
    list: (params?: Record<string, unknown>) => ['projects', 'list', params] as const,
    detail: (id: string) => ['projects', 'detail', id] as const,
  },
  credits: {
    balance: ['credits', 'balance'] as const,
    history: (params?: Record<string, unknown>) => ['credits', 'history', params] as const,
  },
  templates: {
    all: ['templates'] as const,
    list: (params?: Record<string, unknown>) => ['templates', 'list', params] as const,
    detail: (id: string) => ['templates', 'detail', id] as const,
  },
  dashboard: {
    stats: ['dashboard', 'stats'] as const,
  },
  user: {
    me: ['user', 'me'] as const,
  },
  billing: {
    subscription: ['billing', 'subscription'] as const,
  },
  notifications: {
    all: ['notifications'] as const,
    list: (params?: Record<string, unknown>) => ['notifications', 'list', params] as const,
    unreadCount: ['notifications', 'unread-count'] as const,
  },
  admin: {
    stats: ['admin', 'stats'] as const,
    users: (params?: Record<string, unknown>) => ['admin', 'users', params] as const,
    projects: (params?: Record<string, unknown>) => ['admin', 'projects', params] as const,
    renderJobs: (params?: Record<string, unknown>) => ['admin', 'render-jobs', params] as const,
    plans: ['admin', 'plans'] as const,
    roles: ['admin', 'roles'] as const,
  },
};

// ═══════════════════════════════════════════════════════
// PROJECTS — Hook'ları
// ═══════════════════════════════════════════════════════

/** Proje listesi — sayfalı, filtreleme destekli */
export function useProjects(params?: { page?: number; limit?: number; status?: string }) {
  return useQuery({
    queryKey: queryKeys.projects.list(params),
    queryFn: () => projectsApi.list(params),
    staleTime: 30_000,
  });
}

/** Tek proje detayı — sahneler, medya, render job dahil */
export function useProject(id: string, options?: { refetchInterval?: number | ((data: any) => number | false) }) {
  return useQuery({
    queryKey: queryKeys.projects.detail(id),
    queryFn: () => projectsApi.get(id),
    enabled: !!id,
    staleTime: 10_000,
    refetchInterval: options?.refetchInterval,
  });
}

/** Render kuyruğu genel görünümü — aktif işlem varsa otomatik polling */
export function useRenderQueue() {
  return useQuery({
    queryKey: ['render-queue'] as const,
    queryFn: () => projectsApi.getRenderQueue(),
    staleTime: 5_000,
    refetchInterval: (query: any) => {
      const data = query?.state?.data;
      if (!data?.stats) return 10_000;
      const hasActive = data.stats.queued > 0 || data.stats.processing > 0;
      return hasActive ? 4_000 : 15_000;
    },
  });
}

/** Yeni proje oluştur */
export function useCreateProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateProjectPayload) => projectsApi.create(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** Proje güncelle */
export function useUpdateProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Partial<CreateProjectPayload> }) =>
      projectsApi.update(id, data),
    onSuccess: (_data, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.id) });
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
    },
  });
}

/** Proje sil (soft delete) */
export function useDeleteProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => projectsApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** AI senaryo üret — SEO + Humanizer-enhanced */
export function useGenerateScript() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (projectId: string) => projectsApi.generateScript(projectId),
    onSuccess: (data) => {
      qc.setQueryData(queryKeys.projects.detail(data.id), data);
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
    },
  });
}

/** Onay ver ve video üretimine gönder (BullMQ kuyruğu) */
export function useApproveAndQueue() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, data }: { projectId: string; data?: { ttsProvider?: string; visualEffect?: string } }) =>
      projectsApi.approveAndQueue(projectId, data),
    onSuccess: (_data, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.credits.balance });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** Render işlemini iptal et */
export function useCancelRender() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (projectId: string) => projectsApi.cancelRender(projectId),
    onSuccess: (_data, projectId) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
    },
  });
}

/** AI ile 5 yeni SEO başlığı üret */
export function useGenerateSeoTitles() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (projectId: string) =>
      projectsApi.generateSeoTitles(projectId),
    onSuccess: (_data, projectId) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
    },
  });
}

/** AI ile tüm SEO ve Sosyal Medya içeriklerini (caption, description vs) üret */
export function useGenerateSocialContent() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (projectId: string) =>
      projectsApi.generateSocialContent(projectId),
    onSuccess: (_data, projectId) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(projectId) });
      toast.success({ title: 'SEO ve Sosyal Medya içerikleri başarıyla üretildi' });
    },
    onError: (error: any) => {
      console.error('İçerik üretme hatası:', error);
      toast.error({ title: 'Hata', description: error.response?.data?.message || 'İçerikler üretilemedi' });
    },
  });
}

/** Alternatif SEO başlıklarından birini seç ve proje başlığını güncelle */
export function useSelectSeoTitle() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, title }: { projectId: string; title: string }) =>
      projectsApi.selectSeoTitle(projectId, title),
    onSuccess: (_data, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
    },
  });
}

/** Sahne güncelleme (narrasyon, prompt) */
export function useUpdateScene() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, sceneId, data }: { projectId: string; sceneId: string; data: any }) =>
      projectsApi.updateScene(projectId, sceneId, data),
    onSuccess: (updatedScene, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
    },
  });
}

/** Sahneyi AI ile yeniden üretme (Senaryo) */
export function useRegenerateScene() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, sceneId }: { projectId: string; sceneId: string }) =>
      projectsApi.regenerateScene(projectId, sceneId),
    onSuccess: (updatedScene, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
    },
  });
}

/** Sahne görseli oluştur (Gemini) */
export function useGenerateSceneImage() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, sceneId, customPrompt }: { projectId: string; sceneId: string; customPrompt?: string }) =>
      projectsApi.generateSceneImage(projectId, sceneId, customPrompt),
    onSuccess: (updatedScene, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
      toast.success({ title: 'Görsel başarıyla üretildi' });
    },
    onError: (error: any) => {
      console.error('Görsel üretme hatası:', error);
      toast.error({ title: 'Hata', description: error.response?.data?.message || 'Görsel üretilemedi' });
    },
  });
}

/** Sahne görselini upscale (4K) yap */
export function useUpscaleSceneImage() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ projectId, sceneId }: { projectId: string; sceneId: string }) =>
      projectsApi.upscaleSceneImage(projectId, sceneId),
    onSuccess: (updatedScene, variables) => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.detail(variables.projectId) });
    },
  });
}

// ═══════════════════════════════════════════════════════
// CREDITS — Kredi hook'ları
// ═══════════════════════════════════════════════════════

/** Mevcut kredi bakiyesi */
export function useCreditBalance() {
  return useQuery({
    queryKey: queryKeys.credits.balance,
    queryFn: () => creditsApi.getBalance(),
    staleTime: 60_000,
  });
}

/** Kredi işlem geçmişi */
export function useCreditHistory(params?: { page?: number; limit?: number }) {
  return useQuery({
    queryKey: queryKeys.credits.history(params),
    queryFn: () => creditsApi.getHistory(params),
    staleTime: 30_000,
  });
}

// ═══════════════════════════════════════════════════════
// TEMPLATES — Şablon hook'ları
// ═══════════════════════════════════════════════════════

/** Şablon galerisi */
export function useTemplates(params?: {
  category?: string;
  language?: string;
  page?: number;
  limit?: number;
}) {
  return useQuery({
    queryKey: queryKeys.templates.list(params),
    queryFn: () => templatesApi.list(params),
    staleTime: 120_000,
  });
}

/** Tek şablon detayı */
export function useTemplate(id: string) {
  return useQuery({
    queryKey: queryKeys.templates.detail(id),
    queryFn: () => templatesApi.get(id),
    enabled: !!id,
  });
}

/** Şablondan proje klonla */
export function useCloneTemplate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (templateId: string) => templatesApi.clone(templateId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

// ═══════════════════════════════════════════════════════
// DASHBOARD — İstatistik hook'ları
// ═══════════════════════════════════════════════════════

/** Dashboard istatistikleri */
export function useDashboardStats() {
  return useQuery({
    queryKey: queryKeys.dashboard.stats,
    queryFn: () => dashboardApi.getStats(),
    staleTime: 30_000,
    refetchInterval: 60_000,
  });
}

// ═══════════════════════════════════════════════════════
// USER — Kullanıcı profil hook'ları
// ═══════════════════════════════════════════════════════

/** Mevcut kullanıcı bilgisi */
export function useCurrentUser() {
  return useQuery({
    queryKey: queryKeys.user.me,
    queryFn: () => usersApi.getMe(),
    staleTime: 120_000,
  });
}

/** Profil güncelle */
export function useUpdateProfile() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: { firstName?: string; lastName?: string }) =>
      usersApi.updateProfile(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.user.me });
    },
  });
}

/** Şifre değiştir */
export function useChangePassword() {
  return useMutation({
    mutationFn: (data: { currentPassword: string; newPassword: string }) =>
      usersApi.changePassword(data),
  });
}

// ═══════════════════════════════════════════════════════
// BILLING — Abonelik hook'ları
// ═══════════════════════════════════════════════════════

/** Aktif abonelik bilgisi */
export function useSubscription() {
  return useQuery({
    queryKey: queryKeys.billing.subscription,
    queryFn: () => billingApi.getSubscription(),
    staleTime: 60_000,
  });
}

/** Stripe Checkout oturumu oluştur */
export function useCreateCheckout() {
  return useMutation({
    mutationFn: ({ planName, billingCycle }: { planName: string; billingCycle: 'monthly' | 'yearly' }) =>
      billingApi.createCheckout(planName, billingCycle),
    onSuccess: (data) => {
      if (data?.url) {
        window.location.href = data.url;
      }
    },
  });
}

// ═══════════════════════════════════════════════════════
// X/TWITTER — Tweet hook'ları
// ═══════════════════════════════════════════════════════

/** Tweet önizleme */
export function useTweetPreview() {
  return useMutation({
    mutationFn: (tweetUrl: string) => xTwitterApi.preview(tweetUrl),
  });
}

/** Tweet'ten proje oluştur */
export function useCreateFromTweet() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateFromTweetPayload) => projectsApi.createFromTweet(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** YouTube linkinden proje oluştur */
export function useCreateFromYoutube() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateFromYoutubePayload) => projectsApi.createFromYoutube(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** Dokümandan proje oluştur */
export function useCreateFromDocument() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateFromDocumentPayload) => projectsApi.createFromDocument(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** Dokümandan konu önerileri çıkar */
export function useExtractDocumentTopics() {
  return useMutation({
    mutationFn: (data: ExtractDocumentTopicsPayload) => projectsApi.extractDocumentTopics(data),
  });
}

/** Çıkarılan metin ve konudan proje üret */
export function useCreateFromExtractedText() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateFromExtractedTextPayload) => projectsApi.createFromExtractedText(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

/** Serbest metin veya fikir üzerinden proje üret */
export function useCreateFromText() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (data: CreateFromTextPayload) => projectsApi.createFromText(data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.projects.all });
      qc.invalidateQueries({ queryKey: queryKeys.dashboard.stats });
    },
  });
}

// ═══════════════════════════════════════════════════════
// NOTIFICATIONS — Bildirim hook'ları
// ═══════════════════════════════════════════════════════

/** Bildirim listesi — sayfalı, sadece okunmamışlar filtresi */
export function useNotifications(params?: { page?: number; limit?: number; unreadOnly?: boolean }) {
  return useQuery({
    queryKey: queryKeys.notifications.list(params),
    queryFn: () => notificationsApi.list(params),
    staleTime: 15_000,
    refetchInterval: 30_000,
  });
}

/** Okunmamış bildirim sayısı — TopBar badge için */
export function useUnreadNotificationCount() {
  return useQuery({
    queryKey: queryKeys.notifications.unreadCount,
    queryFn: () => notificationsApi.getUnreadCount(),
    staleTime: 10_000,
    refetchInterval: 15_000,
  });
}

/** Tek bildirimi okundu işaretle */
export function useMarkNotificationAsRead() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => notificationsApi.markAsRead(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.notifications.all });
    },
  });
}

/** Tüm bildirimleri okundu işaretle */
export function useMarkAllNotificationsAsRead() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () => notificationsApi.markAllAsRead(),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.notifications.all });
    },
  });
}

/** Bildirim sil */
export function useDeleteNotification() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => notificationsApi.delete(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.notifications.all });
    },
  });
}

// ═══════════════════════════════════════════════════════
// ADMIN — Yönetici hook'ları
// ═══════════════════════════════════════════════════════

/** Sistem istatistikleri */
export function useAdminStats() {
  return useQuery({
    queryKey: queryKeys.admin.stats,
    queryFn: () => adminApi.getStats(),
    staleTime: 30_000,
    refetchInterval: 60_000,
  });
}

/** Tüm kullanıcılar (admin) */
export function useAdminUsers(params?: { page?: number; limit?: number }) {
  return useQuery({
    queryKey: queryKeys.admin.users(params),
    queryFn: () => adminApi.getUsers(params),
    staleTime: 15_000,
  });
}

/** Tüm projeler (admin) */
export function useAdminProjects(params?: { page?: number; limit?: number; status?: string; userId?: string }) {
  return useQuery({
    queryKey: queryKeys.admin.projects(params),
    queryFn: () => adminApi.getProjects(params),
    staleTime: 15_000,
  });
}

/** Tüm render joblar (admin) */
export function useAdminRenderJobs(params?: { page?: number; limit?: number; status?: string }) {
  return useQuery({
    queryKey: queryKeys.admin.renderJobs(params),
    queryFn: () => adminApi.getRenderJobs(params),
    staleTime: 10_000,
    refetchInterval: 15_000,
  });
}

/** Plan listesi (admin) */
export function useAdminPlans() {
  return useQuery({
    queryKey: queryKeys.admin.plans,
    queryFn: () => adminApi.getPlans(),
    staleTime: 60_000,
  });
}

/** Kullanıcıya kredi yükle */
export function useGrantCredits() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ userId, amount, description }: { userId: string; amount: number; description: string }) =>
      adminApi.grantCredits(userId, { amount, description }),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.admin.users() });
      qc.invalidateQueries({ queryKey: queryKeys.admin.stats });
    },
  });
}

/** Kullanıcı aktif/pasif toggle */
export function useToggleUserActive() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => adminApi.toggleUserActive(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.admin.users() });
    },
  });
}

/** Plan güncelle */
export function useAdminUpdatePlan() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: Record<string, unknown> }) =>
      adminApi.updatePlan(id, data),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.admin.plans });
    },
  });
}

/** Admin proje sil */
export function useAdminDeleteProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => adminApi.deleteProject(id),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.admin.projects() });
      qc.invalidateQueries({ queryKey: queryKeys.admin.stats });
    },
  });
}
