import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { handleInvokeError } from '../utils/errorHandler'

export interface Project {
  id?: number
  client_id?: number
  name: string
  hourly_rate: number
  color: string
  archived: boolean
  budget_hours?: number | null
  budget_amount?: number | null
  rounding_override?: number | null
  timeline_override?: string | null
  notes?: string | null
  currency?: string | null
}

export interface Task {
  id?: number
  project_id: number
  name: string
  estimated_hours?: number | null
  hourly_rate?: number | null
}

export const useProjectsStore = defineStore('projects', () => {
  const projects = ref<Project[]>([])
  const loading = ref(false)

  async function fetchProjects() {
    loading.value = true
    try {
      projects.value = await invoke<Project[]>('get_projects')
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch projects', () => fetchProjects())
    } finally {
      loading.value = false
    }
  }

  async function createProject(project: Project): Promise<number | null> {
    try {
      const id = await invoke<number>('create_project', { project })
      projects.value.push({ ...project, id: Number(id) })
      return Number(id)
    } catch (error) {
      handleInvokeError(error, 'Failed to create project')
      return null
    }
  }

  async function updateProject(project: Project): Promise<boolean> {
    try {
      await invoke('update_project', { project })
      const index = projects.value.findIndex(p => p.id === project.id)
      if (index !== -1) {
        projects.value[index] = project
      }
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to update project')
      return false
    }
  }

  async function deleteProject(id: number): Promise<boolean> {
    try {
      await invoke('delete_project', { id })
      projects.value = projects.value.filter(p => p.id !== id)
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to delete project')
      return false
    }
  }

  async function fetchTasks(projectId: number): Promise<Task[]> {
    try {
      return await invoke<Task[]>('get_tasks', { projectId })
    } catch (error) {
      handleInvokeError(error, 'Failed to fetch tasks')
      return []
    }
  }

  async function createTask(task: Task): Promise<number | null> {
    try {
      return await invoke<number>('create_task', { task })
    } catch (error) {
      handleInvokeError(error, 'Failed to create task')
      return null
    }
  }

  async function deleteTask(id: number): Promise<boolean> {
    try {
      await invoke('delete_task', { id })
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to delete task')
      return false
    }
  }

  async function updateTask(task: Task): Promise<boolean> {
    try {
      await invoke('update_task', { task })
      return true
    } catch (error) {
      handleInvokeError(error, 'Failed to update task')
      return false
    }
  }

  const activeProjects = computed(() => projects.value.filter(p => !p.archived))
  const archivedProjects = computed(() => projects.value.filter(p => p.archived))

  return {
    projects,
    loading,
    activeProjects,
    archivedProjects,
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    fetchTasks,
    createTask,
    deleteTask,
    updateTask
  }
})
