import { create } from 'zustand';
import type { Project, GenerationRecord, OptimizeParams, GenerateParams, OptimizeResult, Industry, MediaReference } from '../types';
import * as api from '../api';
import { useAuthStore } from './useAuthStore';

const emptyRecordsPage = (): api.GenerationRecordPageListOut => ({
  page: 1,
  pageSize: 10,
  total: 0,
  items: [],
});

interface AppState {
  projects: Project[];
  records: api.GenerationRecordPageListOut;
  loading: boolean;

  fetchProjects: () => Promise<void>;
  createProject: (name: string, industry: Industry) => Promise<Project>;
  deleteProject: (id: string) => Promise<void>;

  fetchRecords: (params?: api.GetRecordsPageParams) => Promise<void>;
  optimizePrompt: (projectId: string, params: OptimizeParams) => Promise<OptimizeResult>;
  generateVideo: (recordId: string, params: GenerateParams) => Promise<GenerationRecord>;
  updateRecordReferences: (recordId: string, references: MediaReference[]) => void;
}

export const useAppStore = create<AppState>((set, get) => ({
  projects: [],
  records: emptyRecordsPage(),
  loading: false,

  fetchProjects: async () => {
    set({ loading: true });
    try {
      const projects = await api.getProjects();
      set({ projects, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  createProject: async (name, industry) => {
    const project = await api.createProject(name, industry);
    set({ projects: [project, ...get().projects] });
    return project;
  },

  deleteProject: async (id) => {
    await api.deleteProject(id);
    set({ projects: get().projects.filter((p) => p.id !== id) });
  },

  fetchRecords: async (params = {}) => {
    set({ loading: true });
    try {
      const records = await api.getRecordsPage(params);
      set({ records, loading: false });
    } catch {
      set({ loading: false });
    }
  },

  optimizePrompt: async (projectId, params) => {
    const result = await api.optimizePrompt(projectId, params);
    try { await useAuthStore.getState().checkAuth(); } catch { /* */ }

    const currentRecords = get().records;
    set({
      records: {
        ...currentRecords,
        total: currentRecords.total + 1,
        items: [result.record, ...currentRecords.items],
      },
    });
    return result;
  },

  generateVideo: async (recordId, params) => {
    const record = await api.generateVideo(recordId, params);
    try { await useAuthStore.getState().checkAuth(); } catch { /* */ }

    const currentRecords = get().records;
    set({
      records: {
        ...currentRecords,
        items: currentRecords.items.map((r) => (r.id === recordId ? record : r)),
      },
    });
    return record;
  },

  updateRecordReferences: (recordId, references) => {
    const currentRecords = get().records;
    set({
      records: {
        ...currentRecords,
        items: currentRecords.items.map((r) => (r.id === recordId ? { ...r, references } : r)),
      },
    });
  },
}));
