'use strict';

type FixedLengthArray<
  T,
  L extends number,
  PassedObject = [T, ...Array<T>],
> = PassedObject & {
  readonly length: L;
  [I: number]: T;
};

export type AffineMatrix = FixedLengthArray<FixedLengthArray<number, 4>, 4>;

export type AffineMatrixFlat = FixedLengthArray<number, 16>;

interface TransformMatrixDecomposition {
  translationMatrix: AffineMatrix;
  scaleMatrix: AffineMatrix;
  rotationMatrix: AffineMatrix;
  skewMatrix: AffineMatrix;
  perspective?: FixedLengthArray<number, 4>;
}

type Axis = 'x' | 'y' | 'z';

interface TransformMatrixDecompositionWithAngles extends TransformMatrixDecomposition {
  rx: number;
  ry: number;
  rz: number;
}

interface MatrixInterpolation {
  start: AffineMatrixFlat;
  stop: AffineMatrixFlat;
  decomposed?: [
    TransformMatrixDecompositionWithAngles,
    TransformMatrixDecompositionWithAngles,
  ];
}

export function isAffineMatrixFlat(x: unknown): x is AffineMatrixFlat {
  'worklet';
  return (
    Array.isArray(x) &&
    x.length === 16 &&
    x.every((element) => typeof element === 'number' && !isNaN(element))
  );
}

export function isAffineMatrix(x: unknown): x is AffineMatrix {
  'worklet';
  return (
    Array.isArray(x) &&
    x.length === 4 &&
    x.every(
      (row) =>
        Array.isArray(row) &&
        row.length === 4 &&
        row.every((element) => typeof element === 'number' && !isNaN(element))
    )
  );
}

export function flatten(matrix: AffineMatrix): AffineMatrixFlat {
  'worklet';
  return matrix.flat() as AffineMatrixFlat;
}

export function unflatten(m: AffineMatrixFlat): AffineMatrix {
  'worklet';
  return [
    [m[0], m[1], m[2], m[3]],
    [m[4], m[5], m[6], m[7]],
    [m[8], m[9], m[10], m[11]],
    [m[12], m[13], m[14], m[15]],
  ] as AffineMatrix;
}

function maybeFlattenMatrix(
  matrix: AffineMatrix | AffineMatrixFlat
): AffineMatrixFlat {
  'worklet';
  return isAffineMatrix(matrix) ? flatten(matrix) : matrix;
}

export function multiplyMatrices(
  a: AffineMatrix,
  b: AffineMatrix
): AffineMatrix {
  'worklet';
  return [
    [
      a[0][0] * b[0][0] +
        a[0][1] * b[1][0] +
        a[0][2] * b[2][0] +
        a[0][3] * b[3][0],

      a[0][0] * b[0][1] +
        a[0][1] * b[1][1] +
        a[0][2] * b[2][1] +
        a[0][3] * b[3][1],

      a[0][0] * b[0][2] +
        a[0][1] * b[1][2] +
        a[0][2] * b[2][2] +
        a[0][3] * b[3][2],

      a[0][0] * b[0][3] +
        a[0][1] * b[1][3] +
        a[0][2] * b[2][3] +
        a[0][3] * b[3][3],
    ],
    [
      a[1][0] * b[0][0] +
        a[1][1] * b[1][0] +
        a[1][2] * b[2][0] +
        a[1][3] * b[3][0],

      a[1][0] * b[0][1] +
        a[1][1] * b[1][1] +
        a[1][2] * b[2][1] +
        a[1][3] * b[3][1],

      a[1][0] * b[0][2] +
        a[1][1] * b[1][2] +
        a[1][2] * b[2][2] +
        a[1][3] * b[3][2],

      a[1][0] * b[0][3] +
        a[1][1] * b[1][3] +
        a[1][2] * b[2][3] +
        a[1][3] * b[3][3],
    ],
    [
      a[2][0] * b[0][0] +
        a[2][1] * b[1][0] +
        a[2][2] * b[2][0] +
        a[2][3] * b[3][0],

      a[2][0] * b[0][1] +
        a[2][1] * b[1][1] +
        a[2][2] * b[2][1] +
        a[2][3] * b[3][1],

      a[2][0] * b[0][2] +
        a[2][1] * b[1][2] +
        a[2][2] * b[2][2] +
        a[2][3] * b[3][2],

      a[2][0] * b[0][3] +
        a[2][1] * b[1][3] +
        a[2][2] * b[2][3] +
        a[2][3] * b[3][3],
    ],
    [
      a[3][0] * b[0][0] +
        a[3][1] * b[1][0] +
        a[3][2] * b[2][0] +
        a[3][3] * b[3][0],

      a[3][0] * b[0][1] +
        a[3][1] * b[1][1] +
        a[3][2] * b[2][1] +
        a[3][3] * b[3][1],

      a[3][0] * b[0][2] +
        a[3][1] * b[1][2] +
        a[3][2] * b[2][2] +
        a[3][3] * b[3][2],

      a[3][0] * b[0][3] +
        a[3][1] * b[1][3] +
        a[3][2] * b[2][3] +
        a[3][3] * b[3][3],
    ],
  ];
}

export function subtractMatrices<T extends AffineMatrixFlat | AffineMatrix>(
  maybeFlatA: T,
  maybeFlatB: T
): T {
  'worklet';
  const isFlatOnStart = isAffineMatrixFlat(maybeFlatA);
  const a: AffineMatrixFlat = maybeFlattenMatrix(maybeFlatA);
  const b: AffineMatrixFlat = maybeFlattenMatrix(maybeFlatB);

  const c = a.map((_, i) => a[i] - b[i]) as AffineMatrixFlat;
  return isFlatOnStart ? (c as T) : (unflatten(c) as T);
}

export function addMatrices<T extends AffineMatrixFlat | AffineMatrix>(
  maybeFlatA: T,
  maybeFlatB: T
): T {
  'worklet';
  const isFlatOnStart = isAffineMatrixFlat(maybeFlatA);
  const a = maybeFlattenMatrix(maybeFlatA);
  const b = maybeFlattenMatrix(maybeFlatB);

  const c = a.map((_, i) => a[i] + b[i]) as AffineMatrixFlat;
  return isFlatOnStart ? (c as T) : (unflatten(c) as T);
}

function scaleMatrix<T extends AffineMatrixFlat | AffineMatrix>(
  maybeFlatA: T,
  scalar: number
): T {
  'worklet';
  const isFlatOnStart = isAffineMatrixFlat(maybeFlatA);
  const a = maybeFlattenMatrix(maybeFlatA);

  const b = a.map((x) => x * scalar) as AffineMatrixFlat;
  return isFlatOnStart ? (b as T) : (unflatten(b) as T);
}

function getRotationMatrix(angle: number, axis: Axis = 'z'): AffineMatrix {
  'worklet';
  const cos = Math.cos(angle);
  const sin = Math.sin(angle);
  switch (axis) {
    case 'z':
      return [
        [cos, sin, 0, 0],
        [-sin, cos, 0, 0],
        [0, 0, 1, 0],
        [0, 0, 0, 1],
      ];
    case 'y':
      return [
        [cos, 0, -sin, 0],
        [0, 1, 0, 0],
        [sin, 0, cos, 0],
        [0, 0, 0, 1],
      ];
    case 'x':
      return [
        [1, 0, 0, 0],
        [0, cos, sin, 0],
        [0, -sin, cos, 0],
        [0, 0, 0, 1],
      ];
  }
}

function norm3d(x: number, y: number, z: number) {
  'worklet';
  return Math.sqrt(x * x + y * y + z * z);
}

function transposeMatrix(matrix: AffineMatrix): AffineMatrix {
  'worklet';
  const m = flatten(matrix);
  return [
    [m[0], m[4], m[8], m[12]],
    [m[1], m[5], m[9], m[13]],
    [m[2], m[6], m[10], m[14]],
    [m[3], m[7], m[11], m[15]],
  ];
}

function assertVectorsHaveEqualLengths(a: number[], b: number[]) {
  'worklet';
  if (__DEV__ && a.length !== b.length) {
    throw new Error(
      `[Reanimated] Cannot calculate inner product of two vectors of different lengths. Length of ${a.toString()} is ${
        a.length
      } and length of ${b.toString()} is ${b.length}.`
    );
  }
}

function innerProduct(a: number[], b: number[]) {
  'worklet';
  assertVectorsHaveEqualLengths(a, b);
  return a.reduce((acc, _, i) => acc + a[i] * b[i], 0);
}

function projection(u: number[], a: number[]) {
  'worklet';
  assertVectorsHaveEqualLengths(u, a);
  const s = innerProduct(u, a) / innerProduct(u, u);
  return u.map((e) => e * s);
}

function subtractVectors(a: number[], b: number[]) {
  'worklet';
  assertVectorsHaveEqualLengths(a, b);
  return a.map((_, i) => a[i] - b[i]);
}

function scaleVector(u: number[], a: number) {
  'worklet';
  return u.map((e) => e * a);
}

function gramSchmidtAlgorithm(matrix: AffineMatrix): {
  rotationMatrix: AffineMatrix;
  skewMatrix: AffineMatrix;
} {
  // Gram-Schmidt orthogonalization decomposes any matrix with non-zero determinant into an orthogonal and a triangular matrix
  // These matrices are equal to rotation and skew matrices respectively, because we apply it to transformation matrix
  // That is expected to already have extracted the remaining transforms (scale & translation)
  'worklet';
  const [a0, a1, a2, a3] = matrix;

  const u0 = a0;
  const u1 = subtractVectors(a1, projection(u0, a1));
  const u2 = subtractVectors(
    subtractVectors(a2, projection(u0, a2)),
    projection(u1, a2)
  );
  const u3 = subtractVectors(
    subtractVectors(
      subtractVectors(a3, projection(u0, a3)),
      projection(u1, a3)
    ),
    projection(u2, a3)
  );

  const [e0, e1, e2, e3] = [u0, u1, u2, u3].map((u) =>
    scaleVector(u, 1 / Math.sqrt(innerProduct(u, u)))
  );

  const rotationMatrix: AffineMatrix = [
    [e0[0], e1[0], e2[0], e3[0]],
    [e0[1], e1[1], e2[1], e3[1]],
    [e0[2], e1[2], e2[2], e3[2]],
    [e0[3], e1[3], e2[3], e3[3]],
  ];

  const skewMatrix: AffineMatrix = [
    [
      innerProduct(e0, a0),
      innerProduct(e0, a1),
      innerProduct(e0, a2),
      innerProduct(e0, a3),
    ],
    [0, innerProduct(e1, a1), innerProduct(e1, a2), innerProduct(e1, a3)],
    [0, 0, innerProduct(e2, a2), innerProduct(e2, a3)],
    [0, 0, 0, innerProduct(e3, a3)],
  ];
  return {
    rotationMatrix: transposeMatrix(rotationMatrix),
    skewMatrix: transposeMatrix(skewMatrix),
  };
}

function determinant3x3(m: AffineMatrixFlat): number {
  'worklet';
  return (
    m[0] * (m[5] * m[10] - m[6] * m[9]) -
    m[1] * (m[4] * m[10] - m[6] * m[8]) +
    m[2] * (m[4] * m[9] - m[5] * m[8])
  );
}

function extractPerspective(
  m: AffineMatrixFlat
): FixedLengthArray<number, 4> | undefined {
  'worklet';
  if (m[3] === 0 && m[7] === 0 && m[11] === 0) {
    return undefined;
  }
  // Solve A * perspective = M's last column, where A has no perspective.
  const determinant = determinant3x3(m);
  const x =
    (m[3] * (m[5] * m[10] - m[6] * m[9]) +
      m[7] * (m[2] * m[9] - m[1] * m[10]) +
      m[11] * (m[1] * m[6] - m[2] * m[5])) /
    determinant;
  const y =
    (m[3] * (m[6] * m[8] - m[4] * m[10]) +
      m[7] * (m[0] * m[10] - m[2] * m[8]) +
      m[11] * (m[2] * m[4] - m[0] * m[6])) /
    determinant;
  const z =
    (m[3] * (m[4] * m[9] - m[5] * m[8]) +
      m[7] * (m[1] * m[8] - m[0] * m[9]) +
      m[11] * (m[0] * m[5] - m[1] * m[4])) /
    determinant;
  return [x, y, z, 1 - m[12] * x - m[13] * y - m[14] * z];
}

export function decomposeMatrix(
  unknownTypeMatrix: AffineMatrixFlat | AffineMatrix
): TransformMatrixDecomposition {
  'worklet';
  const input = maybeFlattenMatrix(unknownTypeMatrix);

  if (input[15] === 0) {
    throw new Error('[Reanimated] Invalid transform matrix.');
  }
  const matrix = input.map((value) => value / input[15]) as AffineMatrixFlat;

  const translationMatrix: AffineMatrix = [
    [1, 0, 0, 0],
    [0, 1, 0, 0],
    [0, 0, 1, 0],
    [matrix[12], matrix[13], matrix[14], 1],
  ];
  const scales = [
    matrix[15] * norm3d(matrix[0], matrix[4], matrix[8]),
    matrix[15] * norm3d(matrix[1], matrix[5], matrix[9]),
    matrix[15] * norm3d(matrix[2], matrix[6], matrix[10]),
  ];
  // A rotation cannot express a reflection, so the most reversed axis keeps it
  // as a negative scale.
  if (determinant3x3(matrix) < 0) {
    const diagonal = [matrix[0], matrix[5], matrix[10]].map(
      (value, axis) => value / scales[axis]
    );
    const axis = diagonal.indexOf(Math.min(...diagonal));
    scales[axis] = -scales[axis];
  }
  const [sx, sy, sz] = scales;

  // eslint-disable-next-line @typescript-eslint/no-shadow
  const scaleMatrix: AffineMatrix = [
    [sx, 0, 0, 0],
    [0, sy, 0, 0],
    [0, 0, sz, 0],
    [0, 0, 0, 1],
  ];

  const rotationAndSkewMatrix: AffineMatrix = [
    [matrix[0] / sx, matrix[1] / sx, matrix[2] / sx, 0],
    [matrix[4] / sy, matrix[5] / sy, matrix[6] / sy, 0],
    [matrix[8] / sz, matrix[9] / sz, matrix[10] / sz, 0],
    [0, 0, 0, 1],
  ];

  const { rotationMatrix, skewMatrix } = gramSchmidtAlgorithm(
    rotationAndSkewMatrix
  );

  return {
    translationMatrix,
    scaleMatrix,
    rotationMatrix,
    skewMatrix,
    perspective: extractPerspective(matrix),
  };
}

export function decomposeMatrixIntoMatricesAndAngles(
  matrix: AffineMatrixFlat | AffineMatrix
): TransformMatrixDecompositionWithAngles {
  'worklet';
  const {
    // eslint-disable-next-line @typescript-eslint/no-shadow
    scaleMatrix,
    rotationMatrix,
    translationMatrix,
    skewMatrix,
    perspective,
  } = decomposeMatrix(matrix);

  const sinRy = -rotationMatrix[0][2];

  const ry = Math.asin(sinRy);
  let rx;
  let rz;
  if (sinRy === 1 || sinRy === -1) {
    rz = 0;
    rx = Math.atan2(-rotationMatrix[2][1], rotationMatrix[1][1]);
  } else {
    rz = Math.atan2(rotationMatrix[0][1], rotationMatrix[0][0]);
    rx = Math.atan2(rotationMatrix[1][2], rotationMatrix[2][2]);
  }

  return {
    scaleMatrix,
    rotationMatrix,
    translationMatrix,
    skewMatrix,
    perspective,
    rx: rx || 0,
    ry: ry || 0,
    rz: rz || 0,
  };
}

function applyProgressToMatrix(
  progress: number,
  a: AffineMatrix,
  b: AffineMatrix
) {
  'worklet';
  return addMatrices(a, scaleMatrix(subtractMatrices(b, a), progress));
}

function applyProgressToNumber(progress: number, a: number, b: number) {
  'worklet';
  return a + progress * (b - a);
}

function canDecomposeMatrix(matrix: AffineMatrixFlat): boolean {
  'worklet';
  const scale =
    norm3d(matrix[0], matrix[1], matrix[2]) *
    norm3d(matrix[4], matrix[5], matrix[6]) *
    norm3d(matrix[8], matrix[9], matrix[10]);
  const determinant = determinant3x3(matrix) / scale;
  return (
    matrix[15] !== 0 &&
    Number.isFinite(determinant) &&
    Math.abs(determinant) > 8 * Number.EPSILON
  );
}

export function prepareMatrixInterpolation(
  from: AffineMatrixFlat | AffineMatrix,
  to: AffineMatrixFlat | AffineMatrix
): MatrixInterpolation {
  'worklet';
  const start = [...maybeFlattenMatrix(from)] as AffineMatrixFlat;
  const stop = [...maybeFlattenMatrix(to)] as AffineMatrixFlat;
  if (!canDecomposeMatrix(start) || !canDecomposeMatrix(stop)) {
    return { start, stop };
  }
  return {
    start,
    stop,
    decomposed: [
      decomposeMatrixIntoMatricesAndAngles(start),
      decomposeMatrixIntoMatricesAndAngles(stop),
    ],
  };
}

export function interpolateDecomposedMatrix(
  progress: number,
  start: TransformMatrixDecompositionWithAngles,
  stop: TransformMatrixDecompositionWithAngles
): AffineMatrixFlat {
  'worklet';
  const translation = applyProgressToMatrix(
    progress,
    start.translationMatrix,
    stop.translationMatrix
  );
  const scale = applyProgressToMatrix(
    progress,
    start.scaleMatrix,
    stop.scaleMatrix
  );
  const skew = applyProgressToMatrix(
    progress,
    start.skewMatrix,
    stop.skewMatrix
  );
  const rotation = multiplyMatrices(
    getRotationMatrix(applyProgressToNumber(progress, start.rx, stop.rx), 'x'),
    multiplyMatrices(
      getRotationMatrix(
        applyProgressToNumber(progress, start.ry, stop.ry),
        'y'
      ),
      getRotationMatrix(applyProgressToNumber(progress, start.rz, stop.rz), 'z')
    )
  );
  const matrix = multiplyMatrices(
    multiplyMatrices(scale, multiplyMatrices(skew, rotation)),
    translation
  );
  if (start.perspective || stop.perspective) {
    const from = start.perspective ?? [0, 0, 0, 1];
    const to = stop.perspective ?? [0, 0, 0, 1];
    const perspective = from.map((value, i) =>
      applyProgressToNumber(progress, value, to[i])
    );
    for (const row of matrix) {
      row[3] =
        row[0] * perspective[0] +
        row[1] * perspective[1] +
        row[2] * perspective[2] +
        row[3] * perspective[3];
    }
  }
  return flatten(matrix);
}

export function interpolateMatrix(
  progress: number,
  interpolation: MatrixInterpolation
): AffineMatrixFlat {
  'worklet';
  const { start, stop, decomposed } = interpolation;
  if (progress === 0) {
    return start;
  }
  if (progress === 1) {
    return stop;
  }
  // Singular matrices do not have a unique rotation decomposition.
  if (!decomposed) {
    return start.map((value, i) =>
      applyProgressToNumber(progress, value, stop[i])
    ) as AffineMatrixFlat;
  }
  return interpolateDecomposedMatrix(progress, decomposed[0], decomposed[1]);
}
