import { useState, useCallback, useEffect } from 'react';
import { apiClient } from '@/lib/api/client';
import { CreateUserInput } from '@/types/auth';

/**
 * Tipo para empleado con conteo de documentos
 */
export interface Employee {
  id: string;
  name: string | null;
  username: string;
  image: string | null;
  role: string;
  createdAt: Date;
  updatedAt: Date;
  _count: {
    documents: number;
  };
}

/**
 * Resultado de operaciones con empleados
 */
interface EmployeeOperationResult {
  success: boolean;
  error?: string;
  userId?: string;
  message?: string;
}

/**
 * Respuesta de la API para empleados
 */
interface EmployeesApiResponse {
  success: boolean;
  employees?: Employee[];
  error?: string;
}

interface UseEmployeesReturn {
  employees: Employee[];
  isLoading: boolean;
  error: string | null;
  fetchEmployees: () => Promise<void>;
  createEmployee: (data: CreateUserInput) => Promise<{ userId: string }>;
  updateEmployee: (id: string, data: Partial<CreateUserInput>) => Promise<void>;
  deleteEmployee: (id: string) => Promise<void>;
  refetch: () => void;
}

/**
 * Hook personalizado para gestionar empleados
 * 
 * Reemplaza las llamadas fetch directas
 */
export function useEmployees(): UseEmployeesReturn {
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [refetchKey, setRefetchKey] = useState(0);

  const fetchEmployees = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      console.log('👥 [useEmployees] Cargando empleados...');
      const response = await apiClient.get<EmployeesApiResponse>('/api/employees');
      
      if (!response.data?.success) {
        throw new Error(response.data?.error || 'Error al cargar empleados');
      }

      const data = response.data.employees || [];
      console.log('✅ [useEmployees] Empleados cargados:', data.length);
      setEmployees(data);
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Error al cargar empleados';
      console.error('❌ [useEmployees] Error:', errorMessage);
      setError(errorMessage);
      setEmployees([]);
    } finally {
      setIsLoading(false);
    }
  }, [refetchKey]);

  const createEmployee = useCallback(async (data: CreateUserInput) => {
    console.log('📝 [useEmployees] Creando empleado:', data.username);
    
    const response = await apiClient.post<EmployeeOperationResult>('/api/employees', data);
    
    if (!response.data?.success) {
      throw new Error(response.data?.error || 'Error al crear empleado');
    }

    console.log('✅ [useEmployees] Empleado creado:', response.data.userId);
    setRefetchKey(prev => prev + 1);
    return { userId: response.data.userId! };
  }, []);

  const updateEmployee = useCallback(async (id: string, data: Partial<CreateUserInput>) => {
    console.log('✏️ [useEmployees] Actualizando empleado:', id);
    
    const response = await apiClient.put<EmployeeOperationResult>(`/api/employees/${id}`, data);
    
    if (!response.data?.success) {
      throw new Error(response.data?.error || 'Error al actualizar empleado');
    }

    console.log('✅ [useEmployees] Empleado actualizado');
    setRefetchKey(prev => prev + 1);
  }, []);

  const deleteEmployee = useCallback(async (id: string) => {
    console.log('🗑️ [useEmployees] Eliminando empleado:', id);
    
    const response = await apiClient.delete<EmployeeOperationResult>(`/api/employees/${id}`);
    
    if (!response.data?.success) {
      throw new Error(response.data?.error || 'Error al eliminar empleado');
    }

    console.log('✅ [useEmployees] Empleado eliminado');
    setRefetchKey(prev => prev + 1);
  }, []);

  const refetch = useCallback(() => {
    setRefetchKey(prev => prev + 1);
  }, []);

  useEffect(() => {
    fetchEmployees();
  }, [fetchEmployees]);

  return {
    employees,
    isLoading,
    error,
    fetchEmployees,
    createEmployee,
    updateEmployee,
    deleteEmployee,
    refetch,
  };
}
