export interface ProjectMember {
  id: number
  name: string
  email: string
  role: string
  hasLoggedIn: boolean
  color: string | null
  avatarUrl: string | null
}

export interface AppUser {
  id: number
  name: string
  color: string | null
  avatarUrl: string | null
}

export interface Task {
  id: number
  todoListId?: number
  title: string
  description: string | null
  position: number
  status: 'ouverte' | 'terminee'
  completedAt: string | null
  startDate: string | null
  dueDate: string | null
  assignedUsers: { id: number; name: string; color: string | null; avatarUrl: string | null }[]
}

export interface TaskComment {
  id: number
  content: string
  author: { id: number; name: string }
  createdAt: string
}

export interface TaskAttachment {
  id: number
  filename: string
  mimeType: string
  size: number
  uploadedBy: { id: number; name: string }
  createdAt: string
}

export interface ProjectAttachment {
  id: number
  filename: string
  mimeType: string
  size: number
  uploadedBy: { id: number; name: string }
  createdAt: string
}

export interface TaskChecklistItem {
  id: number
  taskId: number
  label: string
  done: boolean
  position: number
  createdAt: string
}

export interface DashboardTask {
  id: number
  title: string
  status: 'ouverte' | 'terminee'
  startDate: string | null
  dueDate: string | null
  assignedUserIds: number[]
  assignedUsers: AppUser[]
  projectId: number
  projectName: string
  projectColor: string | null
  projectStartDate: string | null
  projectDueDate: string | null
}

export interface TodoList {
  id: number
  name: string
  position: number
  archivedAt: string | null
  tasks: Task[]
}

export interface Project {
  id: number
  name: string
  description: string | null
  startDate: string | null
  dueDate: string | null
  color: string | null
  createdAt: string
  archivedAt: string | null
  todoListsCount: number
  openTasksCount: number
  completedTasksCount: number
  owner: { id: number; name: string; email: string }
  members: ProjectMember[]
  todoLists?: TodoList[]
}

export const useProjectsStore = defineStore('projects', {
  state: () => ({
    projects: [] as Project[],
    archivedProjects: [] as Project[],
    current: null as Project | null,
    dashboardTasks: [] as DashboardTask[]
  }),
  actions: {
    async fetchAllUsers() {
      const { request } = useApi()
      return request<AppUser[]>('/api/users')
    },
    async fetchAll() {
      const { request } = useApi()
      this.projects = await request<Project[]>('/api/projects')
    },
    async fetchArchived() {
      const { request } = useApi()
      this.archivedProjects = await request<Project[]>('/api/projects?archived=1')
    },
    async setArchived(id: number, archived: boolean) {
      const { request } = useApi()
      const updated = await request<Project>(`/api/projects/${id}`, { method: 'PUT', body: { archived } })
      this.projects = this.projects.filter((p) => p.id !== id)
      this.archivedProjects = this.archivedProjects.filter((p) => p.id !== id)
      if (archived) {
        this.archivedProjects.unshift(updated)
      } else {
        this.projects.unshift(updated)
      }
      if (this.current?.id === id) this.current.archivedAt = updated.archivedAt
    },
    async fetchDashboardTasks() {
      const { request } = useApi()
      this.dashboardTasks = await request<DashboardTask[]>('/api/dashboard/tasks')
    },
    async create(payload: { name: string; description?: string; startDate?: string; dueDate?: string; color?: string }) {
      const { request } = useApi()
      const project = await request<Project>('/api/projects', { method: 'POST', body: payload })
      this.projects.unshift(project)
      return project
    },
    async updateName(id: number, name: string) {
      const { request } = useApi()
      const updated = await request<Project>(`/api/projects/${id}`, { method: 'PUT', body: { name } })
      const idx = this.projects.findIndex((p) => p.id === id)
      if (idx !== -1) this.projects[idx] = { ...this.projects[idx], name: updated.name }
      if (this.current?.id === id) this.current.name = updated.name
    },
    async updateColor(id: number, color: string) {
      const { request } = useApi()
      const updated = await request<Project>(`/api/projects/${id}`, { method: 'PUT', body: { color } })
      const idx = this.projects.findIndex((p) => p.id === id)
      if (idx !== -1) this.projects[idx] = { ...this.projects[idx], color: updated.color }
      if (this.current?.id === id) this.current.color = updated.color
    },
    async updateStartDate(id: number, startDate: string | null) {
      const { request } = useApi()
      const updated = await request<Project>(`/api/projects/${id}`, { method: 'PUT', body: { startDate } })
      const idx = this.projects.findIndex((p) => p.id === id)
      if (idx !== -1) this.projects[idx] = { ...this.projects[idx], startDate: updated.startDate }
      if (this.current?.id === id) this.current.startDate = updated.startDate
    },
    async updateDueDate(id: number, dueDate: string | null) {
      const { request } = useApi()
      const updated = await request<Project>(`/api/projects/${id}`, { method: 'PUT', body: { dueDate } })
      const idx = this.projects.findIndex((p) => p.id === id)
      if (idx !== -1) this.projects[idx] = { ...this.projects[idx], dueDate: updated.dueDate }
      if (this.current?.id === id) this.current.dueDate = updated.dueDate
    },
    async remove(id: number) {
      const { request } = useApi()
      await request(`/api/projects/${id}`, { method: 'DELETE' })
      this.projects = this.projects.filter((p) => p.id !== id)
    },
    async fetchOne(id: number) {
      const { request } = useApi()
      this.current = await request<Project>(`/api/projects/${id}`)
      return this.current
    },
    async invite(projectId: number, email: string) {
      const { request } = useApi()
      const result = await request<{ members: ProjectMember[] }>(`/api/projects/${projectId}/invite`, {
        method: 'POST',
        body: { email }
      })
      if (this.current) this.current.members = result.members
    },
    async addMember(projectId: number, userId: number) {
      const { request } = useApi()
      const result = await request<{ members: ProjectMember[] }>(`/api/projects/${projectId}/members/${userId}`, {
        method: 'POST'
      })
      if (this.current) this.current.members = result.members
    },
    async resendInvite(projectId: number, userId: number) {
      const { request } = useApi()
      await request(`/api/projects/${projectId}/members/${userId}/resend-invite`, { method: 'POST' })
    },
    async removeMember(projectId: number, userId: number) {
      const { request } = useApi()
      await request(`/api/projects/${projectId}/members/${userId}`, { method: 'DELETE' })
      if (this.current) {
        this.current.members = this.current.members.filter((m) => m.id !== userId)
      }
    },
    async createTodoList(projectId: number, name: string) {
      const { request } = useApi()
      const list = await request<TodoList>(`/api/projects/${projectId}/todo-lists`, {
        method: 'POST',
        body: { name }
      })
      this.current?.todoLists?.push({ ...list, tasks: [] })
    },
    async renameTodoList(id: number, name: string) {
      const { request } = useApi()
      await request(`/api/todo-lists/${id}/rename`, { method: 'PUT', body: { name } })
      const list = this.current?.todoLists?.find((l) => l.id === id)
      if (list) list.name = name
    },
    async setTodoListArchived(id: number, archived: boolean) {
      const { request } = useApi()
      const updated = await request<{ id: number; archivedAt: string | null }>(`/api/todo-lists/${id}/archive`, {
        method: 'PUT',
        body: { archived }
      })
      const list = this.current?.todoLists?.find((l) => l.id === id)
      if (list) list.archivedAt = updated.archivedAt
    },
    async reorderTodoList(id: number, position: number) {
      const { request } = useApi()
      await request(`/api/todo-lists/${id}/reorder`, { method: 'PUT', body: { position } })
    },
    async deleteTodoList(id: number) {
      const { request } = useApi()
      await request(`/api/todo-lists/${id}`, { method: 'DELETE' })
      if (this.current?.todoLists) {
        this.current.todoLists = this.current.todoLists.filter((l) => l.id !== id)
      }
    },
    async createTask(todoListId: number, title: string) {
      const { request } = useApi()
      const task = await request<Task>(`/api/todo-lists/${todoListId}/tasks`, {
        method: 'POST',
        body: { title }
      })
      const list = this.current?.todoLists?.find((l) => l.id === todoListId)
      list?.tasks.push(task)
    },
    async updateTask(taskId: number, payload: Partial<Pick<Task, 'title' | 'description' | 'startDate' | 'dueDate' | 'status' | 'completedAt'>>) {
      const { request } = useApi()
      const updated = await request<Task>(`/api/tasks/${taskId}`, { method: 'PUT', body: payload })
      this.patchTaskInPlace(updated)
    },
    async assignTask(taskId: number, assignedUserIds: number[]) {
      const { request } = useApi()
      const updated = await request<Task>(`/api/tasks/${taskId}/assign`, {
        method: 'PUT',
        body: { assignedUserIds }
      })
      this.patchTaskInPlace(updated)
    },
    async moveTask(taskId: number, todoListId: number, position: number) {
      const { request } = useApi()
      const updated = await request<Task>(`/api/tasks/${taskId}/move`, {
        method: 'PUT',
        body: { todoListId, position }
      })
      this.current?.todoLists?.forEach((l) => {
        l.tasks = l.tasks.filter((t) => t.id !== taskId)
      })
      const targetList = this.current?.todoLists?.find((l) => l.id === updated.todoListId)
      if (targetList) {
        const idx = Math.max(0, Math.min(updated.position, targetList.tasks.length))
        targetList.tasks.splice(idx, 0, updated)
      }
    },
    async deleteTask(taskId: number) {
      const { request } = useApi()
      await request(`/api/tasks/${taskId}`, { method: 'DELETE' })
      this.current?.todoLists?.forEach((l) => {
        l.tasks = l.tasks.filter((t) => t.id !== taskId)
      })
    },
    async fetchComments(taskId: number) {
      const { request } = useApi()
      return request<TaskComment[]>(`/api/tasks/${taskId}/comments`)
    },
    async addComment(taskId: number, content: string) {
      const { request } = useApi()
      return request<TaskComment>(`/api/tasks/${taskId}/comments`, { method: 'POST', body: { content } })
    },
    async updateComment(commentId: number, content: string) {
      const { request } = useApi()
      return request<TaskComment>(`/api/comments/${commentId}`, { method: 'PATCH', body: { content } })
    },
    async deleteComment(commentId: number) {
      const { request } = useApi()
      await request(`/api/comments/${commentId}`, { method: 'DELETE' })
    },
    async fetchAttachments(taskId: number) {
      const { request } = useApi()
      return request<TaskAttachment[]>(`/api/tasks/${taskId}/attachments`)
    },
    async uploadAttachment(taskId: number, file: File) {
      const { request } = useApi()
      const body = new FormData()
      body.append('file', file)
      return request<TaskAttachment>(`/api/tasks/${taskId}/attachments`, { method: 'POST', body })
    },
    async deleteAttachment(attachmentId: number) {
      const { request } = useApi()
      await request(`/api/attachments/${attachmentId}`, { method: 'DELETE' })
    },
    async fetchProjectAttachments(projectId: number) {
      const { request } = useApi()
      return request<ProjectAttachment[]>(`/api/projects/${projectId}/attachments`)
    },
    async uploadProjectAttachment(projectId: number, file: File) {
      const { request } = useApi()
      const body = new FormData()
      body.append('file', file)
      return request<ProjectAttachment>(`/api/projects/${projectId}/attachments`, { method: 'POST', body })
    },
    async deleteProjectAttachment(attachmentId: number) {
      const { request } = useApi()
      await request(`/api/project-attachments/${attachmentId}`, { method: 'DELETE' })
    },
    async fetchChecklistItems(taskId: number) {
      const { request } = useApi()
      return request<TaskChecklistItem[]>(`/api/tasks/${taskId}/checklist-items`)
    },
    async addChecklistItem(taskId: number, label: string) {
      const { request } = useApi()
      return request<TaskChecklistItem>(`/api/tasks/${taskId}/checklist-items`, { method: 'POST', body: { label } })
    },
    async updateChecklistItem(itemId: number, payload: Partial<Pick<TaskChecklistItem, 'label' | 'done'>>) {
      const { request } = useApi()
      return request<TaskChecklistItem>(`/api/checklist-items/${itemId}`, { method: 'PUT', body: payload })
    },
    async deleteChecklistItem(itemId: number) {
      const { request } = useApi()
      await request(`/api/checklist-items/${itemId}`, { method: 'DELETE' })
    },
    async reorderChecklistItems(taskId: number, orderedIds: number[]) {
      const { request } = useApi()
      return request<TaskChecklistItem[]>(`/api/tasks/${taskId}/checklist-items/reorder`, { method: 'PUT', body: { orderedIds } })
    },
    patchTaskInPlace(updated: Task) {
      this.current?.todoLists?.forEach((l) => {
        const idx = l.tasks.findIndex((t) => t.id === updated.id)
        if (idx !== -1) {
          l.tasks[idx] = { ...l.tasks[idx], ...updated }
        }
      })
    }
  }
})
