import { format, parseISO } from 'date-fns';

import useMediaQuery from '@material-hu/mui/useMediaQuery';

import { CATEGORIES, IDEA_STATUS } from 'src/constants/recognitions';
import { ColorType } from 'src/types/recognitions';

export const transformPlantsData = plants =>
  plants?.data?.Plants.map(plant => ({
    id: plant.ID,
    name: plant.Nombre,
    ...plant,
  }));

export const transformAreasData = areas =>
  areas?.data?.Areas.map(area => ({
    id: area.ID,
    name: area.Nombre,
    ...area,
  }));

export const transformSupervisorsData = supervisors =>
  supervisors?.data?.Supervisores.map(supervisor => ({
    id: supervisor.ID,
    name: supervisor.Nombre,
    ...supervisor,
  }));

export const getOptionName = (id, data) => {
  const selectedOption = data.find(option => option.id === id);
  return selectedOption ? selectedOption.Nombre : null;
};

export const getOptionSupervisor = (id, data) => {
  const selectedOption = data.find(option => option.id === id);
  return selectedOption ? selectedOption.Correo : null;
};

export const getCategoryClassification = currentCategoryId => {
  const currentCategory = CATEGORIES.filter(
    category => category.id === currentCategoryId,
  );
  return currentCategory[0].classification;
};

export const getFilteredTransactions = (data, movement) => {
  if (!data.data.Transactions) {
    return null;
  } else {
    let sorted = [...data.data.Transactions];
    if (movement !== 'All') {
      sorted = sorted.filter(transaction => transaction.movement === movement);
    }
    return sorted;
  }
};

// Truncamos la cadena para eliminar los milisegundos y la 'Z' al final.
export const parseDate = date => {
  if (date) {
    try {
      const fecha = new Date(date);
      const fechaISO = fecha.toISOString();
      return fechaISO.substring(0, fechaISO.length - 5);
    } catch (err) {
      return date;
    }
  }
  return date;
};

export const formatDate = date => {
  try {
    const auxDate = parseISO(date);
    return format(auxDate, 'dd/MM/yyyy HH:mm');
  } catch (err) {
    return '';
  }
};

export const filterByDate = (ideas, startDate, endDate) => {
  return ideas.filter(idea => {
    if (startDate && endDate) {
      return (
        new Date(Number(idea.created.match(/\d+/)[0])) >= new Date(startDate) &&
        new Date(Number(idea.created.match(/\d+/)[0])) <= new Date(endDate)
      );
    } else if (startDate) {
      return (
        new Date(Number(idea.created.match(/\d+/)[0])) >= new Date(startDate)
      );
    } else if (endDate) {
      return (
        new Date(Number(idea.created.match(/\d+/)[0])) <= new Date(endDate)
      );
    } else {
      return true;
    }
  });
};

export const filterByParam = (items, param, value) => {
  return value !== '' ? items.filter(item => item[param] === value) : items;
};

export const filterByRange = (products, property, min, max) => {
  return products.filter(product => {
    if (min && max) {
      return (
        Number(product[property]) >= Number(min) &&
        Number(product[property]) <= Number(max)
      );
    } else if (min) {
      return Number(product[property]) >= Number(min);
    } else if (max) {
      return Number(product[property]) <= Number(max);
    }
    return true;
  });
};

const colorByStatus: Record<string, ColorType> = {
  [IDEA_STATUS.IN_PROCESS]: 'info',
  [IDEA_STATUS.APPROVED]: 'success',
  [IDEA_STATUS.PENDING]: 'warning',
  [IDEA_STATUS.CANCELED]: 'error',
  [IDEA_STATUS.REJECTED]: 'error',
};

export const getStatusColor = status => {
  return colorByStatus[status] || 'primary';
};

export const isMobile = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent,
  );

export const isIOS = () => /iPhone|iPad|iPod/i.test(navigator.userAgent);

export const isMobileScreen = () => useMediaQuery('(max-width:600px)');

export const hasValue = (data: string) => data && data !== '';

export const getUserId = () => Number(localStorage.getItem('userId'));

export const getUserData = () => JSON.parse(localStorage.getItem('userData'));

export const checkCorrectAnswers = data =>
  data.ownIdea &&
  !data.hasSecurityRisks &&
  !data.hasNegativeImpact &&
  !data.isARepair;

export const checkIsMissingImage = (data, startImage, endImage) =>
  !startImage || (data.ideaImplemented && !endImage);

export const userLogout = () => {
  localStorage.removeItem('userId');
  localStorage.removeItem('userData');
};

export const getFolio = message => {
  const regex = /ID: (\d+)/;
  const result = message.match(regex);
  return Number(result[1]);
};

export const getUploadedFile = (filesData, isBeforeImage) => {
  const bool = isBeforeImage ? 1 : 2;
  const fileData = filesData?.find(file => file.fileCategoryId === bool);
  if (fileData) {
    return {
      fileName: fileData.name,
      imageData: `data:image/jpeg;base64,${fileData.data}`,
    };
  }
  return null;
};

export const getImageBody = (
  folio,
  startImage,
  endImage,
  userId,
  isStartImage,
) => {
  const img = isStartImage ? startImage : endImage;
  const fileCategoryId = isStartImage ? 1 : 2;

  return {
    name: img.fileName,
    data: img.imageData?.split(',')[1],
    folio,
    moduleId: 1,
    fileCategoryId,
    author: userId,
  };
};

export const getEditIdeaValues = (data, idea) => {
  if (!idea.ideaImplemented && idea.statusID === 2) {
    return {
      ...idea,
      ideaImplemented: data.ideaImplementedAfter,
      implementationDate: data.implementationDate.toISOString(),
      statusID: 2,
    };
  } else if (idea.statusID === 13) {
    return {
      ...idea,
      ...data,
      materialSavings: data.materialSavings || idea.materialSavings,
      reduceInspections: data.reduceInspections || idea.reduceInspections,
      defect: data.defect || idea.defect,
      ocurrence: data.ocurrence || idea.ocurrence,
      severity: data.severity || idea.severity,
      ownIdea: data.ownIdea || idea.ownIdea,
      hasSecurityRisks: data.hasSecurityRisks || idea.hasSecurityRisks,
      hasNegativeImpact: data.hasNegativeImpact || idea.hasNegativeImpact,
      isARepair: data.isARepair || idea.isARepair,
      ideaImplemented: data.ideaImplemented || idea.ideaImplemented,
      categoryID: data.category || idea.categoryID,
    };
  }
  return {};
};

export const hasImagesBeenUploaded = statusCodeArray =>
  statusCodeArray.every(statusCode => statusCode === '0');
