import { User, UserNode } from '@/redux/api/userApi';

export const getInitials = (name?: string) => {
  if (!name || typeof name !== 'string') return '';

  return name
    .split(' ')
    .map((part) => part[0])
    .join('')
    .toUpperCase();
};

export const mapApiUsersToUserNodes = (apiUsers: any[]): UserNode[] => {
  return apiUsers.map((user) => ({
    id: user.id,
    firstName: user.firstName,
    lastName: user.lastName,
    email: user.email,
    phone: user.phone,

    // Map role from company.role array (taking first role)
    role: user.company?.role?.[0]?.name || 'No Role',

    // Map team from team array (taking first team)
    team: user.team?.length > 0 ? user.team : [],

    // Map other fields
    memberType: user.memberType,
    userType: user.userType,
    status: user.status,
    isDeleted: user.isDeleted,
    joiningDate: user.joiningDate,

    // Map reporting structure
    reportingTo: user.reportingTo,

    // Initialize children array (will be populated by buildHierarchy)
    children: [],

    // Additional fields that might be useful
    companyId: user.company?.id?.id,
    createdBy: user.createdBy,
    updatedBy: user.updatedBy,
    isEmailVerified: user.isEmailVerified,
    lastPermissionUpdate: user.lastPermissionUpdate,
  }));
};

export const buildHierarchy = (users: UserNode[]): UserNode[] => {
  const userMap = new Map<string, UserNode>();
  const rootNodes: UserNode[] = [];

  // Create a map of all users
  users.forEach((user) => {
    userMap.set(user.id, { ...user, children: [] });
  });

  // Build the hierarchy
  users.forEach((user) => {
    const mappedUser = userMap.get(user.id);
    if (!mappedUser) return;

    if (user.reportingTo?.id) {
      // This user reports to someone
      const manager = userMap.get(user.reportingTo.id);
      if (manager) {
        manager.children.push(mappedUser);
      } else {
        // Manager not found in current dataset, treat as root
        rootNodes.push(mappedUser);
      }
    } else {
      // This user doesn't report to anyone, so they're a root node
      rootNodes.push(mappedUser);
    }
  });

  return rootNodes;
};

export const calculatePercentage = (achieved: number, target: number) => {
  return Math.round((achieved / target) * 100);
};

export const deepMerge = (target: any, source: any): any => {
  const output = { ...target };

  for (const key of Object.keys(source)) {
    const sourceValue = source[key];
    const targetValue = target[key];

    const isObject = (val: any) => val && typeof val === 'object' && !Array.isArray(val);

    // Skip if sourceValue is undefined, null, or empty string (but allow 0, false, etc.)
    const isValidValue = (val: any) => val !== undefined && val !== null && val !== '';

    if (isObject(sourceValue) && isObject(targetValue)) {
      output[key] = deepMerge(targetValue, sourceValue);
    } else if (isObject(sourceValue)) {
      output[key] = deepMerge({}, sourceValue); // trust that new object is valid
    } else if (isValidValue(sourceValue)) {
      output[key] = sourceValue;
    }
  }

  return output;
};
