'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import type { ContractType, UserRole } from '@/types';

/**
 * Employment status types
 */
export type EmploymentStatus = 'active' | 'inactive' | 'on_leave' | 'terminated';

/**
 * Employee entity
 */
export interface Employee {
  id: string;
  employeeNumber: string;
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  avatarUrl?: string;
  position: string;
  departmentId: string;
  department?: {
    id: string;
    name: string;
    code?: string;
  };
  managerId?: string;
  manager?: {
    id: string;
    firstName: string;
    lastName: string;
  };
  roles: UserRole[];
  contractType: ContractType;
  status: EmploymentStatus;
  hireDate: string;
  terminationDate?: string;
  weeklyHours: number;
  vacationDaysTotal: number;
  vacationDaysUsed: number;
  vacationDaysPending: number;
  overtimeBalance: number;
  address?: {
    street: string;
    city: string;
    zipCode: string;
    country: string;
  };
  emergencyContact?: {
    name: string;
    phone: string;
    relationship: string;
  };
  createdAt: string;
  updatedAt: string;
}

/**
 * Paginated response for employees
 */
export interface EmployeePaginatedResponse<T> {
  data: T[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

/**
 * Query parameters for employees
 */
export interface QueryEmployeesParams {
  page?: number;
  limit?: number;
  search?: string;
  departmentId?: string;
  status?: EmploymentStatus;
  contractType?: ContractType;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * Create employee DTO
 */
export interface CreateEmployeeDto {
  employeeNumber: string;
  firstName: string;
  lastName: string;
  email: string;
  phone?: string;
  position: string;
  departmentId: string;
  managerId?: string;
  roles?: UserRole[];
  contractType: ContractType;
  hireDate: string;
  weeklyHours: number;
  vacationDaysTotal?: number;
  address?: {
    street: string;
    city: string;
    zipCode: string;
    country: string;
  };
  emergencyContact?: {
    name: string;
    phone: string;
    relationship: string;
  };
}

/**
 * Update employee DTO
 */
export interface UpdateEmployeeDto extends Partial<CreateEmployeeDto> {
  status?: EmploymentStatus;
  terminationDate?: string;
}

/**
 * Employee statistics
 */
export interface EmployeeStats {
  total: number;
  active: number;
  onLeave: number;
  newThisMonth: number;
  departmentBreakdown: {
    departmentId: string;
    departmentName: string;
    count: number;
  }[];
}

/**
 * Query key factory for employees
 */
export const employeesKeys = {
  all: ['employees'] as const,
  lists: () => [...employeesKeys.all, 'list'] as const,
  list: (params?: QueryEmployeesParams) => [...employeesKeys.lists(), params] as const,
  detail: (id: string) => [...employeesKeys.all, 'detail', id] as const,
  stats: () => [...employeesKeys.all, 'stats'] as const,
  orgChart: () => [...employeesKeys.all, 'org-chart'] as const,
  department: (departmentId: string) => [...employeesKeys.all, 'department', departmentId] as const,
};

// =============================================================================
// API FUNCTIONS
// =============================================================================

async function fetchEmployees(
  params?: QueryEmployeesParams
): Promise<EmployeePaginatedResponse<Employee>> {
  return api.get('/hr/employees', { params: params as Record<string, string | number | boolean | undefined> });
}

async function fetchEmployee(id: string): Promise<Employee> {
  return api.get(`/hr/employees/${id}`);
}

async function fetchEmployeeStats(): Promise<EmployeeStats> {
  return api.get('/hr/employees/stats');
}

async function createEmployee(dto: CreateEmployeeDto): Promise<Employee> {
  return api.post('/hr/employees', dto);
}

async function updateEmployee(id: string, dto: UpdateEmployeeDto): Promise<Employee> {
  return api.put(`/hr/employees/${id}`, dto);
}

async function deleteEmployee(id: string): Promise<void> {
  return api.delete(`/hr/employees/${id}`);
}

// ============ React Query Hooks ============

/**
 * Hook to fetch all employees
 */
export function useEmployees(params?: QueryEmployeesParams) {
  return useQuery({
    queryKey: employeesKeys.list(params),
    queryFn: () => fetchEmployees(params),
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch a single employee
 */
export function useEmployee(id: string) {
  return useQuery({
    queryKey: employeesKeys.detail(id),
    queryFn: () => fetchEmployee(id),
    enabled: !!id,
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch employee statistics
 */
export function useEmployeeStats() {
  return useQuery({
    queryKey: employeesKeys.stats(),
    queryFn: fetchEmployeeStats,
    staleTime: 60 * 1000,
  });
}

/**
 * Hook to create an employee
 */
export function useCreateEmployee() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: createEmployee,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: employeesKeys.all });
    },
  });
}

/**
 * Hook to update an employee
 */
export function useUpdateEmployee() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateEmployeeDto }) => updateEmployee(id, dto),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: employeesKeys.detail(id) });
      queryClient.invalidateQueries({ queryKey: employeesKeys.lists() });
    },
  });
}

/**
 * Hook to delete (terminate) an employee
 */
export function useDeleteEmployee() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: deleteEmployee,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: employeesKeys.all });
    },
  });
}

// ============ Utility Constants ============

/**
 * Employment status labels for display
 */
export const EMPLOYMENT_STATUS_LABELS: Record<EmploymentStatus, string> = {
  active: 'active',
  inactive: 'inactive',
  on_leave: 'onLeave',
  terminated: 'terminated',
};

/**
 * Employment status colors for display
 */
export const EMPLOYMENT_STATUS_COLORS: Record<
  EmploymentStatus,
  { bg: string; text: string; border: string }
> = {
  active: {
    bg: 'bg-green-100 dark:bg-green-900/30',
    text: 'text-green-700 dark:text-green-400',
    border: 'border-green-300',
  },
  inactive: {
    bg: 'bg-gray-100 dark:bg-gray-800',
    text: 'text-gray-700 dark:text-gray-400',
    border: 'border-gray-300',
  },
  on_leave: {
    bg: 'bg-yellow-100 dark:bg-yellow-900/30',
    text: 'text-yellow-700 dark:text-yellow-400',
    border: 'border-yellow-300',
  },
  terminated: {
    bg: 'bg-red-100 dark:bg-red-900/30',
    text: 'text-red-700 dark:text-red-400',
    border: 'border-red-300',
  },
};

/**
 * Contract type labels for display
 */
export const CONTRACT_TYPE_LABELS: Record<ContractType, string> = {
  full_time: 'fullTime',
  part_time: 'partTime',
  mini_job: 'miniJob',
  intern: 'intern',
  trainee: 'trainee',
  freelance: 'freelance',
};
