import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { z } from 'zod'
import { api } from '../client'
import type { WorkspaceWithMeta, WorkspaceMember } from '../../types/api'

// ── Schemas ───────────────────────────────────────────────────────────────────

const wsSchema = z.object({
  id: z.number(),
  handle: z.string(),
  displayName: z.string(),
  description: z.string(),
  avatarUrl: z.string(),
  createdBy: z.number(),
  createdAt: z.string(),
  updatedAt: z.string(),
  memberCount: z.number(),
  repoCount: z.number(),
  myRole: z.string(),
})

const memberSchema = z.object({
  id: z.number(),
  workspaceId: z.number(),
  userId: z.number(),
  username: z.string(),
  role: z.enum(['owner', 'admin', 'member']),
  addedAt: z.string(),
})

// WorkspaceRepo — raw repo as returned by the workspace list endpoint
export interface WorkspaceRepo {
  id: number
  ownerId: number
  workspaceId?: number | null
  ownerName: string
  name: string
  description: string
  isPrivate: boolean
  defaultBranch: string
  createdAt: string
  updatedAt: string
}

const repoSchema = z.object({
  id: z.number(),
  ownerId: z.number(),
  workspaceId: z.number().nullable().optional(),
  ownerName: z.string(),
  name: z.string(),
  description: z.string(),
  isPrivate: z.boolean(),
  defaultBranch: z.string(),
  createdAt: z.string(),
  updatedAt: z.string(),
})

// ── Queries ───────────────────────────────────────────────────────────────────

export function useWorkspaces() {
  return useQuery({
    queryKey: ['workspaces'],
    queryFn: () => api.get<WorkspaceWithMeta[]>('/api/v1/workspaces', z.array(wsSchema)),
  })
}

export function useWorkspace(handle: string) {
  return useQuery({
    queryKey: ['workspaces', handle],
    queryFn: () => api.get<WorkspaceWithMeta>(`/api/v1/workspaces/${handle}`, wsSchema),
    enabled: Boolean(handle),
  })
}

export function useWorkspaceMembers(handle: string) {
  return useQuery({
    queryKey: ['workspaces', handle, 'members'],
    queryFn: () =>
      api.get<WorkspaceMember[]>(`/api/v1/workspaces/${handle}/members`, z.array(memberSchema)),
    enabled: Boolean(handle),
  })
}

export function useWorkspaceRepos(handle: string) {
  return useQuery({
    queryKey: ['workspaces', handle, 'repos'],
    queryFn: () =>
      api.get<WorkspaceRepo[]>(`/api/v1/workspaces/${handle}/repos`, z.array(repoSchema)),
    enabled: Boolean(handle),
  })
}

// ── Mutations ─────────────────────────────────────────────────────────────────

export function useCreateWorkspace() {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { handle: string; displayName?: string; description?: string }) =>
      api.post<WorkspaceWithMeta>('/api/v1/workspaces', wsSchema, body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces'] }),
  })
}

export function useUpdateWorkspace(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { displayName?: string; description?: string }) =>
      api.patch<WorkspaceWithMeta>(`/api/v1/workspaces/${handle}`, wsSchema, body),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ['workspaces'] })
      qc.invalidateQueries({ queryKey: ['workspaces', handle] })
    },
  })
}

export function useDeleteWorkspace(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: () =>
      api.delete<void>(`/api/v1/workspaces/${handle}`, z.unknown() as z.ZodType<void>),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces'] }),
  })
}

export function useAddWorkspaceMember(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (body: { username: string; role: string }) =>
      api.post<WorkspaceMember>(`/api/v1/workspaces/${handle}/members`, memberSchema, body),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
  })
}

export function useUpdateWorkspaceMember(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: ({ username, role }: { username: string; role: string }) =>
      api.patch<WorkspaceMember>(
        `/api/v1/workspaces/${handle}/members/${username}`,
        memberSchema,
        { role },
      ),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
  })
}

export function useRemoveWorkspaceMember(handle: string) {
  const qc = useQueryClient()
  return useMutation({
    mutationFn: (username: string) =>
      api.delete<void>(
        `/api/v1/workspaces/${handle}/members/${username}`,
        z.unknown() as z.ZodType<void>,
      ),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['workspaces', handle, 'members'] }),
  })
}
