import { api } from '@/services/api'

export interface Customer {
  id: number
  name: string
  email: string | null
  phone: string | null
  address: string | null
  status: string
  portal_account?: {
    id: number
    name: string
    email: string
    status: string
    last_login_at: string | null
  } | null
}

export interface CustomerPortalAccount {
  id: number
  name: string
  email: string
  status: string
  customer: Pick<Customer, 'id' | 'name' | 'email' | 'phone'>
  company: {
    id: number
    name: string
    slug: string
  }
  last_login_at: string | null
}

export interface InvoiceItem {
  id?: number
  description: string
  quantity: number | string
  unit_price: number | string
  tax_rate?: number | string
  tax_amount?: string
  discount_amount?: number | string
  line_total?: string
}

export interface Invoice {
  id: number
  invoice_number: string
  customer?: Pick<Customer, 'id' | 'name' | 'email' | 'phone'> | null
  issue_date: string
  due_date: string | null
  subtotal: string
  tax_total: string
  discount_total: string
  total: string
  paid_total: string
  due_total: string
  status: string
  notes: string | null
  items?: InvoiceItem[]
  payments?: Array<{
    id: number
    financial_account?: {
      id: number
      name: string
      type: string
    } | null
    amount: string
    payment_method: string
    reference: string | null
    paid_at: string
    note: string | null
  }>
}

export interface StoreCustomerPayload {
  name: string
  email?: string
  phone?: string
  address?: string
  status?: string
}

export interface UpdateCustomerPayload {
  name?: string
  email?: string | null
  phone?: string | null
  address?: string | null
  status?: string
}

export interface SaveCustomerPortalAccountPayload {
  name?: string
  email: string
  password?: string
  status?: 'active' | 'inactive'
}

export interface StoreInvoicePayload {
  customer_id?: number
  issue_date: string
  due_date?: string
  status?: 'draft' | 'sent'
  notes?: string
  items: Array<{
    description: string
    quantity: number
    unit_price: number
    tax_rate?: number
    discount_amount?: number
  }>
}

export interface UpdateInvoicePayload {
  status?: 'draft' | 'sent' | 'cancelled'
  notes?: string | null
}

export interface InvoiceFilters {
  search?: string
  status?: string
  date_from?: string
  date_to?: string
  page?: number
  per_page?: number
}

export interface PaginationMeta {
  current_page: number
  from: number | null
  last_page: number
  per_page: number
  to: number | null
  total: number
}

export interface Paginated<T> {
  data: T[]
  meta: PaginationMeta
}

export const invoiceService = {
  async customers() {
    const { data } = await api.get<{ data: Customer[] }>('/customers')

    return data.data
  },

  async createCustomer(payload: StoreCustomerPayload) {
    const { data } = await api.post<{ data: Customer }>('/customers', payload)

    return data.data
  },

  async updateCustomer(customer: Customer, payload: UpdateCustomerPayload) {
    const { data } = await api.patch<{ data: Customer }>(`/customers/${customer.id}`, payload)

    return data.data
  },

  async customerPortalAccount(customer: Customer) {
    const { data } = await api.get<{ data: CustomerPortalAccount }>(`/customers/${customer.id}/portal-account`)

    return data.data
  },

  async saveCustomerPortalAccount(customer: Customer, payload: SaveCustomerPortalAccountPayload) {
    const { data } = await api.put<{ data: CustomerPortalAccount }>(`/customers/${customer.id}/portal-account`, payload)

    return data.data
  },

  async revokeCustomerPortalSessions(customer: Customer) {
    const { data } = await api.post<{ data: CustomerPortalAccount }>(`/customers/${customer.id}/portal-account/revoke-tokens`)

    return data.data
  },

  async invoices(filters: InvoiceFilters = {}) {
    const { data } = await api.get<{ data: Invoice[] }>('/invoices', {
      params: filters,
    })

    return data.data
  },

  async paginatedInvoices(filters: InvoiceFilters = {}) {
    const { data } = await api.get<{ data: Paginated<Invoice> }>('/invoices', {
      params: filters,
    })

    return data.data
  },

  async createInvoice(payload: StoreInvoicePayload) {
    const { data } = await api.post<{ data: Invoice }>('/invoices', payload)

    return data.data
  },

  async updateInvoice(invoice: Invoice, payload: UpdateInvoicePayload) {
    const { data } = await api.patch<{ data: Invoice }>(`/invoices/${invoice.id}`, payload)

    return data.data
  },

  async invoice(invoice: Invoice) {
    const { data } = await api.get<{ data: Invoice }>(`/invoices/${invoice.id}`)

    return data.data
  },

  async exportInvoiceHtml(invoice: Invoice) {
    const { data } = await api.get<Blob>(`/invoices/${invoice.id}/export/html`, {
      responseType: 'blob',
    })

    return data
  },

  async recordPayment(invoice: Invoice, amount: number, financialAccountId?: number) {
    const { data } = await api.post<{ data: Invoice }>(`/invoices/${invoice.id}/payments`, {
      financial_account_id: financialAccountId,
      amount,
      payment_method: 'cash',
      paid_at: new Date().toISOString().slice(0, 10),
    })

    return data.data
  },
}
