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;
  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 };
}

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;
  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;
}

interface AppState {
  qbit: StatusSnapshot["qbit"];
  torrents: TorrentInfo[];
  transfer: any;
  jobs: LoopJob[];
  logs: JobLog[];
  timerRules: TimerRule[];
  timerLogs: TimerLog[];
  timerSummary: TimerSummary | 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;
  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,
  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 }),
  selectHash: (hash) => set({ selectedHash: hash }),
  setLoopForm: (partial) =>
    set((state) => ({
      loopForm: { ...state.loopForm, ...partial },
    })),
}));
