import { create } from "zustand";
import {
  type ColumnMetadata,
  type PipelineCondition,
  type PipelineRequest,
  type PipelineResult,
} from "@/app/lib/api";

export type PipelineHistoryItem = {
  id: string;
  request: PipelineRequest;
  result?: PipelineResult;
  error?: string;
  timestamp: Date;
  duration?: number;
};

type PipelinesState = {
  activeTab: string;
  pipelineName: string;
  sourceTable: string;
  sourceColumns: string;
  sourceLimit: string;
  conditions: PipelineCondition[];
  condCol: string;
  condVal: string;
  groupBy: string;
  timeGranularity: string;
  aggColumn: string;
  aggStrategy: string;
  sinkTable: string;
  running: boolean;
  lastResult: PipelineResult | null;
  lastError: string | null;
  history: PipelineHistoryItem[];
  jsonBody: string;
  sourceTableColumns: ColumnMetadata[];
  columnsLoading: boolean;
};

type PipelinesActions = {
  setState: (patch: Partial<PipelinesState>) => void;
  setConditions: (
    updater:
      | PipelineCondition[]
      | ((prev: PipelineCondition[]) => PipelineCondition[]),
  ) => void;
  addCondition: () => void;
  setRunning: (running: boolean) => void;
  clearRunResult: () => void;
  recordSuccess: (
    request: PipelineRequest,
    result: PipelineResult,
    duration: number,
  ) => void;
  recordError: (request: PipelineRequest, error: string, duration: number) => void;
};

const HISTORY_LIMIT = 20;

const initialState: PipelinesState = {
  activeTab: "builder",
  pipelineName: "",
  sourceTable: "",
  sourceColumns: "",
  sourceLimit: "",
  conditions: [],
  condCol: "",
  condVal: "",
  groupBy: "",
  timeGranularity: "",
  aggColumn: "",
  aggStrategy: "",
  sinkTable: "",
  running: false,
  lastResult: null,
  lastError: null,
  history: [],
  jsonBody: "{\n  \n}",
  sourceTableColumns: [],
  columnsLoading: false,
};

export const usePipelinesStore = create<PipelinesState & PipelinesActions>()(
  (set, get) => ({
    ...initialState,

    setState: (patch) => set((state) => ({ ...state, ...patch })),

    setConditions: (updater) =>
      set((state) => ({
        conditions:
          typeof updater === "function"
            ? updater(state.conditions)
            : updater,
      })),

    addCondition: () => {
      const { condCol, condVal } = get();
      const nextCol = condCol.trim();
      const nextVal = condVal.trim();
      if (!nextCol || !nextVal) {
        return;
      }
      set((state) => ({
        conditions: [
          ...state.conditions,
          { eq_column: nextCol, eq_value: nextVal },
        ],
        condCol: "",
        condVal: "",
      }));
    },

    setRunning: (running) => set({ running }),

    clearRunResult: () => set({ lastResult: null, lastError: null }),

    recordSuccess: (request, result, duration) =>
      set((state) => ({
        lastResult: result,
        lastError: null,
        history: [
          {
            id: crypto.randomUUID(),
            request,
            result,
            timestamp: new Date(),
            duration,
          },
          ...state.history,
        ].slice(0, HISTORY_LIMIT),
      })),

    recordError: (request, error, duration) =>
      set((state) => ({
        lastResult: null,
        lastError: error,
        history: [
          {
            id: crypto.randomUUID(),
            request,
            error,
            timestamp: new Date(),
            duration,
          },
          ...state.history,
        ].slice(0, HISTORY_LIMIT),
      })),
  }),
);
