import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
import { AttendanceRange, AttendanceSummary, CostData, EmployeeMovement, EmployeeSummary, FilterOptions, HrCost, HrCostByJob, HrCostByOrganization, HrCostPerMonth, HrCostPerEmployee, MonthlyAttendance, MonthlyEmployee, MppRecruitment, ProductivityByAge, ProductivityByRegion, ProductivityByTenure, ResignationCategory, ResignationReason, ResignationType as ResignationType, ResignSummary, SanctionSummary, TargetTonnage, TonnageHarvestGroupEmployee, TonnageHarvestByEmployeeOrigin, TonnageHarvestByEmployeeSalary, User, OrganizationMap } from './types'
import { Response , Filter} from './types'
import { config } from '@/config';


let valueToSap: Record<string, string> = {}
let sapToValue: Record<string, string> = {}

const deepClone = (obj: any) => JSON.parse(JSON.stringify(obj))
const rawBaseQuery = fetchBaseQuery({ baseUrl: config.api.baseApiUrl });
const translatedBaseQuery: typeof rawBaseQuery = async (args, api, extraOptions) => {
  const request =
    typeof args === 'string'
      ? { url: args }
      : { ...(args as any), params: args.params ? { ...args.params } : undefined }

  const url = request.url
  const isDashboard = url?.startsWith('/dashboard') && url !== '/dashboard/filter-options'

  // Build mapping dictionaries from organizations map in state
  const orgMapPre = (api.getState() as any).api.queries['getOrganizationsMap(undefined)']?.data ?? []
  if (Array.isArray(orgMapPre) && orgMapPre.length) {
    valueToSap = {}
    sapToValue = {}
    orgMapPre.forEach((org: OrganizationMap) => {
      valueToSap[org.value] = org.sap_code
      sapToValue[org.sap_code] = org.value
    })
  }

  // === Translate REQUEST (value -> sap_code) ===
  if (isDashboard) {
    // ✅ Case 1: params object exists
    if (request.params?.organization_code) {
      const mapped = String(request.params.organization_code)
        .split(',')
        .map((o) => valueToSap[o] ?? o)
        .join(',')
      request.params = { ...request.params, organization_code: mapped }
    } else if (url.includes('organization_code=')) {
      const u = new URL(url, 'http://dummy')
      const orgs = u.searchParams.get('organization_code')?.split(',') ?? []
      const mapped = orgs.map((o) => valueToSap[o] ?? o)
      u.searchParams.set('organization_code', mapped.join(','))
      request.url = u.pathname + '?' + u.searchParams.toString()
    }
  }


  // 2️⃣ Do the request
  const result = await rawBaseQuery(request, api, extraOptions)
  const orgMap = (api.getState() as any).api.queries['getOrganizationsMap(undefined)']?.data ?? []
  const translateOrgCode = (obj: any): any => {
          if (Array.isArray(obj)) return obj.map(translateOrgCode)
          if (obj && typeof obj === 'object') {
            const newObj: Record<string, any> = {}
            for (const [key, val] of Object.entries(obj)) {
              if (key === 'organization_code' && typeof val === 'string') {
                const mappedOrg = orgMap.find((org: any) => org.sap_code === val)
                newObj[key] = mappedOrg?.value || val
              } else {
                newObj[key] = translateOrgCode(val)
              }
            }
            return newObj
          }
          return obj
        }


  // 3️⃣ Translate RESPONSE (sap_code -> value)
  if (isDashboard && result.data) {
    result.data = translateOrgCode(result.data)
  }

  return result
}

export const api = createApi({
    baseQuery: translatedBaseQuery,
    endpoints: (builder) => ({
        login: builder.mutation<{
            user: User;
            token: string;
            roles: string[];
        }, { username: string, password: string }>({
            query: ({ username, password }) => ({
                url: '/login',
                method: 'POST',
                body: { username, password },
            }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        authCheck: builder.query<{
            user: User;
            token: string;
            roles: string[];
        }, void>({
            query: () => ({ url: '/auth-check' }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getOrganizationsMap: builder.query<OrganizationMap[], void>({
            query: () => '/organizations-map',
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getFilterOptions: builder.query<FilterOptions, Filter>({
            query: (params) => ({ url: '/dashboard/filter-options', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getEmployeeSummary: builder.query<EmployeeSummary[], Filter>({
            query: (params) => ({ url: '/dashboard/employee', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getMonthlyEmployee: builder.query<MonthlyEmployee[], Filter>({
            query: (params) => ({ url: '/dashboard/monthly-employee', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getSanctionSummary: builder.query<SanctionSummary[], Filter>({
            query: (params) => ({ url: '/dashboard/sanction-summary', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getOrganizationAttendance: builder.query<AttendanceSummary[], Filter>({
            query: (params) => ({ url: '/dashboard/organization-attendance', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getAttendanceRange: builder.query<AttendanceRange[], Filter>({
            query: (params) => ({ url: '/dashboard/attendance-range', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    // Define the desired order for attendance ranges
                    const desiredOrder = ['0-5', '6-10', '11-15', '16-20', '21-25', '25+'];
                    
                    // Sort the data based on the predefined order
                    const sortedData = response.data!.sort((a: AttendanceRange, b: AttendanceRange) => {
                        const aIndex = desiredOrder.indexOf(a.range);
                        const bIndex = desiredOrder.indexOf(b.range);
                        return aIndex - bIndex;
                    });
                    
                    return sortedData;
                }
            },
        }),
        getMonthlyAttendance: builder.query<MonthlyAttendance[], Filter>({
            query: (params) => ({ url: '/dashboard/monthly-attendance', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getResignSummary: builder.query<ResignSummary[], Filter>({
            query: (params) => ({ url: '/dashboard/to-resign', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getResignType: builder.query<ResignationType[], Filter>({
            query: (params) => ({ url: '/dashboard/to-resign-type', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getResignCategory: builder.query<ResignationCategory[], Filter>({
            query: (params) => ({ url: '/dashboard/to-resign-category', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getResignReason: builder.query<ResignationReason[], Filter>({
            query: (params) => ({ url: '/dashboard/to-resign-reason', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getEmployeeMovement: builder.query<EmployeeMovement[], Filter>({
            query: (params) => ({ url: '/dashboard/employee-movement', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getMppRecruitment: builder.query<MppRecruitment[], Filter>({
            query: (params) => ({ url: '/dashboard/to-mpp-recruitment', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getProductivityByRegion: builder.query<ProductivityByRegion[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-by-employee-count', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getProductivityByAge: builder.query<ProductivityByAge[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-by-employee-age', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getProductivityByTenure: builder.query<ProductivityByTenure[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-by-tenure', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getTonnageHarvestGroupEmployee: builder.query<TonnageHarvestGroupEmployee[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-group-employee', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getTonnageHarvestByEmployeeOrigin: builder.query<TonnageHarvestByEmployeeOrigin[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-employee-origin', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getTonnageHarvestByEmployeeSalary: builder.query<TonnageHarvestByEmployeeSalary[], Filter>({
            query: (params) => ({ url: '/dashboard/tonnage-harvest-employee-salary', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getTargetTonnage: builder.query<TargetTonnage, Filter>({
            query: (params) => ({ url: '/dashboard/target-tonnage', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getHrCostByJob: builder.query<HrCostByJob[], Filter>({
            query: (params) => ({ url: '/dashboard/hr-cost-by-job', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getHrCost: builder.query<HrCost, Filter>({
            query: (params) => ({ url: '/dashboard/hr-cost', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getHrCostByOrganization: builder.query<HrCostByOrganization[], Filter>({
            query: (params) => ({ url: '/dashboard/hr-cost-by-organization', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getHrCostPerMonth: builder.query<HrCostPerMonth[], Filter>({
            query: (params) => ({ url: '/dashboard/hr-cost-per-month', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getHrCostPerEmployee: builder.query<HrCostPerEmployee[], Filter>({
            query: (params) => ({ url: '/dashboard/hr-cost-per-employee', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
        getCost: builder.query<CostData[], Filter>({
            query: (params) => ({ url: '/dashboard/cost', params }),
            transformResponse: (response: Response) => {
                if (response.status === "success") {
                    return response.data!;
                }
            },
        }),
    }),
})

export const { useGetOrganizationsMapQuery, useGetFilterOptionsQuery, useGetEmployeeSummaryQuery, useGetMonthlyEmployeeQuery, useGetMonthlyAttendanceQuery,
    useGetOrganizationAttendanceQuery, useGetAttendanceRangeQuery, useGetResignSummaryQuery, useGetResignTypeQuery, useLazyGetMonthlyEmployeeQuery,
    useLoginMutation, useAuthCheckQuery, useGetSanctionSummaryQuery,
     useGetResignCategoryQuery, useGetResignReasonQuery, useGetEmployeeMovementQuery, useGetMppRecruitmentQuery,
     useGetProductivityByRegionQuery, useGetProductivityByAgeQuery, useGetProductivityByTenureQuery, useGetTonnageHarvestGroupEmployeeQuery, useGetTonnageHarvestByEmployeeOriginQuery, useGetTonnageHarvestByEmployeeSalaryQuery, useGetTargetTonnageQuery, useGetHrCostByJobQuery, useGetHrCostQuery, useGetHrCostByOrganizationQuery, useGetHrCostPerMonthQuery, useGetHrCostPerEmployeeQuery, useGetCostQuery } = api