"use client"

import { createContext, useContext, useState, type ReactNode } from "react"
import type { Project, StackCategory } from "./types"
import { mockProjects, mockStackCategories } from "./mock-data"

interface DataStore {
  projects: Project[]
  stackCategories: StackCategory[]
  // Project CRUD
  addProject: (project: Omit<Project, "id">) => void
  updateProject: (id: string, project: Partial<Project>) => void
  deleteProject: (id: string) => void
  // Stack CRUD
  addStackCategory: (category: Omit<StackCategory, "id">) => void
  updateStackCategory: (id: string, category: Partial<StackCategory>) => void
  deleteStackCategory: (id: string) => void
}

const DataStoreContext = createContext<DataStore | null>(null)

export function DataStoreProvider({ children }: { children: ReactNode }) {
  const [projects, setProjects] = useState<Project[]>(mockProjects)
  const [stackCategories, setStackCategories] = useState<StackCategory[]>(mockStackCategories)

  const addProject = (project: Omit<Project, "id">) => {
    const newProject = { ...project, id: crypto.randomUUID() }
    setProjects((prev) => [...prev, newProject])
  }

  const updateProject = (id: string, updates: Partial<Project>) => {
    setProjects((prev) => prev.map((p) => (p.id === id ? { ...p, ...updates } : p)))
  }

  const deleteProject = (id: string) => {
    setProjects((prev) => prev.filter((p) => p.id !== id))
  }

  const addStackCategory = (category: Omit<StackCategory, "id">) => {
    const newCategory = { ...category, id: crypto.randomUUID() }
    setStackCategories((prev) => [...prev, newCategory])
  }

  const updateStackCategory = (id: string, updates: Partial<StackCategory>) => {
    setStackCategories((prev) => prev.map((c) => (c.id === id ? { ...c, ...updates } : c)))
  }

  const deleteStackCategory = (id: string) => {
    setStackCategories((prev) => prev.filter((c) => c.id !== id))
  }

  return (
    <DataStoreContext.Provider
      value={{
        projects,
        stackCategories,
        addProject,
        updateProject,
        deleteProject,
        addStackCategory,
        updateStackCategory,
        deleteStackCategory,
      }}
    >
      {children}
    </DataStoreContext.Provider>
  )
}

export function useDataStore() {
  const context = useContext(DataStoreContext)
  if (!context) {
    throw new Error("useDataStore must be used within a DataStoreProvider")
  }
  return context
}
