import React from 'react';
import { styled, keyframes } from '@mui/system';

const numCols = 10;
const numRows = 6;
const numCells = numCols * numRows;
const shapeHeight = 230;
const shapeWidth = 200;
const bgColor = '#6223D2';

const Overlay = styled('div')`
  width: 100vw;
  height: 100vh;
  position: absolute;
  z-index: 2;
  background: radial-gradient(circle, transparent 0%, rgba(98, 35, 210, 0.15) 100%);
`;

const Container = styled('div')`
  display: grid;
  grid-template-columns: repeat(${numCols}, ${shapeWidth}px);
  grid-template-rows: repeat(${numRows}, ${shapeHeight}px);
  transform: translate(-3%, -4%);
`;

const triangleAnimation = keyframes`
  from {
    points: 50 57.5, 50 57.5, 50 57.5;
  }
  to {
    points: 50 -75, 175 126, -75 126;
  }
`;

const Shape = styled('svg')`
  width: ${shapeWidth}px;
  height: ${shapeHeight}px;
  clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0 75%, 0 25%);
  ${({ index }) => {
    let transform = '';
    if (index > numCols) {
      transform = 'translate(-50%, -25%)';
    }
    if (index > numCols * 2) {
      transform = 'translate(0%, -50%)';
    }
    if (index > numCols * 3) {
      transform = 'translate(-50%, -75%)';
    }
    if (index > numCols * 4) {
      transform = 'translate(0%, -100%)';
    }
    if (index > numCols * 5) {
      transform = 'translate(-50%, -125%)';
    }
    return `
      transform: ${transform};
    `;
  }}
`;

const Polygon = styled('polygon')`
  fill: none;
  stroke-width: 5;
  stroke: ${({ color }) => color};
  animation: ${triangleAnimation} 4s infinite;
  animation-delay: ${({ num }) => num}s;
`;

const colors = ["hsl(320,100%,70%)", "hsl(240,100%,70%)", "hsl(160,100%,70%)", "hsl(80,100%,70%)"];

const TrianglesBackground = ({ children }) => {
  const shapes = [];

  for (let i = 0; i < numCells; i++) {
    shapes.push(
      <Shape key={i} index={i + 1} viewBox="0 0 100 115" preserveAspectRatio="xMidYMin slice">
        {colors.map((color, idx) => (
          <Polygon key={idx} num={idx} color={color} />
        ))}
      </Shape>
    );
  }

  return (
    <div style={{ backgroundColor: bgColor, height: '100vh', width: '100vw', position: 'relative', overflow: 'hidden' }}>
      <Overlay />
      <Container>{shapes}</Container>
      {children}
    </div>
  );
};

export default TrianglesBackground;
