import { generateQueryString } from '@/utils/queryStringUtil';
import { apiSlice } from '.';
import URLS from './constants';
import { Contact } from './contactApi';
import { Lead } from './leadApi';

type Sales = {
  kind: 'Project' | 'Property';
  project?: string;
  property?: string;
  soldBy: string;
  salesAt: string;
  notes?: string;
};

export interface Customer {
  id: string;
  name: string;
  email?: string;
  phone?: number;
  company?: { id: string };
  contactId?: Contact;
  leadId?: Lead;
  unitBookingOrHold?: string;
  sales: {
    kind: 'Project' | 'Property';
    project?: { id: string; projectName: string };
    property?: { id: string };
    soldBy: { id: string };
    salesAt: string;
    notes?: string;
  }[];
  createdBy?: { id: string };
  updatedBy?: { id: string };
}

interface GetCustomerListResponse {
  code: number;
  message: string;
  success: boolean;
  data: {
    results: Customer[];
    page: number;
    limit: number;
    totalPages: number;
    totalResults: number;
  };
}

interface CreateCustomerRequest {
  name: string;
  email?: string;
  phone?: number;
  contactId?: string;
  sales: Sales[];
}

type GetCustomersQueryParams = {
  search?: string;
  sortBy?: string;
  page?: number;
  limit?: number;
  company?: string;
  populate?: string;
};

interface GetCustomerByIdParams {
  id: string;
  populate?: string;
}

interface GetCustomerByIdResponse {
  code: number;
  message: string;
  data: Customer;
  success: boolean;
}

// ---------- Payment Types ----------
export interface PaymentTimeline {
  label: string;
  paid: number;
  lastPaidAt?: string;
  status: string;
  method?: string;
  key?: string;
  dueDate?: string;
  dueAmount?: number;
  _id?: string;
}

export interface GetCustomerPaymentResponse {
  code: number;
  message: string;
  data: {
    totalAmount: number;
    paidAmount: number;
    overallStatus: string;
    timeline: PaymentTimeline[];
  };
  success: boolean;
}

export interface UpdateCustomerPaymentRequest {
  timeline: PaymentTimeline[];
}

export interface UpdateCustomerPaymentResponse {
  code: number;
  message: string;
  data: {
    totalAmount: number;
    paidAmount: number;
    overallStatus: string;
    timeline: PaymentTimeline[];
  };
  success: boolean;
}

// API slice
export const customerApi = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getCustomers: builder.query<GetCustomerListResponse, GetCustomersQueryParams>({
      query: (params) => ({
        url: `${URLS.CUSTOMER}?${generateQueryString(params as Record<string, unknown>)}`,
        method: 'GET',
      }),
      providesTags: ['Customer'],
    }),

    getCustomerById: builder.query<GetCustomerByIdResponse, GetCustomerByIdParams>({
      query: ({ id, populate }) => {
        const query = populate ? `?populate=${populate}` : '';
        return {
          url: `${URLS.CUSTOMER}/${id}${query}`,
          method: 'GET',
        };
      },
      providesTags: (_result, _error, { id }) => [{ type: 'Customer', id }],
    }),

    createCustomer: builder.mutation<Customer, CreateCustomerRequest>({
      query: (body) => ({
        url: `${URLS.CUSTOMER}`,
        method: 'POST',
        body,
      }),
      invalidatesTags: ['Customer'],
    }),

    // -------- Payment Endpoints --------
    getCustomerPayment: builder.query<GetCustomerPaymentResponse, { id: string }>({
      query: ({ id }) => ({
        url: `${URLS.CUSTOMER}/${id}/payment`,
        method: 'GET',
      }),
      providesTags: (_result, _error, { id }) => [{ type: 'Customer', id }],
    }),

    updateCustomerPayment: builder.mutation<
      UpdateCustomerPaymentResponse,
      { id: string; body: UpdateCustomerPaymentRequest }
    >({
      query: ({ id, body }) => ({
        url: `${URLS.CUSTOMER}/${id}/payment`,
        method: 'PATCH',
        body,
      }),
      invalidatesTags: (_result, _error, { id }) => [{ type: 'Customer', id }],
    }),
  }),
  overrideExisting: false,
});

export const {
  useGetCustomersQuery,
  useGetCustomerByIdQuery,
  useCreateCustomerMutation,
  useGetCustomerPaymentQuery,
  useUpdateCustomerPaymentMutation,
} = customerApi;
