import AsyncStorage from '@react-native-async-storage/async-storage';
import { Share } from 'react-native';
import type { Zone } from 'parksmarter-client';

/**
 * Saved kiosks live entirely on-device. The ParkSmarter server exposes no
 * favorites API (the `FavoriteID` field never appears in live responses), so
 * "save" and "share" are client-side features we own.
 */
export interface SavedKiosk {
  /** Stable local id — the scanner code or serial identifies the kiosk. */
  key: string;
  zoneName?: string;
  scannerCode?: string;
  terminalSerNo?: string;
  zoneId?: number;
  customerId?: number;
  lat?: number;
  long?: number;
  savedAt: number;
  note?: string;
}

const KEY = 'ps_saved_kiosks';

export function kioskKey(z: Pick<Zone, 'ScannerCode' | 'TerminalSerNo' | 'ZoneId'>): string {
  return String(z.ScannerCode ?? z.TerminalSerNo ?? z.ZoneId ?? 'unknown');
}

export function toSavedKiosk(z: Zone, note?: string): SavedKiosk {
  return {
    key: kioskKey(z),
    zoneName: z.ZoneName,
    scannerCode: z.ScannerCode,
    terminalSerNo: z.TerminalSerNo,
    zoneId: z.ZoneId,
    customerId: z.CustomerId,
    lat: z.Lat,
    long: z.Long,
    savedAt: Date.now(),
    note,
  };
}

export async function listKiosks(): Promise<SavedKiosk[]> {
  const raw = await AsyncStorage.getItem(KEY);
  return raw ? (JSON.parse(raw) as SavedKiosk[]) : [];
}

export async function saveKiosk(k: SavedKiosk): Promise<SavedKiosk[]> {
  const all = await listKiosks();
  const next = [k, ...all.filter((x) => x.key !== k.key)];
  await AsyncStorage.setItem(KEY, JSON.stringify(next));
  return next;
}

export async function removeKiosk(key: string): Promise<SavedKiosk[]> {
  const next = (await listKiosks()).filter((x) => x.key !== key);
  await AsyncStorage.setItem(KEY, JSON.stringify(next));
  return next;
}

/**
 * Share a saved kiosk. Uses a `parksmarteralt://` deep link so another install
 * of this app can open straight to the kiosk; falls back to human-readable text.
 */
export async function shareKiosk(k: SavedKiosk): Promise<void> {
  const code = k.scannerCode ?? k.terminalSerNo ?? '';
  const deepLink = `bigbrainparking://kiosk?code=${encodeURIComponent(code)}`;
  const geo =
    k.lat != null && k.long != null ? `\nMap: geo:${k.lat},${k.long}` : '';
  await Share.share({
    message:
      `Parking kiosk${k.zoneName ? `: ${k.zoneName}` : ''}` +
      (code ? `\nCode: ${code}` : '') +
      geo +
      `\nOpen in ParkSmarter: ${deepLink}`,
  });
}
