import { api } from './api';
import { PageResponse, PageRequest } from '@/types/backend';
import {
    AgentDTO, AgentStatsDTO, AgentStatusHistoryDTO, CareerTimelineDTO,
    PayrollPeriodDTO, PayrollRunDTO, PayrollItemDTO
} from '@/types/rh';

const AGENTS_URL = '/rh/agents';
const PAYROLL_PERIODS_URL = '/rh/payroll-periods';
const PAYROLL_RUNS_URL = '/rh/payroll-runs';
const BANK_ACCOUNTS_URL = '/rh/bank-accounts';
const CONTRACTS_URL = '/rh/contracts';

export const rhService = {
    // Agents
    getAgents: async (pageRequest: PageRequest & {
        query?: string;
        status?: string;
        ministry?: string;
        orgUnit?: string;
        position?: string;
        functionalSituation?: string;
        appointmentType?: string;
    }): Promise<PageResponse<AgentDTO>> => {
        const {
            page = 0,
            size = 20,
            sortBy,
            sortDirection,
            query,
            status,
            ministry,
            orgUnit,
            position,
            functionalSituation,
            appointmentType
        } = pageRequest;
        const params = new URLSearchParams();
        params.append('page', page.toString());
        params.append('size', size.toString());
        if (query) {
            params.append('query', query);
        }
        if (status) {
            params.append('status', status);
        }
        if (ministry) {
            params.append('ministry', ministry);
        }
        if (orgUnit) {
            params.append('orgUnit', orgUnit);
        }
        if (position) {
            params.append('position', position);
        }
        if (functionalSituation) {
            params.append('functionalSituation', functionalSituation);
        }
        if (appointmentType) {
            params.append('appointmentType', appointmentType);
        }
        if (sortBy) {
            params.append('sortBy', sortBy);
            if (sortDirection) {
                params.append('sortDirection', sortDirection);
            }
        }

        const response = await api.get<PageResponse<AgentDTO>>(AGENTS_URL, { params });
        return response;
    },

    getAgentById: async (id: string): Promise<AgentDTO> => {
        const response = await api.get<AgentDTO>(`${AGENTS_URL}/${id}`);
        return response;
    },

    createAgent: async (agent: Omit<AgentDTO, 'id'>): Promise<AgentDTO> => {
        const response = await api.post<AgentDTO>(AGENTS_URL, agent);
        return response;
    },

    updateAgent: async (id: string, agent: Partial<AgentDTO>): Promise<AgentDTO> => {
        const response = await api.put<AgentDTO>(`${AGENTS_URL}/${id}`, agent);
        return response;
    },

    deleteAgent: async (id: string): Promise<void> => {
        await api.delete(`${AGENTS_URL}/${id}`);
    },

    getStats: async (filters?: {
        query?: string;
        status?: string;
        ministry?: string;
        orgUnit?: string;
        position?: string;
        functionalSituation?: string;
        appointmentType?: string;
    }): Promise<AgentStatsDTO> => {
        const params: Record<string, any> = {};
        if (filters) {
            Object.entries(filters).forEach(([key, value]) => {
                if (value !== undefined && value !== null && value !== '') {
                    params[key] = value;
                }
            });
        }
        const response = await api.get<AgentStatsDTO>(`${AGENTS_URL}/stats`, { params });
        return response;
    },

    getAgentHistory: async (id: string): Promise<CareerTimelineDTO[]> => {
        const response = await api.get<CareerTimelineDTO[]>(`${AGENTS_URL}/${id}/history`);
        return response;
    },

    getAgentStatusHistory: async (id: string): Promise<AgentStatusHistoryDTO[]> => {
        const response = await api.get<AgentStatusHistoryDTO[]>(`${AGENTS_URL}/${id}/status-history`);
        return response;
    },

    // Payroll
    getPayrollPeriods: async (): Promise<PayrollPeriodDTO[]> => {
        const response = await api.get<PayrollPeriodDTO[]>(PAYROLL_PERIODS_URL);
        return response;
    },

    getPayrollRuns: async (): Promise<PayrollRunDTO[]> => {
        const response = await api.get<PayrollRunDTO[]>(PAYROLL_RUNS_URL);
        return response;
    },

    getPayrollRunById: async (id: string): Promise<PayrollRunDTO> => {
        const response = await api.get<PayrollRunDTO>(`${PAYROLL_RUNS_URL}/${id}`);
        return response;
    },

    createPayrollRun: async (run: { periodId: string; ministryId: string; orgUnitId?: string; runType: string }): Promise<PayrollRunDTO> => {
        const response = await api.post<PayrollRunDTO>(PAYROLL_RUNS_URL, run);
        return response;
    },

    generatePayrollItems: async (id: string): Promise<void> => {
        await api.post(`${PAYROLL_RUNS_URL}/${id}/generate`);
    },

    processPayrollRun: (id: string): Promise<void> =>
        api.post(`/rh/payroll-runs/${id}/process`),

    deletePayrollRun: async (id: string): Promise<void> => {
        await api.delete(`${PAYROLL_RUNS_URL}/${id}`);
    },

    diagnosePayrollRun: async (id: string): Promise<any> => {
        const response = await api.get(`${PAYROLL_RUNS_URL}/${id}/diagnose`);
        return response;
    },

    // Gestão Tributária
    getTaxRules: (): Promise<any> =>
        api.get('/rh/taxes/rules'),

    saveTaxRule: (rule: any): Promise<any> =>
        api.post('/rh/taxes/rules', rule),

    deleteTaxRule: (id: string): Promise<void> =>
        api.delete(`/rh/taxes/rules/${id}`),

    getTaxBrackets: (): Promise<any> =>
        api.get('/rh/taxes/brackets'),

    saveTaxBracket: (bracket: any): Promise<any> =>
        api.post('/rh/taxes/brackets', bracket),

    deleteTaxBracket: (id: string): Promise<void> =>
        api.delete(`/rh/taxes/brackets/${id}`),

    getActiveTaxBrackets: (): Promise<any> =>
        api.get('/rh/taxes/brackets/active'),

    getDeductionTypes: (): Promise<any[]> =>
        api.get('/rh/taxes/types'),

    saveDeductionType: (type: any): Promise<any> =>
        api.post('/rh/taxes/types', type),

    toggleDeductionTypeStatus: (id: string): Promise<void> =>
        api.put(`/rh/taxes/types/${id}/toggle`),

    // Contas Bancárias
    getBankAccounts: (): Promise<any[]> =>
        api.get(BANK_ACCOUNTS_URL),

    getBankAccountsByAgent: (agentId: string): Promise<any[]> =>
        api.get(`${BANK_ACCOUNTS_URL}/agent/${agentId}`),

    saveBankAccount: (account: any): Promise<any> =>
        api.post(BANK_ACCOUNTS_URL, account),

    updateBankAccount: (id: string, account: any): Promise<any> =>
        api.put(`${BANK_ACCOUNTS_URL}/${id}`, account),

    deleteBankAccount: (id: string): Promise<void> =>
        api.delete(`${BANK_ACCOUNTS_URL}/${id}`),

    // Contratos
    getContracts: (): Promise<any[]> =>
        api.get(CONTRACTS_URL),

    getContractsByAgent: (agentId: string): Promise<any[]> =>
        api.get(`${CONTRACTS_URL}/agent/${agentId}`),

    saveContract: (contract: any): Promise<any> =>
        api.post(CONTRACTS_URL, contract),

    updateContract: (id: string, contract: any): Promise<any> =>
        api.put(`${CONTRACTS_URL}/${id}`, contract),

    deleteContract: (id: string): Promise<void> =>
        api.delete(`${CONTRACTS_URL}/${id}`),

    // Gestão de Períodos
    createPayrollPeriod: (period: any): Promise<any> =>
        api.post(PAYROLL_PERIODS_URL, period),

    updatePayrollPeriodStatus: (id: string, status: string): Promise<any> =>
        api.put(`${PAYROLL_PERIODS_URL}/${id}/status`, null, { params: { status } }),

    // Performance Evaluation
    getEvaluations: async (pageRequest: PageRequest): Promise<PageResponse<any>> => {
        const response = await api.get<PageResponse<any>>('/rh/evaluations', { params: pageRequest });
        return response;
    },

    finalizeEvaluation: async (id: string): Promise<void> => {
        await api.post(`/rh/evaluations/${id}/finalize`);
    },

    // Payroll Cycle Closure
    closePayrollRun: async (id: string): Promise<void> => {
        await api.post(`/rh/payroll-runs/${id}/close`);
    },

    exportPayrollRun: async (id: string, format: 'pdf' | 'xlsx'): Promise<void> => {
        const response = await api.get(`/reports/payroll/runs/${id}/export`, {
            params: { format },
            responseType: 'blob',
        });
        const url = window.URL.createObjectURL(new Blob([response as any]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `payroll_run_${id}.${format}`);
        document.body.appendChild(link);
        link.click();
        link.remove();
    },
};
