import { create } from "zustand";

export interface TorrentInfo {
  hash: string;
  name: string;
  size: number;
  progress: number;
  dlspeed: number;
  upspeed?: number;
  state: string;
  magnet_uri?: string;
  tracker?: string;
  num_seeds?: number;
  num_leechs?: number;
  tags?: string;
  category?: string;
  added_on?: number;
  seeding_time?: number;
}

export interface LoopJob {
  id: string;
  torrentHash: string;
  name: string;
  sizeBytes: number;
  allowIp: string;
  targetLoops: number;
  doneLoops: number;
  delayMs: number;
  profileName?: string;
  profileId?: string;
  status: string;
  bans: { bannedIps: string[] };
  nextRunAt?: string;
  lastError?: string;
  totals?: { totalDownloadedBytes: number };
  createdAt?: string;
  updatedAt?: string;
}

export interface StatusSnapshot {
  qbit: { ok: boolean; version?: string; lastError?: string };
  torrents: TorrentInfo[];
  transfer?: any;
  jobs: LoopJob[];
}

export interface JobLog {
  jobId: string;
  level: "INFO" | "WARN" | "ERROR";
  message: string;
  createdAt: string;
}

export interface TimerRule {
  id: string;
  tags: string[];
  seedLimitSeconds: number;
  deleteFiles?: boolean;
  createdAt: string;
}

export interface TimerLog {
  id: string;
  hash: string;
  name: string;
  sizeBytes: number;
  tracker?: string;
  tags: string[];
  category?: string;
  seedingTimeSeconds: number;
  uploadedBytes: number;
  deletedAt: string;
}

export interface TimerSummary {
  totalDeleted: number;
  totalSeededSeconds: number;
  totalUploadedBytes: number;
  updatedAt: string;
}

export interface WatcherTracker {
  key: string;
  label: string;
  cliSiteKey: string;
  supportsRemoveBookmark: boolean;
}

export interface Watcher {
  id: string;
  tracker: string;
  trackerLabel: string;
  wishlistUrl?: string;
  category?: string;
  cookieHint: string;
  hasCookie: boolean;
  intervalMinutes: number;
  enabled: boolean;
  lastRunAt?: string;
  lastSuccessAt?: string;
  lastError?: string;
  nextRunAt?: string;
  totalImported: number;
  totalSeen: number;
  createdAt: string;
  updatedAt: string;
}

export interface WatcherItem {
  id: string;
  watcherId: string;
  tracker: string;
  trackerLabel: string;
  sourceKey: string;
  pageUrl: string;
  title: string;
  imageUrl?: string;
  downloadUrl?: string;
  removeToken?: string;
  status: string;
  statusLabel: string;
  qbitHash?: string;
  qbitName?: string;
  progress: number;
  state?: string;
  qbitCategory?: string;
  sizeBytes?: number;
  seeders?: number;
  leechers?: number;
  seenAt: string;
  importedAt?: string;
  lastSyncAt: string;
  errorMessage?: string;
}

export interface WatcherSummary {
  activeWatchers: number;
  totalImported: number;
  totalSeen: number;
  trackedLabels: string[];
  lastRunAt?: string;
  lastSuccessAt?: string;
  nextRunAt?: string;
  lastError?: string;
  updatedAt: string;
  watchers: Array<{
    id: string;
    tracker: string;
    trackerLabel: string;
    enabled: boolean;
    lastRunAt?: string;
    lastSuccessAt?: string;
    nextRunAt?: string;
    totalImported: number;
  }>;
}

interface AppState {
  qbit: StatusSnapshot["qbit"];
  torrents: TorrentInfo[];
  transfer: any;
  jobs: LoopJob[];
  logs: JobLog[];
  timerRules: TimerRule[];
  timerLogs: TimerLog[];
  timerSummary: TimerSummary | null;
  watcherTrackers: WatcherTracker[];
  qbitCategories: string[];
  watchers: Watcher[];
  watcherItems: WatcherItem[];
  watcherSummary: WatcherSummary | null;
  selectedHash: string | null;
  loopForm: { allowIp: string; delayMs: number; targetLoops: number };
  setSnapshot: (snapshot: StatusSnapshot) => void;
  updateStatus: (snapshot: Partial<StatusSnapshot>) => void;
  addLog: (log: JobLog) => void;
  setLogs: (logs: JobLog[]) => void;
  setTimerRules: (rules: TimerRule[]) => void;
  setTimerLogs: (logs: TimerLog[]) => void;
  addTimerLog: (log: TimerLog) => void;
  setTimerSummary: (summary: TimerSummary) => void;
  setWatcherTrackers: (trackers: WatcherTracker[]) => void;
  setQbitCategories: (categories: string[]) => void;
  setWatchers: (watchers: Watcher[]) => void;
  setWatcherItems: (items: WatcherItem[]) => void;
  setWatcherSummary: (summary: WatcherSummary | null) => void;
  selectHash: (hash: string) => void;
  setLoopForm: (partial: Partial<AppState["loopForm"]>) => void;
}

export const useAppStore = create<AppState>((set) => ({
  qbit: { ok: false },
  torrents: [],
  transfer: null,
  jobs: [],
  logs: [],
  timerRules: [],
  timerLogs: [],
  timerSummary: null,
  watcherTrackers: [],
  qbitCategories: [],
  watchers: [],
  watcherItems: [],
  watcherSummary: null,
  selectedHash: null,
  loopForm: { allowIp: "", delayMs: 3000, targetLoops: 3 },
  setSnapshot: (snapshot) =>
    set((state) => ({
      qbit: snapshot.qbit,
      torrents: snapshot.torrents,
      transfer: snapshot.transfer,
      jobs: snapshot.jobs,
      selectedHash:
        state.selectedHash ?? snapshot.torrents?.[0]?.hash ?? null,
    })),
  updateStatus: (snapshot) =>
    set((state) => ({
      qbit: snapshot.qbit ?? state.qbit,
      torrents: snapshot.torrents ?? state.torrents,
      transfer: snapshot.transfer ?? state.transfer,
      jobs: snapshot.jobs ?? state.jobs,
    })),
  addLog: (log) =>
    set((state) => ({
      logs: [...state.logs, log].slice(-500),
    })),
  setLogs: (logs) => set({ logs }),
  setTimerRules: (rules) => set({ timerRules: rules }),
  setTimerLogs: (logs) => set({ timerLogs: logs }),
  addTimerLog: (log) =>
    set((state) => ({
      timerLogs: [log, ...state.timerLogs].slice(0, 500),
    })),
  setTimerSummary: (summary) => set({ timerSummary: summary }),
  setWatcherTrackers: (watcherTrackers) => set({ watcherTrackers }),
  setQbitCategories: (qbitCategories) => set({ qbitCategories }),
  setWatchers: (watchers) => set({ watchers }),
  setWatcherItems: (watcherItems) => set({ watcherItems }),
  setWatcherSummary: (watcherSummary) => set({ watcherSummary }),
  selectHash: (hash) => set({ selectedHash: hash }),
  setLoopForm: (partial) =>
    set((state) => ({
      loopForm: { ...state.loopForm, ...partial },
    })),
}));
