import isEqual from 'lodash-es/isEqual';

import ListItem from '@material-hu/components/design-system/List/components/ListItem';

import useProfileFields from 'src/hooks/queryHooks/useProfileFields';
import { type SecurityActivity } from 'src/types/insights';

type ProfileDataValue =
  | string
  | string[]
  | number
  | number[]
  | null
  | undefined;

const formatProfileValue = (value: ProfileDataValue): string => {
  if (!value && value !== 0) return '-';
  if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : '-';
  return String(value);
};

type DataSide = 'old' | 'new';

const useProfileDataComparison = (activity: SecurityActivity) => {
  const { data: profileFields = [] } = useProfileFields({
    enabled: !!activity.metadata?.newProfileData,
  });
  const { metadata = {} } = activity;

  const { oldProfileData, newProfileData } = metadata;

  const allUuids = Array.from(
    new Set([
      ...Object.keys(oldProfileData ?? {}),
      ...Object.keys(newProfileData ?? {}),
    ]),
  );

  const changedFields = allUuids.filter(
    uuid => !isEqual(oldProfileData?.[uuid], newProfileData?.[uuid]),
  );

  const getFieldName = (uuid: string): string => {
    const field = profileFields.find(f => f.id === uuid || f.uuid === uuid);
    return field?.name ?? uuid;
  };

  const getProfileDataComparisonElement = (side: DataSide) => {
    if (changedFields.length === 0) return null;

    const profileData = side === 'new' ? newProfileData : oldProfileData;

    return changedFields.map(uuid => (
      <ListItem
        key={`profile-data-${side}-${uuid}`}
        slotProps={{ container: { sx: { p: 0 } } }}
        text={{
          copetin: getFieldName(uuid),
          title: formatProfileValue(profileData?.[uuid]),
        }}
      />
    ));
  };

  return {
    hasChangedFields: Boolean(changedFields.length),
    getProfileDataComparisonElement,
  };
};

export default useProfileDataComparison;
