import adminClient from "./client"
import type { ApiResponse } from "../../types"
import type {
  TicketDepartment,
  TicketDetail,
  TicketActor,
  TicketMessage,
  TicketPriority,
  TicketStatus,
  TicketSummary,
  TicketAttachmentUploadResult,
} from "../../api/tickets"
import type { AdminTicketStatusGroup } from "../../utils/ticketMeta"
import { listResult } from "./response"

export interface AdminTicketUser {
  id: number
  username: string
  nickname: string | null
  email: string | null
  phone: string | null
}

export interface AdminTicketSummary extends Omit<TicketSummary, "unread_count"> {
  user: AdminTicketUser | null
  assignee: TicketActor | null
  unread_count: number
  user_unread_count: number
  closed_at: string | null
}

export interface AdminTicketDetail extends Omit<TicketDetail, "unread_count"> {
  user: AdminTicketUser | null
  assignee: TicketActor | null
  unread_count: number
  user_unread_count: number
  closed_at: string | null
  messages: TicketMessage[]
}

export interface TicketDepartmentPayload {
  code?: string | null
  name: string
  description?: string | null
  is_enabled?: boolean
  sort_order?: number
  min_member_level?: number | null
  auto_reply_enabled?: boolean
  auto_reply_content?: string | null
}

export interface AdminTicketReplyPayload {
  content: string
  attachments?: Array<Record<string, unknown>>
  is_internal?: boolean
}

export interface AdminTicketUpdatePayload {
  status?: TicketStatus
  priority?: TicketPriority
  department_id?: number | null
  assignee_id?: number | null
}

export interface AdminTicketStats {
  open?: number
  pending?: number
  processing?: number
  waiting_user?: number
  answered?: number
  resolved?: number
  closed?: number
  unread?: number
  rated_count?: number
  average_rating?: number | null
  satisfaction_1?: number
  satisfaction_2?: number
  satisfaction_3?: number
  satisfaction_4?: number
  satisfaction_5?: number
}

export interface TicketReplyTemplate {
  id: number
  title: string
  content: string
  department_id: number | null
  department_name: string | null
  is_enabled: boolean
  sort_order: number
  usage_count: number
  created_by_id: number | null
  updated_by_id: number | null
  created_at: string | null
  updated_at: string | null
}

export interface TicketReplyTemplatePayload {
  title: string
  content: string
  department_id?: number | null
  is_enabled?: boolean
  sort_order?: number
}

export async function listAdminTicketDepartments() {
  const { data } = await adminClient.get<ApiResponse<TicketDepartment[] | { items: TicketDepartment[]; total: number }>>("/v1/admin/tickets/departments")
  return { ...data, data: listResult<TicketDepartment>(data.data) }
}

export async function listAdminTicketStaff() {
  const { data } = await adminClient.get<ApiResponse<TicketActor[] | { items: TicketActor[]; total: number }>>("/v1/admin/tickets/staff")
  return { ...data, data: listResult<TicketActor>(data.data) }
}

export async function uploadAdminTicketImage(file: File) {
  const form = new FormData()
  form.append("file", file)
  const { data } = await adminClient.post<ApiResponse<TicketAttachmentUploadResult>>(
    "/v1/admin/tickets/attachments/images",
    form,
    { headers: { "Content-Type": "multipart/form-data" } },
  )
  return data
}

export async function createAdminTicketDepartment(payload: TicketDepartmentPayload) {
  const { data } = await adminClient.post<ApiResponse<TicketDepartment>>("/v1/admin/tickets/departments", payload)
  return data
}

export async function updateAdminTicketDepartment(id: number, payload: TicketDepartmentPayload) {
  const { data } = await adminClient.patch<ApiResponse<TicketDepartment>>(`/v1/admin/tickets/departments/${id}`, payload)
  return data
}

export async function deleteAdminTicketDepartment(id: number) {
  const { data } = await adminClient.delete<ApiResponse<null>>(`/v1/admin/tickets/departments/${id}`)
  return data
}

export async function getAdminTicketStats() {
  const { data } = await adminClient.get<ApiResponse<AdminTicketStats>>("/v1/admin/tickets/stats")
  return data
}

export async function listAdminTicketReplyTemplates(params?: {
  department_id?: number
  enabled_only?: boolean
  include_global?: boolean
}) {
  const { data } = await adminClient.get<ApiResponse<TicketReplyTemplate[] | { items: TicketReplyTemplate[]; total: number }>>("/v1/admin/tickets/reply-templates", { params })
  return { ...data, data: listResult<TicketReplyTemplate>(data.data) }
}

export async function createAdminTicketReplyTemplate(payload: TicketReplyTemplatePayload) {
  const { data } = await adminClient.post<ApiResponse<TicketReplyTemplate>>("/v1/admin/tickets/reply-templates", payload)
  return data
}

export async function updateAdminTicketReplyTemplate(id: number, payload: Partial<TicketReplyTemplatePayload>) {
  const { data } = await adminClient.patch<ApiResponse<TicketReplyTemplate>>(`/v1/admin/tickets/reply-templates/${id}`, payload)
  return data
}

export async function deleteAdminTicketReplyTemplate(id: number) {
  const { data } = await adminClient.delete<ApiResponse<null>>(`/v1/admin/tickets/reply-templates/${id}`)
  return data
}

export async function listAdminTickets(params?: {
  keyword?: string
  status?: TicketStatus
  status_group?: AdminTicketStatusGroup
  department_id?: number
  assignee_id?: number
  user_id?: number
  limit?: number
  offset?: number
}) {
  const { data } = await adminClient.get<ApiResponse<AdminTicketSummary[] | { items: AdminTicketSummary[]; total: number }>>("/v1/admin/tickets", { params })
  return { ...data, data: listResult<AdminTicketSummary>(data.data) }
}

export async function getAdminTicket(ticketId: number | string) {
  const { data } = await adminClient.get<ApiResponse<AdminTicketDetail>>(`/v1/admin/tickets/${ticketId}`)
  return data
}

export async function updateAdminTicket(ticketId: number | string, payload: AdminTicketUpdatePayload) {
  const { data } = await adminClient.patch<ApiResponse<AdminTicketSummary>>(`/v1/admin/tickets/${ticketId}`, payload)
  return data
}

export async function replyAdminTicket(ticketId: number | string, payload: AdminTicketReplyPayload) {
  const { data } = await adminClient.post<ApiResponse<TicketMessage>>(`/v1/admin/tickets/${ticketId}/messages`, payload)
  return data
}

export async function replyAdminTicketWithTemplate(ticketId: number | string, payload: {
  template_id: number
  is_internal?: boolean
}) {
  const { data } = await adminClient.post<ApiResponse<TicketMessage>>(`/v1/admin/tickets/${ticketId}/template-replies`, payload)
  return data
}

export async function closeAdminTicket(ticketId: number | string) {
  const { data } = await adminClient.post<ApiResponse<AdminTicketSummary>>(`/v1/admin/tickets/${ticketId}/close`)
  return data
}

export async function reopenAdminTicket(ticketId: number | string) {
  const { data } = await adminClient.post<ApiResponse<AdminTicketSummary>>(`/v1/admin/tickets/${ticketId}/reopen`)
  return data
}
