'use server';

import { dailyService } from '@/services/task-management/daily';
import {
  UpdateDailyCheckboxData,
  DailyCheckbox,
  CreateDailyCheckboxData,
} from '@/lib/types';
import { revalidatePath } from 'next/cache';
import {
  getToday,
  getPreviousWorkday,
  parseDate,
  normalizeDate,
} from '@/lib/date-utils';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/lib/auth';

/**
 * Toggle l'état d'une checkbox
 */
export async function toggleCheckbox(checkboxId: string): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    // Toggle direct côté service par ID (indépendant de la date)
    const updatedCheckbox = await dailyService.toggleCheckbox(checkboxId);

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

/**
 * Ajoute une checkbox pour aujourd'hui
 */
export async function addTodayCheckbox(
  content: string,
  type?: 'task' | 'meeting',
  taskId?: string,
  date?: Date
): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const targetDate = normalizeDate(date || getToday());

    const newCheckbox = await dailyService.addCheckbox({
      date: targetDate,
      userId: session.user.id,
      text: content,
      type: type || 'task',
      taskId,
    });

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

/**
 * Ajoute une checkbox pour hier
 */
export async function addYesterdayCheckbox(
  content: string,
  type?: 'task' | 'meeting',
  taskId?: string,
  baseDate?: Date
): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const base = normalizeDate(baseDate || getToday());
    const yesterday = getPreviousWorkday(base);

    const newCheckbox = await dailyService.addCheckbox({
      date: yesterday,
      userId: session.user.id,
      text: content,
      type: type || 'task',
      taskId,
    });

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

/**
 * Met à jour une checkbox complète
 */
export async function updateCheckbox(
  checkboxId: string,
  data: UpdateDailyCheckboxData
): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const updatedCheckbox = await dailyService.updateCheckbox(checkboxId, data);

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

/**
 * Supprime une checkbox
 */
export async function deleteCheckbox(checkboxId: string): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    await dailyService.deleteCheckbox(checkboxId);

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

/**
 * Ajoute un todo lié à une tâche
 */
export async function addTodoToTask(
  taskId: string,
  text: string,
  date?: Date
): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.id) {
      return { success: false, error: 'Non authentifié' };
    }

    const targetDate = normalizeDate(date || getToday());

    const checkboxData: CreateDailyCheckboxData = {
      date: targetDate,
      userId: session.user.id,
      text: text.trim(),
      type: 'task',
      taskId: taskId,
      isChecked: false,
    };

    const checkbox = await dailyService.addCheckbox(checkboxData);

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

/**
 * Réorganise les checkboxes d'une date
 */
export async function reorderCheckboxes(
  dailyId: string,
  checkboxIds: string[]
): Promise<{
  success: boolean;
  error?: string;
}> {
  try {
    // Le dailyId correspond à la date au format YYYY-MM-DD
    const date = parseDate(dailyId);

    await dailyService.reorderCheckboxes(date, checkboxIds);

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

/**
 * Déplace une checkbox non cochée à aujourd'hui
 */
export async function moveCheckboxToToday(checkboxId: string): Promise<{
  success: boolean;
  data?: DailyCheckbox;
  error?: string;
}> {
  try {
    const updatedCheckbox = await dailyService.moveCheckboxToToday(checkboxId);

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