'use client';

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

/**
 * Skill Level enum matching backend
 */
export type SkillLevelValue = 0 | 1 | 2 | 3 | 4;

/**
 * Skill level labels for display
 */
export const SKILL_LEVEL_LABELS: Record<SkillLevelValue, string> = {
  0: 'noKnowledge',
  1: 'basics',
  2: 'independent',
  3: 'expert',
  4: 'canTrain',
};

/**
 * Skill level colors for display
 */
export const SKILL_LEVEL_COLORS: Record<SkillLevelValue, { bg: string; text: string; border: string }> = {
  0: { bg: 'bg-gray-100 dark:bg-gray-800', text: 'text-gray-500', border: 'border-gray-300' },
  1: { bg: 'bg-red-100 dark:bg-red-900/30', text: 'text-red-700 dark:text-red-400', border: 'border-red-300' },
  2: { bg: 'bg-yellow-100 dark:bg-yellow-900/30', text: 'text-yellow-700 dark:text-yellow-400', border: 'border-yellow-300' },
  3: { bg: 'bg-green-100 dark:bg-green-900/30', text: 'text-green-700 dark:text-green-400', border: 'border-green-300' },
  4: { bg: 'bg-blue-100 dark:bg-blue-900/30', text: 'text-blue-700 dark:text-blue-400', border: 'border-blue-300' },
};

/**
 * Department with basic info
 */
export interface SkillDepartment {
  id: string;
  name: string;
  code: string | null;
}

/**
 * Skill definition
 */
export interface Skill {
  id: string;
  name: string;
  description: string | null;
  category: string | null;
  isActive: boolean;
  department: SkillDepartment | null;
  _count?: {
    entries: number;
  };
}

/**
 * Query parameters for skills
 */
export interface QuerySkillsParams {
  page?: number;
  limit?: number;
  search?: string;
  departmentId?: string;
  category?: string;
  isActive?: boolean;
  includeGlobal?: boolean;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

/**
 * Create skill DTO
 */
export interface CreateSkillDto {
  name: string;
  description?: string;
  category?: string;
  departmentId?: string;
  isActive?: boolean;
}

/**
 * Update skill DTO
 */
export interface UpdateSkillDto {
  name?: string;
  description?: string;
  category?: string;
  departmentId?: string;
  isActive?: boolean;
}

/**
 * Query key factory for skills
 */
export const skillsKeys = {
  all: ['skills'] as const,
  lists: () => [...skillsKeys.all, 'list'] as const,
  list: (params?: QuerySkillsParams) => [...skillsKeys.lists(), params] as const,
  detail: (id: string) => [...skillsKeys.all, 'detail', id] as const,
  categories: () => [...skillsKeys.all, 'categories'] as const,
  department: (departmentId: string) => [...skillsKeys.all, 'department', departmentId] as const,
};

/**
 * Fetch all skills with filters
 */
async function fetchSkills(params?: QuerySkillsParams): Promise<LeanPaginatedResponse<Skill>> {
  return api.get('/lean/skills', { params: params as Record<string, string | number | boolean | undefined> });
}

/**
 * Fetch a single skill
 */
async function fetchSkill(id: string): Promise<Skill> {
  return api.get(`/lean/skills/${id}`);
}

/**
 * Fetch skills for a department
 */
async function fetchSkillsForDepartment(departmentId: string): Promise<Skill[]> {
  return api.get(`/lean/skills/department/${departmentId}`);
}

/**
 * Fetch all skill categories
 */
async function fetchCategories(): Promise<string[]> {
  return api.get('/lean/skills/categories');
}

/**
 * Create a new skill
 */
async function createSkill(dto: CreateSkillDto): Promise<Skill> {
  return api.post('/lean/skills', dto);
}

/**
 * Update a skill
 */
async function updateSkill(id: string, dto: UpdateSkillDto): Promise<Skill> {
  return api.put(`/lean/skills/${id}`, dto);
}

/**
 * Delete (deactivate) a skill
 */
async function deleteSkill(id: string): Promise<Skill> {
  return api.delete(`/lean/skills/${id}`);
}

/**
 * Hook to fetch all skills
 */
export function useSkills(params?: QuerySkillsParams) {
  return useQuery({
    queryKey: skillsKeys.list(params),
    queryFn: () => fetchSkills(params),
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch a single skill
 */
export function useSkill(id: string) {
  return useQuery({
    queryKey: skillsKeys.detail(id),
    queryFn: () => fetchSkill(id),
    enabled: !!id,
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch skills for a department
 */
export function useSkillsForDepartment(departmentId: string) {
  return useQuery({
    queryKey: skillsKeys.department(departmentId),
    queryFn: () => fetchSkillsForDepartment(departmentId),
    enabled: !!departmentId,
    staleTime: 30 * 1000,
  });
}

/**
 * Hook to fetch skill categories
 */
export function useSkillCategories() {
  return useQuery({
    queryKey: skillsKeys.categories(),
    queryFn: fetchCategories,
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
}

/**
 * Hook to create a skill
 */
export function useCreateSkill() {
  const queryClient = useQueryClient();

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

/**
 * Hook to update a skill
 */
export function useUpdateSkill() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, dto }: { id: string; dto: UpdateSkillDto }) => updateSkill(id, dto),
    onSuccess: (_, { id }) => {
      queryClient.invalidateQueries({ queryKey: skillsKeys.detail(id) });
      queryClient.invalidateQueries({ queryKey: skillsKeys.lists() });
    },
  });
}

/**
 * Hook to delete a skill
 */
export function useDeleteSkill() {
  const queryClient = useQueryClient();

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