import apiClient from '../../../shared/services/apiClient';

export interface InvoiceItem {
  id: number;
  description: string;
  quantity: number;
  unit_price: number;
  tax_rate: number;
  discount_amount: number;
  line_total: number;
  room_id?: number;
  service_id?: number;
}

export interface Invoice {
  id: number;
  invoice_number: string;
  booking_id: number;
  user_id: number;
  issue_date: string;
  due_date: string;
  paid_date?: string;
  subtotal: number;
  tax_rate: number;
  tax_amount: number;
  discount_amount: number;
  total_amount: number;
  amount_paid: number;
  balance_due: number;
  amount_due?: number; // Alias for balance_due
  status: 'draft' | 'sent' | 'paid' | 'overdue' | 'cancelled';
  company_name?: string;
  company_address?: string;
  company_phone?: string;
  company_email?: string;
  company_tax_id?: string;
  company_logo_url?: string;
  customer_name: string;
  customer_email: string;
  customer_address?: string;
  customer_phone?: string;
  customer_tax_id?: string;
  notes?: string;
  terms_and_conditions?: string;
  payment_instructions?: string;
  is_proforma?: boolean;
  promotion_code?: string;
  items: InvoiceItem[];
  created_at: string;
  updated_at: string;
}

export interface InvoiceResponse {
  status: string;
  message?: string;
  data: {
    invoice?: Invoice;
    invoices?: Invoice[];
    total?: number;
    page?: number;
    limit?: number;
    total_pages?: number;
  };
}

export interface CreateInvoiceData {
  booking_id: number;
  tax_rate?: number;
  discount_amount?: number;
  due_days?: number;
  company_name?: string;
  company_address?: string;
  company_phone?: string;
  company_email?: string;
  company_tax_id?: string;
  company_logo_url?: string;
  customer_tax_id?: string;
  notes?: string;
  terms_and_conditions?: string;
  payment_instructions?: string;
}

export interface UpdateInvoiceData {
  company_name?: string;
  company_address?: string;
  company_phone?: string;
  company_email?: string;
  company_tax_id?: string;
  company_logo_url?: string;
  notes?: string;
  terms_and_conditions?: string;
  payment_instructions?: string;
  status?: string;
  due_date?: string;
  tax_rate?: number;
  discount_amount?: number;
}

export const getInvoices = async (params?: {
  booking_id?: number;
  status?: string;
  page?: number;
  limit?: number;
}): Promise<InvoiceResponse> => {
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>('/invoices', { params });
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: data.status === 'success' || data.success === true ? 'success' : 'error',
    data: data.data || {},
    message: data.message,
  };
};

export const getInvoiceById = async (id: number): Promise<InvoiceResponse> => {
  // Validate that id is a valid number
  // Convert to number if it's a string
  let numericId = id;
  if (typeof id === 'string') {
    numericId = parseInt(id, 10);
  }
  
  if (!numericId || isNaN(numericId) || numericId <= 0 || !isFinite(numericId)) {
    console.error('Invalid invoice ID in getInvoiceById', { id, numericId, type: typeof id });
    throw new Error('Invalid invoice ID');
  }
  
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>(`/invoices/${numericId}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: data.status === 'success' || data.success === true ? 'success' : 'error',
    data: data.data || {},
    message: data.message,
  };
};

export const getInvoicesByBooking = async (bookingId: number): Promise<InvoiceResponse> => {
  // Validate that bookingId is a valid number
  if (!bookingId || isNaN(bookingId) || bookingId <= 0) {
    throw new Error('Invalid booking ID');
  }
  const response = await apiClient.get<{ status?: string; success?: boolean; data?: unknown; message?: string }>(`/invoices/booking/${bookingId}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: data.status === 'success' || data.success === true ? 'success' : 'error',
    data: data.data || {},
    message: data.message,
  };
};

export const createInvoice = async (data: CreateInvoiceData): Promise<InvoiceResponse> => {
  // Validate that booking_id is a valid number
  if (!data.booking_id || isNaN(data.booking_id) || data.booking_id <= 0) {
    throw new Error('Invalid booking ID');
  }
  const response = await apiClient.post<{ status?: string; success?: boolean; data?: unknown; message?: string }>('/invoices', data);
  const responseData = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: responseData.status === 'success' || responseData.success === true ? 'success' : 'error',
    data: responseData.data || {},
    message: responseData.message,
  };
};

export const updateInvoice = async (id: number, data: UpdateInvoiceData): Promise<InvoiceResponse> => {
  // Validate that id is a valid number
  if (!id || isNaN(id) || id <= 0) {
    throw new Error('Invalid invoice ID');
  }
  const response = await apiClient.put<{ status?: string; success?: boolean; data?: unknown; message?: string }>(`/invoices/${id}`, data);
  const responseData = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: responseData.status === 'success' || responseData.success === true ? 'success' : 'error',
    data: responseData.data || {},
    message: responseData.message,
  };
};

export const markInvoiceAsPaid = async (id: number, amount?: number): Promise<InvoiceResponse> => {
  // Validate that id is a valid number
  if (!id || isNaN(id) || id <= 0) {
    throw new Error('Invalid invoice ID');
  }
  const response = await apiClient.post<{ status?: string; success?: boolean; data?: unknown; message?: string }>(`/invoices/${id}/mark-paid`, { amount });
  const responseData = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: responseData.status === 'success' || responseData.success === true ? 'success' : 'error',
    data: responseData.data || {},
    message: responseData.message,
  };
};

export const deleteInvoice = async (id: number): Promise<{ status: string; message: string }> => {
  // Validate that id is a valid number
  if (!id || isNaN(id) || id <= 0) {
    throw new Error('Invalid invoice ID');
  }
  const response = await apiClient.delete<{ status?: string; success?: boolean; message?: string }>(`/invoices/${id}`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: data.status === 'success' || data.success === true ? 'success' : 'error',
    message: data.message || 'Invoice deleted successfully',
  };
};

export const sendInvoiceEmail = async (id: number): Promise<{ status: string; message: string }> => {
  // Validate that id is a valid number
  if (!id || isNaN(id) || id <= 0) {
    throw new Error('Invalid invoice ID');
  }
  const response = await apiClient.post<{ status?: string; success?: boolean; message?: string }>(`/invoices/${id}/send-email`);
  const data = response.data;
  // Handle both 'status: success' and 'success: true' formats
  return {
    status: data.status === 'success' || data.success === true ? 'success' : 'error',
    message: data.message || 'Invoice sent successfully',
  };
};

const invoiceService = {
  getInvoices,
  getInvoiceById,
  getInvoicesByBooking,
  createInvoice,
  updateInvoice,
  markInvoiceAsPaid,
  deleteInvoice,
  sendInvoiceEmail,
};

export default invoiceService;

