const currencyFormatter = new Intl.NumberFormat('en-US', {
  style: 'currency',
  currency: 'USD',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});

const numberFormatter = new Intl.NumberFormat('en-US', {
  minimumFractionDigits: 0,
  maximumFractionDigits: 2,
});

export const coerceNumber = (value: unknown) => {
  if (value === null || value === undefined || value === '') {
    return 0;
  }

  const parsed = Number(value);

  return Number.isFinite(parsed) ? parsed : 0;
};

export const formatCurrency = (value: unknown) => currencyFormatter.format(coerceNumber(value));

export const formatDecimal = (value: unknown) => numberFormatter.format(coerceNumber(value));

export const resolveEntityId = (value: any) => {
  if (!value) {
    return null;
  }

  if (typeof value === 'string') {
    return value;
  }

  if (typeof value === 'object' && value.id) {
    return value.id;
  }

  return null;
};

export const hasPayTypeDetails = (payType: any) => {
  if (!payType || typeof payType !== 'object') {
    return false;
  }

  return Boolean(payType.pay_method || payType.hourly_rate || payType.commission_rate);
};

export const hasWorkersCompDetails = (workersCompClass: any) => {
  if (!workersCompClass || typeof workersCompClass !== 'object') {
    return false;
  }

  return workersCompClass.percentage !== undefined && workersCompClass.percentage !== null;
};

export const calculateJobLogPayPreview = ({
  payType,
  workersCompClass,
  hoursConducted,
  clientPaid,
}: {
  payType?: any;
  workersCompClass?: any;
  hoursConducted?: unknown;
  clientPaid?: unknown;
}) => {
  const payMethod = payType?.pay_method || null;
  const hours = coerceNumber(hoursConducted);
  const clientAmount = coerceNumber(clientPaid);
  const hourlyRate = coerceNumber(payType?.hourly_rate);
  const commissionRate = coerceNumber(payType?.commission_rate);
  const workersCompPercentage = coerceNumber(workersCompClass?.percentage);

  let estimatedPay = 0;
  let formulaLabel = 'Select a pay type to preview earnings.';

  if (payMethod === 'hourly') {
    estimatedPay = hours * hourlyRate;
    formulaLabel = `${formatDecimal(hours)} hours × ${formatCurrency(hourlyRate)}/hr`;
  } else if (payMethod === 'commission') {
    estimatedPay = clientAmount * (commissionRate / 100);
    formulaLabel = `${formatCurrency(clientAmount)} client paid × ${formatDecimal(commissionRate)}%`;
  }

  const workersCompAmount = estimatedPay * (workersCompPercentage / 100);

  return {
    payMethod,
    payTypeName: payType?.name || 'Not selected',
    hours,
    clientAmount,
    hourlyRate,
    commissionRate,
    estimatedPay,
    formulaLabel,
    workersCompName: workersCompClass?.name || null,
    workersCompPercentage,
    workersCompAmount,
    hasEstimate: payMethod === 'hourly' || payMethod === 'commission',
  };
};
