import { api } from '../api'

export interface Contact {
  id: string
  uniqueContactId: string
  type: string
  name: string
  nameAr?: string
  email?: string
  phone?: string
  mobile?: string
  website?: string
  companyName?: string
  companyNameAr?: string
  taxNumber?: string
  commercialRegister?: string
  address?: string
  city?: string
  country?: string
  postalCode?: string
  status: string
  rating?: number
  source: string
  tags?: string[]
  customFields?: any
  categories?: any[]
  parent?: any
  parentId?: string
  employeeId?: string | null
  employee?: { id: string; firstName: string; lastName: string; email: string; uniqueEmployeeId?: string }
  createdAt: string
  updatedAt: string
  createdBy?: any
}

export interface CreateContactData {
  type: string
  name: string
  nameAr?: string
  email?: string
  phone?: string
  mobile?: string
  website?: string
  companyName?: string
  companyNameAr?: string
  taxNumber?: string
  commercialRegister?: string
  address?: string
  city?: string
  country?: string
  postalCode?: string
  categories?: string[]
  tags?: string[]
  parentId?: string
  employeeId?: string | null
  source: string
  customFields?: any
}

export interface UpdateContactData extends Partial<CreateContactData> {
  status?: string
  rating?: number
}

export interface ContactFilters {
  search?: string
  type?: string
  status?: string
  category?: string
  source?: string
  rating?: number
  page?: number
  pageSize?: number
  excludeSuppliers?: boolean
}

export interface ContactsResponse {
  contacts: Contact[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export const contactsAPI = {
  // Get all contacts with filters and pagination
  getAll: async (filters: ContactFilters = {}): Promise<ContactsResponse> => {
    const params = new URLSearchParams()
    if (filters.search) params.append('search', filters.search)
    if (filters.type) params.append('type', filters.type)
    if (filters.status) params.append('status', filters.status)
    if (filters.category) params.append('category', filters.category)
    if (filters.source) params.append('source', filters.source)
    if (filters.rating) params.append('rating', filters.rating.toString())
    if (filters.page) params.append('page', filters.page.toString())
    if (filters.pageSize) params.append('pageSize', filters.pageSize.toString())
    if (filters.excludeSuppliers) params.append('excludeSuppliers', 'true')

    const response = await api.get(`/contacts?${params.toString()}`)
    const { data, pagination } = response.data
    return {
      contacts: data || [],
      total: pagination?.total || 0,
      page: pagination?.page || 1,
      pageSize: pagination?.pageSize || 20,
      totalPages: pagination?.totalPages || 0,
    }
  },

  // Get single contact by ID
  getById: async (id: string): Promise<Contact> => {
    const response = await api.get(`/contacts/${id}`)
    return response.data.data
  },

  // Create new contact
  create: async (data: CreateContactData): Promise<Contact> => {
    const response = await api.post('/contacts', data)
    return response.data.data
  },

  // Update existing contact
  update: async (id: string, data: UpdateContactData): Promise<Contact> => {
    const response = await api.put(`/contacts/${id}`, data)
    return response.data.data
  },

  // Archive contact (soft delete)
  archive: async (id: string, reason?: string): Promise<Contact> => {
    const response = await api.post(`/contacts/${id}/archive`, { reason })
    return response.data.data
  },

  // Delete contact (hard delete)
  delete: async (id: string, reason: string): Promise<void> => {
    await api.delete(`/contacts/${id}`, { data: { reason } })
  },

  // Get contact history
  getHistory: async (id: string): Promise<any[]> => {
    const response = await api.get(`/contacts/${id}/history`)
    return response.data.data
  },

  // Merge contacts
  merge: async (sourceId: string, targetId: string, reason: string): Promise<Contact> => {
    const response = await api.post('/contacts/merge', { sourceId, targetId, reason })
    return response.data.data
  },

  // Export contacts
  export: async (filters: ContactFilters & { excludeCompanyEmployees?: boolean } = {}): Promise<Blob> => {
    const params = new URLSearchParams()
    if (filters.search) params.append('search', filters.search)
    if (filters.type) params.append('type', filters.type)
    if (filters.status) params.append('status', filters.status)
    if (filters.category) params.append('category', filters.category)
    if (filters.excludeCompanyEmployees) params.append('excludeCompanyEmployees', 'true')
    if (filters.excludeSuppliers) params.append('excludeSuppliers', 'true')

    const response = await api.get(`/contacts/export?${params.toString()}`, {
      responseType: 'blob'
    })
    return response.data
  },

  // Import contacts
  import: async (file: File): Promise<{ 
    success: number
    failed: number
    duplicates: number
    errors: Array<{ row: number; field: string; message: string; data?: any }>
  }> => {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await api.post('/contacts/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data.data
  },

  // Check for duplicates
  checkDuplicates: async (data: {
    email?: string
    phone?: string
    mobile?: string
    taxNumber?: string
    commercialRegister?: string
    excludeId?: string
  }): Promise<Contact[]> => {
    const response = await api.post('/contacts/check-duplicates', data)
    return response.data.data
  },

  // Relationship management
  getRelationships: async (contactId: string): Promise<any[]> => {
    const response = await api.get(`/contacts/${contactId}/relationships`)
    return response.data.data
  },

  addRelationship: async (contactId: string, data: {
    toContactId: string
    type: string
    startDate: string
    endDate?: string
    notes?: string
  }): Promise<any> => {
    const response = await api.post(`/contacts/${contactId}/relationships`, data)
    return response.data.data
  },

  updateRelationship: async (contactId: string, relationshipId: string, data: {
    type?: string
    startDate?: string
    endDate?: string
    notes?: string
    isActive?: boolean
  }): Promise<any> => {
    const response = await api.put(`/contacts/${contactId}/relationships/${relationshipId}`, data)
    return response.data.data
  },

  deleteRelationship: async (contactId: string, relationshipId: string): Promise<void> => {
    await api.delete(`/contacts/${contactId}/relationships/${relationshipId}`)
  }
}

