// Skeleton loader component
// props:
// - type: string (rounded | circle | rectangle)
// - width: number
// - height: number
// - animationType: string (pulse | wave)

import React, { useEffect, useRef } from 'react'
import { View, StyleSheet, Animated } from 'react-native'
import { HEIGHT, WIDTH } from '../utils'
const Skeleton = ({
  type = 'rounded',
  width = 100,
  height = 20,
  animationType = 'pulse',
  style,
  m,
  mx,
  my = 2,
  mt,
  mr,
  mb,
  ml,
  p,
  px,
  py,
  pt,
  pr,
  pb,
  pl,
}) => {
  const animationRef = useRef(new Animated.Value(0)).current
  const calculatedWidth = WIDTH * (width / 100)
  const calculatedHeight = HEIGHT * (height / 100)

  const marginStyle = {
    margin: m,
    marginTop: mt,
    marginBottom: mb,
    marginLeft: ml,
    marginRight: mr,
    marginVertical: my,
    marginHorizontal: mx,
  }
  const paddingStyle = {
    padding: p,
    paddingTop: pt,
    paddingBottom: pb,
    paddingLeft: pl,
    paddingRight: pr,
    paddingVertical: py,
    paddingHorizontal: px,
  }

  const styles = StyleSheet.create({
    skeleton: {
      width: calculatedWidth,
      height: 8 * height,
      borderRadius: type === 'rounded' ? 10 : type === 'circle' ? 100 : 0,
      backgroundColor: '#f0f0f0',
    },
    pulse: {
      animationName: 'pulse',
      animationDuration: '1s',
      animationIterationCount: 'infinite',
      animationTimingFunction: 'ease-in-out',
    },
    wave: {
      animationName: 'wave',
      animationDuration: '1s',
      animationIterationCount: 'infinite',
      animationTimingFunction: 'ease-in-out',
    },
  })

  // animate the skeleton loader
  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(animationRef, {
          toValue: 1,
          duration: 1000,
          useNativeDriver: true,
        }),
        Animated.timing(animationRef, {
          toValue: 0,
          duration: 1000,
          useNativeDriver: true,
        }),
      ])
    ).start()
  }, [animationRef])

  return (
    <Animated.View
      ref={animationRef}
      style={[
        styles.skeleton,
        style,
        animationType === 'pulse' && styles.pulse,
        animationType === 'wave' && styles.wave,
        marginStyle,
        paddingStyle,
      ]}
    />
  )
}

export default Skeleton
