import {create} from 'zustand';
import AsyncStorage from '@react-native-async-storage/async-storage';
import {ContentType} from '../api/addonTypes';

const PREFIX = 'library:';

export interface LibraryItem {
  id: string;
  type: ContentType;
  name: string;
  poster?: string;
  addedAt: number;
  lastWatchedAt?: number;
  watchProgress?: number; // 0-1
  watchDuration?: number; // seconds
  currentVideoId?: string; // for series: "tt:season:episode"
  isWatchlist: boolean;
  isFavorite: boolean;
}

interface LibraryState {
  watchlist: LibraryItem[];
  favorites: LibraryItem[];
  history: LibraryItem[];
  loaded: boolean;
  // Actions
  load: () => Promise<void>;
  addToWatchlist: (item: Omit<LibraryItem, 'addedAt' | 'isWatchlist' | 'isFavorite'>) => void;
  removeFromWatchlist: (id: string) => void;
  toggleFavorite: (id: string) => void;
  updateProgress: (id: string, progress: number, duration: number, videoId?: string) => void;
  addToHistory: (item: LibraryItem) => void;
  getItem: (id: string) => LibraryItem | undefined;
}

async function saveKey(key: string, data: unknown) {
  await AsyncStorage.setItem(PREFIX + key, JSON.stringify(data));
}

async function loadKey<T>(key: string, fallback: T): Promise<T> {
  const raw = await AsyncStorage.getItem(PREFIX + key);
  if (!raw) return fallback;
  try {
    return JSON.parse(raw) as T;
  } catch {
    return fallback;
  }
}

export const useLibraryStore = create<LibraryState>((set, get) => ({
  watchlist: [],
  favorites: [],
  history: [],
  loaded: false,

  load: async () => {
    const [watchlist, favorites, history] = await Promise.all([
      loadKey<LibraryItem[]>('watchlist', []),
      loadKey<LibraryItem[]>('favorites', []),
      loadKey<LibraryItem[]>('history', []),
    ]);
    set({watchlist, favorites, history, loaded: true});
  },

  addToWatchlist: item => {
    const existing = get().watchlist.find(i => i.id === item.id);
    if (existing) return;
    const newItem: LibraryItem = {
      ...item,
      addedAt: Date.now(),
      isWatchlist: true,
      isFavorite: false,
    };
    const updated = [newItem, ...get().watchlist];
    set({watchlist: updated});
    saveKey('watchlist', updated);
  },

  removeFromWatchlist: id => {
    const updated = get().watchlist.filter(i => i.id !== id);
    set({watchlist: updated});
    saveKey('watchlist', updated);
  },

  toggleFavorite: id => {
    const allItems = [...get().watchlist, ...get().history];
    const item = allItems.find(i => i.id === id);
    if (!item) return;

    const favorites = get().favorites;
    const isFav = favorites.some(i => i.id === id);

    if (isFav) {
      const updated = favorites.filter(i => i.id !== id);
      set({favorites: updated});
      saveKey('favorites', updated);
    } else {
      const newFav = {...item, isFavorite: true, addedAt: Date.now()};
      const updated = [newFav, ...favorites];
      set({favorites: updated});
      saveKey('favorites', updated);
    }
  },

  updateProgress: (id, progress, duration, videoId) => {
    const history = get().history;
    const existing = history.find(i => i.id === id);

    if (existing) {
      const updated = history.map(i =>
        i.id === id
          ? {
              ...i,
              watchProgress: progress,
              watchDuration: duration,
              lastWatchedAt: Date.now(),
              currentVideoId: videoId,
            }
          : i,
      );
      set({history: updated});
      saveKey('history', updated);
    }
  },

  addToHistory: (item: LibraryItem) => {
    const history = get().history;
    const filtered = history.filter(i => i.id !== item.id);
    const updated = [item, ...filtered].slice(0, 200); // cap at 200
    set({history: updated});
    saveKey('history', updated);
  },

  getItem: id => {
    const all = [...get().watchlist, ...get().favorites, ...get().history];
    return all.find(i => i.id === id);
  },
}));
