'use server';

import { userPreferencesService } from '@/services/core/user-preferences';
import {
  KanbanFilters,
  ViewPreferences,
  ColumnVisibility,
  TaskStatus,
} from '@/lib/types';
import { Theme } from '@/lib/ui-config';
import { revalidatePath } from 'next/cache';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';

/**
 * Met à jour les préférences de vue
 */
export async function updateViewPreferences(
  updates: Partial<ViewPreferences>
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    await userPreferencesService.updateViewPreferences(
      session.user.id,
      updates
    );
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur updateViewPreferences:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Met à jour l'image de fond
 */
export async function setBackgroundImage(
  backgroundImage: string | undefined
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    await userPreferencesService.updateViewPreferences(session.user.id, {
      backgroundImage,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur setBackgroundImage:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Met à jour les filtres Kanban
 */
export async function updateKanbanFilters(
  updates: Partial<KanbanFilters>
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    await userPreferencesService.updateKanbanFilters(session.user.id, updates);
    revalidatePath('/kanban');
    return { success: true };
  } catch (error) {
    console.error('Erreur updateKanbanFilters:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Met à jour la visibilité des colonnes
 */
export async function updateColumnVisibility(
  updates: Partial<ColumnVisibility>
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const newColumnVisibility: ColumnVisibility = {
      ...preferences.columnVisibility,
      ...updates,
    };

    await userPreferencesService.saveColumnVisibility(
      session.user.id,
      newColumnVisibility
    );
    revalidatePath('/kanban');
    return { success: true };
  } catch (error) {
    console.error('Erreur updateColumnVisibility:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Toggle la visibilité des objectifs
 */
export async function toggleObjectivesVisibility(): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const showObjectives = !preferences.viewPreferences.showObjectives;

    await userPreferencesService.updateViewPreferences(session.user.id, {
      showObjectives,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur toggleObjectivesVisibility:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Toggle le mode collapse des objectifs
 */
export async function toggleObjectivesCollapse(): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const collapseObjectives = !preferences.viewPreferences.collapseObjectives;

    await userPreferencesService.updateViewPreferences(session.user.id, {
      collapseObjectives,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur toggleObjectivesCollapse:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Change le thème (light/dark/dracula/monokai/nord)
 */
export async function setTheme(theme: Theme): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    await userPreferencesService.updateViewPreferences(session.user.id, {
      theme,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur setTheme:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Toggle le thème entre light et dark
 */
export async function toggleTheme(): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const newTheme =
      preferences.viewPreferences.theme === 'dark' ? 'light' : 'dark';

    await userPreferencesService.updateViewPreferences(session.user.id, {
      theme: newTheme,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur toggleTheme:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Toggle la taille de police
 */
export async function toggleFontSize(): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const fontSizes: ('small' | 'medium' | 'large')[] = [
      'small',
      'medium',
      'large',
    ];
    const currentIndex = fontSizes.indexOf(
      preferences.viewPreferences.fontSize
    );
    const nextIndex = (currentIndex + 1) % fontSizes.length;
    const newFontSize = fontSizes[nextIndex];

    await userPreferencesService.updateViewPreferences(session.user.id, {
      fontSize: newFontSize,
    });
    revalidatePath('/');
    return { success: true };
  } catch (error) {
    console.error('Erreur toggleFontSize:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}

/**
 * Toggle la visibilité d'une colonne Kanban
 */
export async function toggleColumnVisibility(status: TaskStatus): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const preferences = await userPreferencesService.getAllPreferences(
      session.user.id
    );
    const hiddenStatuses = new Set(preferences.columnVisibility.hiddenStatuses);

    if (hiddenStatuses.has(status)) {
      hiddenStatuses.delete(status);
    } else {
      hiddenStatuses.add(status);
    }

    await userPreferencesService.saveColumnVisibility(session.user.id, {
      hiddenStatuses: Array.from(hiddenStatuses),
    });

    revalidatePath('/kanban');
    return { success: true };
  } catch (error) {
    console.error('Erreur toggleColumnVisibility:', error);
    return {
      success: false,
      error: error instanceof Error ? error.message : 'Erreur inconnue',
    };
  }
}
