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

const STORAGE_KEY = 'watchLater:queue';

export interface WatchLaterItem {
  infoHash: string;
  name: string;
  poster?: string;
  type: string;
  id: string; // content ID (e.g. "tt1234567")
  season?: number;
  episode?: number;
  episodeTitle?: string;
  addedAt: number;
  progress: number; // 0-100
  status: 'queued' | 'resolving' | 'downloading' | 'ready' | 'error';
  fileName?: string;
  totalSize?: number;
  errorMsg?: string;
}

interface WatchLaterState {
  items: WatchLaterItem[];
  loaded: boolean;
  load: () => Promise<void>;
  addItem: (item: Omit<WatchLaterItem, 'addedAt' | 'progress' | 'status'>) => void;
  removeItem: (infoHash: string) => void;
  updateProgress: (infoHash: string, progress: number, status: WatchLaterItem['status']) => void;
  updateStatus: (infoHash: string, status: WatchLaterItem['status'], errorMsg?: string) => void;
  getItem: (infoHash: string) => WatchLaterItem | undefined;
}

function persist(items: WatchLaterItem[]) {
  AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(items));
}

export const useWatchLaterStore = create<WatchLaterState>((set, get) => ({
  items: [],
  loaded: false,

  load: async () => {
    try {
      const raw = await AsyncStorage.getItem(STORAGE_KEY);
      if (raw) {
        const items = JSON.parse(raw) as WatchLaterItem[];
        // Reset any in-progress items to queued (app was restarted)
        const fixed = items.map(i =>
          i.status === 'resolving' || i.status === 'downloading'
            ? {...i, status: 'queued' as const}
            : i,
        );
        set({items: fixed, loaded: true});
        persist(fixed);
        return;
      }
    } catch {}
    set({loaded: true});
  },

  addItem: item => {
    const existing = get().items.find(i => i.infoHash === item.infoHash);
    if (existing) return;
    const newItem: WatchLaterItem = {
      ...item,
      addedAt: Date.now(),
      progress: 0,
      status: 'queued',
    };
    const updated = [newItem, ...get().items];
    set({items: updated});
    persist(updated);
  },

  removeItem: infoHash => {
    const updated = get().items.filter(i => i.infoHash !== infoHash);
    set({items: updated});
    persist(updated);
  },

  updateProgress: (infoHash, progress, status) => {
    const updated = get().items.map(i =>
      i.infoHash === infoHash ? {...i, progress, status} : i,
    );
    set({items: updated});
    persist(updated);
  },

  updateStatus: (infoHash, status, errorMsg) => {
    const updated = get().items.map(i =>
      i.infoHash === infoHash ? {...i, status, errorMsg} : i,
    );
    set({items: updated});
    persist(updated);
  },

  getItem: infoHash => get().items.find(i => i.infoHash === infoHash),
}));
