import { create } from 'zustand';

export interface Project {
  id: string;
  name: string;
  description?: string;
  status: 'Ready' | 'Parsing' | 'Error';
  fps?: string;
  frames?: number;
  thumbnail?: string;
  createdAt?: string;
  updatedAt?: string;
}

export interface Frame {
  id: string;
  projectId: string;
  index: number;
  url: string;
  width: number;
  height: number;
  timestamp?: string;
}

export interface Annotation {
  id: string;
  frameId: string;
  type: 'polygon' | 'rectangle' | 'circle' | 'point' | 'mask';
  points: number[];
  label: string;
  color: string;
  zIndex?: number;
  confidence?: number;
  metadata?: Record<string, unknown>;
}

export interface Mask {
  id: string;
  frameId: string;
  pathData: string;
  label: string;
  color: string;
  opacity?: number;
  segmentation?: number[][];
  bbox?: [number, number, number, number];
  area?: number;
}

export interface Template {
  id: string;
  name: string;
  description?: string;
  classes: TemplateClass[];
  rules?: TemplateRule[];
  createdAt?: string;
  updatedAt?: string;
}

export interface TemplateClass {
  id: string;
  name: string;
  color: string;
  zIndex: number;
  category?: string;
  description?: string;
}

export interface TemplateRule {
  id: string;
  name: string;
  sourceKey: string;
  targetKey: string;
  operation: string;
}

export interface AppState {
  // Auth
  isAuthenticated: boolean;
  token: string | null;
  login: (token: string) => void;
  logout: () => void;

  // Projects
  projects: Project[];
  currentProject: Project | null;
  setProjects: (projects: Project[]) => void;
  setCurrentProject: (project: Project | null) => void;
  addProject: (project: Project) => void;
  updateProject: (project: Project) => void;

  // Workspace
  activeModule: string;
  activeTool: string;
  frames: Frame[];
  currentFrameIndex: number;
  annotations: Annotation[];
  masks: Mask[];
  setActiveModule: (module: string) => void;
  setActiveTool: (tool: string) => void;
  setFrames: (frames: Frame[]) => void;
  setCurrentFrame: (index: number) => void;
  addAnnotation: (annotation: Annotation) => void;
  addMask: (mask: Mask) => void;
  clearMasks: () => void;
  removeAnnotation: (id: string) => void;

  // Templates
  templates: Template[];
  setTemplates: (templates: Template[]) => void;
  addTemplate: (template: Template) => void;
  updateTemplate: (template: Template) => void;
  removeTemplate: (id: string) => void;

  // UI
  isLoading: boolean;
  error: string | null;
  setLoading: (loading: boolean) => void;
  setError: (error: string | null) => void;
}

export const useStore = create<AppState>((set) => ({
  // Auth
  isAuthenticated: false,
  token: null,
  login: (token: string) => {
    localStorage.setItem('token', token);
    set({ isAuthenticated: true, token });
  },
  logout: () => {
    localStorage.removeItem('token');
    set({
      isAuthenticated: false,
      token: null,
      currentProject: null,
      projects: [],
      templates: [],
      frames: [],
      annotations: [],
      masks: [],
    });
  },

  // Projects
  projects: [],
  currentProject: null,
  setProjects: (projects: Project[]) => set({ projects }),
  setCurrentProject: (currentProject: Project | null) => set({ currentProject }),
  addProject: (project: Project) =>
    set((state) => ({ projects: [project, ...state.projects] })),
  updateProject: (project: Project) =>
    set((state) => ({
      projects: state.projects.map((p) => (p.id === project.id ? project : p)),
    })),

  // Workspace
  activeModule: 'workspace',
  activeTool: 'move',
  frames: [],
  currentFrameIndex: 0,
  annotations: [],
  masks: [],
  setActiveModule: (activeModule: string) => set({ activeModule }),
  setActiveTool: (activeTool: string) => set({ activeTool }),
  setFrames: (frames: Frame[]) => set({ frames }),
  setCurrentFrame: (currentFrameIndex: number) => set({ currentFrameIndex }),
  addAnnotation: (annotation: Annotation) =>
    set((state) => ({ annotations: [...state.annotations, annotation] })),
  addMask: (mask: Mask) =>
    set((state) => ({ masks: [...state.masks, mask] })),
  clearMasks: () => set({ masks: [] }),
  removeAnnotation: (id: string) =>
    set((state) => ({
      annotations: state.annotations.filter((a) => a.id !== id),
    })),

  // Templates
  templates: [],
  setTemplates: (templates: Template[]) => set({ templates }),
  addTemplate: (template: Template) =>
    set((state) => ({ templates: [...state.templates, template] })),
  updateTemplate: (template: Template) =>
    set((state) => ({
      templates: state.templates.map((t) => (t.id === template.id ? template : t)),
    })),
  removeTemplate: (id: string) =>
    set((state) => ({
      templates: state.templates.filter((t) => t.id !== id),
    })),

  // UI
  isLoading: false,
  error: null,
  setLoading: (isLoading: boolean) => set({ isLoading }),
  setError: (error: string | null) => set({ error }),
}));
