import * as FileSystem from 'expo-file-system/legacy';
import * as ImagePicker from 'expo-image-picker';
import { getMeta, setMeta } from '../db/repositories';

export type FieldKey = 'project_name' | 'date' | 'coordinates' | 'custom';

export interface FooterField {
  id: string;
  key: FieldKey;
  label: string;
  enabled: boolean;
  /** Solo para key === 'custom': texto estático que aparece en el pie. */
  customValue?: string;
}

export interface FooterConfig {
  enabled: boolean;
  logoUri: string | null;
  fields: FooterField[];
}

export interface StampMeta {
  projectName: string | null;
  date: string;
  coordinates: string | null;
}

const META_KEY = 'photo_footer_config';
const LOGO_DEST = (FileSystem.documentDirectory ?? '') + 'footer_logo.jpg';

function defaultConfig(): FooterConfig {
  return {
    enabled: true,
    logoUri: null,
    fields: [
      { id: 'project_name', key: 'project_name', label: 'Proyecto', enabled: true },
      { id: 'date', key: 'date', label: 'Fecha', enabled: true },
      { id: 'coordinates', key: 'coordinates', label: 'Coordenadas GPS', enabled: true },
    ],
  };
}

export async function loadFooterConfig(): Promise<FooterConfig> {
  const raw = await getMeta(META_KEY);
  if (!raw) return defaultConfig();
  try {
    return JSON.parse(raw) as FooterConfig;
  } catch {
    return defaultConfig();
  }
}

export async function saveFooterConfig(config: FooterConfig): Promise<void> {
  await setMeta(META_KEY, JSON.stringify(config));
}

/** Abre la galería, copia la imagen al almacenamiento de la app y devuelve la ruta. */
export async function pickAndSaveLogo(): Promise<string | null> {
  const perm = await ImagePicker.requestMediaLibraryPermissionsAsync();
  if (!perm.granted) return null;
  const result = await ImagePicker.launchImageLibraryAsync({
    quality: 0.9,
    mediaTypes: 'images',
    allowsEditing: true,
    aspect: [1, 1],
  });
  if (result.canceled || !result.assets?.length) return null;
  await FileSystem.copyAsync({ from: result.assets[0].uri, to: LOGO_DEST });
  // Añadir timestamp para que Image no use caché de la versión anterior.
  return `${LOGO_DEST}?t=${Date.now()}`;
}

export async function clearLogo(): Promise<void> {
  try { await FileSystem.deleteAsync(LOGO_DEST, { idempotent: true }); } catch { /* */ }
}

/** Resuelve el texto que aparece en la línea de un campo. */
export function resolveFieldValue(field: FooterField, meta: StampMeta): string {
  switch (field.key) {
    case 'project_name': return meta.projectName ?? '';
    case 'date': return meta.date;
    case 'coordinates': return meta.coordinates ?? 'Sin GPS';
    case 'custom': return field.customValue ?? field.label;
    default: return '';
  }
}
