import { apiFetch } from './client';

export type CategoryOption = { value: string; label: string; gradient: [string, string] };
export type ItemTypeOption = { value: string; label: string; badge: string };

export type MealPlanItem = {
  id: number;
  category: string;
  type: string;
  title: string;
  subtitle: string | null;
  recipeId: number | null;
  imageUrl: string | null;
  // Origine de la recette liée ('tracked'/'own'/'catalog'/'anchor', voir
  // MealPlanAutofillService::sourceInfo()) — null si l'item n'a pas de recette (idée IA
  // texte libre, aliment simple).
  source: string | null;
  // Jour prévu (Midi/Soir uniquement) — null pour Petit-déjeuner/Collation, qui restent une
  // simple file sans notion de jour. Plusieurs items peuvent partager la même date.
  plannedDate: string | null;
  canRemove: boolean;
  // Type 'ai' uniquement — pas de fiche recette pour ce type, affichés au clic sur
  // "Ouvrir" (voir MealItemCard.tsx). Toujours vide pour les autres types.
  ingredients: AiIngredient[];
};

export type MealPlanSection = {
  category: string;
  label: string;
  gradient: [string, string];
  count: number;
  target: number;
  statusShow: boolean;
  statusText: string | null;
  statusColor: string | null;
  items: MealPlanItem[];
};

export type MealPlanPeriod = { id: number; startDate: string; endDate: string | null };

export type MealPlanPayload = {
  plan: MealPlanPeriod;
  sections: MealPlanSection[];
  meta: { categories: CategoryOption[]; itemTypes: ItemTypeOption[]; hasFamilyMembers: boolean };
};

export type PickerRecipe = {
  id: number;
  name: string;
  imageUrl: string | null;
  totalCalories: number;
  prepTimeMinutes: number | null;
  servings: number | null;
  categories: string[];
  dietTags: { value: string; label: string; color: string }[];
  gradient: [string, string];
};

export type AiIngredient = { name: string; quantity: number; unit: string };

export type AddItemInput = {
  category: string;
  type: string;
  title?: string;
  subtitle?: string;
  recipeId?: number;
  // Format 'YYYY-MM-DD' — omis pour Petit-déjeuner/Collation (pas de notion de jour).
  plannedDate?: string;
  // Type 'ai' uniquement — reportés dans la liste de courses, pas de fiche recette créée.
  ingredients?: AiIngredient[];
};

export type AiIdea = { title: string; desc: string | null; ingredients: AiIngredient[] };

export function fetchMealPlan() {
  return apiFetch<MealPlanPayload>('/meal-plan');
}

export function addItem(input: AddItemInput) {
  return apiFetch<MealPlanPayload>('/meal-plan/items', { method: 'POST', body: input });
}

// En POST plutôt que DELETE — l'hébergement de prod bloque ce verbe HTTP (403 avant
// même d'atteindre PHP), voir Api\V1\TrackingController::removeEntry().
export function removeItem(id: number) {
  return apiFetch<MealPlanPayload>(`/meal-plan/items/${id}/remove`, { method: 'POST' });
}

export function moveItem(id: number, direction: 'up' | 'down') {
  return apiFetch<MealPlanPayload>(`/meal-plan/items/${id}/move`, { method: 'POST', body: { direction } });
}

// Format 'YYYY-MM-DD' — report d'un repas (Midi/Soir) vers un autre jour.
export function moveItemToDate(id: number, plannedDate: string) {
  return apiFetch<MealPlanPayload>(`/meal-plan/items/${id}/move-date`, { method: 'POST', body: { plannedDate } });
}

export function adjustTarget(category: string, direction: 'inc' | 'dec') {
  return apiFetch<MealPlanPayload>(`/meal-plan/categories/${category}/target`, { method: 'POST', body: { direction } });
}

export function searchRecipes(query: string) {
  return apiFetch<{ recipes: PickerRecipe[] }>(`/meal-plan/recipes${query ? `?q=${encodeURIComponent(query)}` : ''}`);
}

export function generateAiIdea(ingredients: string, envie: string, assumeBasics: boolean) {
  return apiFetch<AiIdea>('/meal-plan/ai-preview', { method: 'POST', body: { ingredients, envie, assumeBasics } });
}

// Envoie un email à chaque membre de la famille (hors soi-même) pour lui demander une idée de
// repas — bouton visible uniquement si `meta.hasFamilyMembers` (AddMealModal.tsx).
export function askFamilyIdeas() {
  return apiFetch<{ sent: number }>('/meal-plan/ask-family-ideas', { method: 'POST' });
}

// Voir MealPlanAutofillService::previewUpcoming()/applyPreview() — "Remplir automatiquement"
// en 2 temps : preview (calcule sans ajouter, pour la popin de revue d'AutofillModal.tsx, qui
// laisse retirer une proposition avant confirmation) puis apply (persiste ce qui reste).
// 'source' : 'tracked' (correspond à un repas suivi dans "Mon suivi") | 'own' (une de mes
// recettes) | 'catalog' (recette favorite/famille) | 'anchor' (repas fixe configuré par
// l'utilisateur — voir MealPlanAutofillService::sourceInfo()).
export type AutofillPreviewItem = {
  category: string;
  plannedDate: string | null;
  type: string;
  recipeId: number | null;
  title: string;
  source: string;
  imageUrl: string | null;
};

export function previewAutofill(startDate: string, days: number) {
  return apiFetch<{ items: AutofillPreviewItem[] }>('/meal-plan/autofill-preview', { method: 'POST', body: { startDate, days } });
}

export function applyAutofill(items: AutofillPreviewItem[]) {
  return apiFetch<MealPlanPayload & { added: number }>('/meal-plan/autofill-apply', { method: 'POST', body: { items } });
}

// Bouton "Autre proposition" sur une ligne de la popin de revue — voir
// MealPlanAutofillService::resuggestItem(). `excludeRecipeIds` doit inclure toutes les
// recettes déjà affichées dans la popin (celle à remplacer comprise), pour ne jamais
// reproposer un doublon visible à l'écran. `item: null` si plus rien d'autre à proposer.
export function resuggestAutofillItem(category: string, plannedDate: string | null, excludeRecipeIds: number[]) {
  return apiFetch<{ item: AutofillPreviewItem | null }>('/meal-plan/autofill-suggest', {
    method: 'POST',
    body: { category, plannedDate, excludeRecipeIds },
  });
}

