import React, { useState, useEffect, useCallback, useRef } from 'react'
import { View, TouchableOpacity, StyleSheet, Dimensions, StatusBar, SafeAreaView } from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import { Slider } from '@miblanchard/react-native-slider'

import FastImage from 'react-native-fast-image'
import Sound from 'react-native-sound'
import { useNavigation } from '@react-navigation/native'
import { ActivityIndicator } from 'react-native-paper'
import { HMText, OmniIcon } from '@avegen/ui'
import { generateTypography } from '../../themes/dhp301/typography'
import { DefaultTheme, useTheme } from 'styled-components/native'
import { EventRegister } from '@avegen-atlantis/hm-utils'
import { useNeoAnalytics } from '@avegen/neo-provider'

const { width, height } = Dimensions.get('window')
type AudioPlayerProps = {
  url?: string
  title?: string
  chipIcon?: string
  chipText?: string
  compact?: boolean
  code?: string
}

const AudioPlayer = (props: AudioPlayerProps) => {
  const [isPlaying, setIsPlaying] = useState(false)
  const [isDragging, setIsDragging] = useState(false)
  const [sliderPosition, setSliderPosition] = useState(0)
  const [draggedPosition, setDraggedPosition] = useState(0)
  const [duration, setDuration] = useState(0)
  const [currentTime, setCurrentTime] = useState(0)
  const [hasEnded, setHasEnded] = useState(false)
  const [isLoaded, setIsLoaded] = useState(false)
  const theme = useTheme()
  const styles = getStyles(theme)

  const soundRef = useRef(null)
  const intervalRef = useRef(null)
  const isDraggingRef = useRef(false)
  const navigationListenerRef = useRef(null) // For navigation cleanup

  const { logEvent } = useNeoAnalytics()
  const stopAudio = useCallback(() => {
    if (soundRef.current) {
      try {
        if (soundRef.current.isPlaying()) {
          soundRef.current.pause()
        }
        soundRef.current.release()
        soundRef.current = null
      } catch (error) {
        console.warn('Error stopping audio:', error)
      }
    }
    if (intervalRef.current) {
      clearInterval(intervalRef.current)
      intervalRef.current = null
    }
    setIsPlaying(false)
    setIsLoaded(false)
    setCurrentTime(0)
    setSliderPosition(0)
    setHasEnded(false)
  }, [])

  useEffect(() => {
    navigationListenerRef.current = EventRegister.addEventListener('pageContentNavigated', () => {
      stopAudio()
    })

    return () => {
      if (navigationListenerRef.current && typeof navigationListenerRef.current === 'string') {
        EventRegister.removeEventListener(navigationListenerRef.current)
      }
    }
  }, [stopAudio])

  useEffect(() => {
    if (!props.url) return
    stopAudio()

    Sound.setCategory('Playback')
    Sound.setActive(true)

    if (props.code) {
      logEvent('audio_initial_found', {
        audioUrl: props.url,
        code: props.code,
      })
    }

    const sound = new Sound(props.url, null, error => {
      if (error) {
        console.warn('Audio loading error:', error)
        if (props.code) {
          logEvent('audio_load_error', {
            audioUrl: props.url,
            code: props.code,
            error: error.message,
          })
        }
        return
      }
      const audioDuration = sound.getDuration()
      setDuration(audioDuration)
      setIsLoaded(true)
      sound.setVolume(1)
      soundRef.current = sound

      if (props.code) {
        logEvent('audio_loaded_successfully', {
          audioUrl: props.url,
          code: props.code,
          duration: audioDuration,
        })
      }
    })

    return () => {
      stopAudio()
    }
  }, [props.url, props.code, stopAudio, logEvent])

  const updateProgress = useCallback(() => {
    if (soundRef.current && isLoaded && !isDraggingRef.current) {
      soundRef.current.getCurrentTime(seconds => {
        setCurrentTime(seconds)
        setSliderPosition(seconds)
      })
    }
  }, [isLoaded])

  useEffect(() => {
    if (isPlaying && isLoaded) {
      intervalRef.current = setInterval(updateProgress, 100)
    } else {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
        intervalRef.current = null
      }
    }

    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current)
      }
    }
  }, [isPlaying, isLoaded, updateProgress])

  const formatTime = useCallback(seconds => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }, [])

  const handlePlayPause = useCallback(() => {
    if (!soundRef.current || !isLoaded) {
      if (props.code) {
        logEvent('audio_not_found_play_pause_click', { code: props.code })
      }
      return
    }

    if (isPlaying) {
      if (props.code) {
        logEvent('audio_pause_clicked', {
          timestamp: `${Math.floor(Date.now() / 1000)}`,
          code: props.code,
          currentTime: currentTime,
        })
      }

      soundRef.current.pause()
      setIsPlaying(false)
    } else {
      if (props.code) {
        logEvent('audio_play_clicked', {
          timestamp: `${Math.floor(Date.now() / 1000)}`,
          code: props.code,
          currentTime: currentTime,
        })
      }

      soundRef.current.play(success => {
        if (success) {
          setIsPlaying(false)
          setCurrentTime(0)
          setSliderPosition(0)
          setHasEnded(true)
          if (props.code) {
            logEvent('audio_completed', {
              code: props.code,
              duration: duration,
            })
          }
        } else {
          if (props.code) {
            logEvent('audio_play_failed', {
              code: props.code,
            })
          }
        }
      })
      setIsPlaying(true)
      setHasEnded(false)
    }
  }, [isPlaying, isLoaded, currentTime, duration, props.code, logEvent])

  const handleRetry = useCallback(() => {
    if (!soundRef.current || !isLoaded) return
    if (props.code) {
      logEvent('audio_retry_clicked', {
        code: props.code,
        timestamp: `${Math.floor(Date.now() / 1000)}`,
      })
    }

    soundRef.current.setCurrentTime(0)
    setCurrentTime(0)
    setSliderPosition(0)
    setHasEnded(false)

    soundRef.current.play(success => {
      if (success) {
        setIsPlaying(false)
        setCurrentTime(0)
        setSliderPosition(0)
        setHasEnded(true)
        if (props.code) {
          logEvent('audio_completed_after_retry', {
            code: props.code,
            duration: duration,
          })
        }
      }
    })

    setIsPlaying(true)
  }, [isLoaded, duration, props.code, logEvent])

  const handleSliderChange = useCallback(value => {
    const newValue = Array.isArray(value) ? value[0] : value
    setDraggedPosition(newValue)
    if (isDraggingRef.current) {
      setSliderPosition(newValue)
    }
  }, [])

  const handleSlidingStart = useCallback(() => {
    setIsDragging(true)
    isDraggingRef.current = true
    if (props.code) {
      logEvent('audio_seek_started', {
        code: props.code,
        fromTime: currentTime,
      })
    }
  }, [currentTime, props.code, logEvent])

  const handleSlidingComplete = useCallback(
    value => {
      const newValue = Array.isArray(value) ? value[0] : value

      if (soundRef.current && isLoaded) {
        soundRef.current.setCurrentTime(newValue)
        setCurrentTime(newValue)
        setSliderPosition(newValue)
        if (props.code) {
          logEvent('audio_seek_completed', {
            code: props.code,
            fromTime: currentTime,
            toTime: newValue,
          })
        }
      }

      setTimeout(() => {
        setIsDragging(false)
        isDraggingRef.current = false
      }, 100)
    },
    [isLoaded, currentTime, props.code, logEvent]
  )

  const handleGoBack = useCallback(() => {
    if (props.code) {
      logEvent('audio_back_clicked', {
        code: props.code,
        currentTime: currentTime,
        wasPlaying: isPlaying,
      })
    }
    stopAudio()

    console.log('Go back')
  }, [currentTime, isPlaying, props.code, logEvent, stopAudio])

  const displayPosition = isDragging ? draggedPosition : sliderPosition
  if (props.compact) {
    return (
      <View style={[styles.compactContainer, { backgroundColor: theme?.generic?.colours?.neutral?.['50'] }]}>
        <View style={styles.compactContent}>
          <View style={styles.compactLeftSection}>
            {!isLoaded ? (
              <View style={[styles.compactPlayButton, styles.playButtonDisabled]}>
                <ActivityIndicator size={20} color={theme?.neutrals?.white} />
              </View>
            ) : hasEnded ? (
              <TouchableOpacity style={styles.compactPlayButton} onPress={handleRetry}>
                <OmniIcon name="replay" library="material" size={20} color={theme?.neutrals?.white} />
              </TouchableOpacity>
            ) : (
              <TouchableOpacity style={styles.compactPlayButton} onPress={handlePlayPause}>
                <OmniIcon
                  name={isPlaying ? 'pause' : 'play-arrow'}
                  library="material"
                  size={20}
                  color={theme?.neutrals?.white}
                />
              </TouchableOpacity>
            )}
          </View>

          <View style={styles.compactRightSection}>
            {props.title && (
              <HMText
                style={[generateTypography('heading', 'h5', 700), styles.compactTitle]}
                color={theme?.font?.heading?.primary}
              >
                {props.title}
              </HMText>
            )}

            <View style={styles.compactProgressContainer}>
              <Slider
                minimumValue={0}
                maximumValue={duration || 1}
                value={displayPosition}
                onValueChange={handleSliderChange}
                onSlidingStart={handleSlidingStart}
                onSlidingComplete={handleSlidingComplete}
                minimumTrackTintColor={theme?.generic?.colours?.brand?.primary?.default}
                maximumTrackTintColor={theme?.generic?.colours?.neutral?.['200']}
                thumbStyle={styles.compactSliderThumb}
                trackStyle={styles.compactSliderTrack}
                containerStyle={styles.compactSliderContainer}
                thumbTouchSize={{ width: 30, height: 30 }}
                animateTransitions={true}
                disabled={!isLoaded}
              />
            </View>

            <View style={styles.compactTimeContainer}>
              <HMText style={[generateTypography('body', 'xs', 400)]} color={theme?.generic?.colours?.neutral?.['500']}>
                {formatTime(displayPosition)} / {formatTime(duration || 0)}
              </HMText>
            </View>
          </View>
        </View>
      </View>
    )
  }
  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="light-content" />
      <FastImage
        source={require('../../../../assets/images/cardImage.png')}
        style={styles.backgroundImage}
        resizeMode="cover"
      />
      <LinearGradient colors={['rgba(0, 0, 0, 0)', 'rgba(0,0,0,0.7)']} style={styles.overlay} />

      <View style={styles.header}>
        <TouchableOpacity onPress={handleGoBack} style={styles.backButton}>
          <OmniIcon name="arrow-back" library={'material'} size={24} color={theme?.neutrals?.white} />
        </TouchableOpacity>
      </View>

      <View style={styles.content}>
        <HMText
          style={[generateTypography('heading', 'h4', 700, 'heading')]}
          color={theme?.neutrals?.white}
          textAlign="center"
        >
          {props.title}
        </HMText>
        <View style={styles.readTime}>
          <OmniIcon name={props.chipIcon} library={'ionicon'} size={16} color="white" />
          <HMText style={[generateTypography('alt', 'sm', 700)]} color={theme?.neutrals?.white}>
            {props.chipText}
          </HMText>
        </View>
        {!isLoaded ? (
          <View style={[styles.playButton, styles.playButtonDisabled]}>
            <ActivityIndicator style={{ marginLeft: 1 }} size={24} color={theme?.neutrals?.black} />
          </View>
        ) : hasEnded ? (
          <TouchableOpacity style={styles.playButton} onPress={handleRetry}>
            <OmniIcon name="replay" library="material" size={24} color={theme?.neutrals?.black} />
          </TouchableOpacity>
        ) : (
          <TouchableOpacity style={styles.playButton} onPress={handlePlayPause}>
            <OmniIcon
              name={isPlaying ? 'pause' : 'play-arrow'}
              library="material"
              size={24}
              color={theme?.neutrals?.black}
            />
          </TouchableOpacity>
        )}
      </View>

      <View style={styles.audioControls}>
        <View style={styles.progressContainer}>
          <Slider
            minimumValue={0}
            maximumValue={duration || 1}
            value={displayPosition}
            onValueChange={handleSliderChange}
            onSlidingStart={handleSlidingStart}
            onSlidingComplete={handleSlidingComplete}
            minimumTrackTintColor={theme?.generic?.colours?.brand?.primary?.darker}
            maximumTrackTintColor={theme?.generic?.colours?.neutral?.['700']}
            thumbStyle={styles.sliderThumb}
            trackStyle={styles.sliderTrack}
            containerStyle={styles.sliderContainer}
            thumbTouchSize={{ width: 40, height: 40 }}
            animateTransitions={true}
            disabled={!isLoaded}
          />

          <View style={styles.timeContainer}>
            <HMText style={[generateTypography('body', 'sm', 400)]} color={theme?.generic?.colours?.neutral?.['200']}>
              {formatTime(displayPosition)}
            </HMText>
            <HMText style={[generateTypography('body', 'sm', 400)]} color={theme?.generic?.colours?.neutral?.['200']}>
              {formatTime(duration || 0)}
            </HMText>
          </View>
        </View>
      </View>
    </SafeAreaView>
  )
}

const getStyles = (theme: DefaultTheme) => {
  return StyleSheet.create({
    compactContainer: {
      borderRadius: 8,
      padding: 12,
      marginVertical: 8,
    },
    compactContent: {
      flexDirection: 'row',
      alignItems: 'center',
    },
    compactLeftSection: {
      marginRight: 12,
    },
    compactRightSection: {
      flex: 1,
    },
    compactPlayButton: {
      width: 40,
      height: 40,
      borderRadius: 999,
      backgroundColor: theme?.generic?.colours?.brand?.primary?.default,
      justifyContent: 'center',
      alignItems: 'center',
    },
    compactTitle: {
      marginBottom: 6,
    },
    compactProgressContainer: {
      marginBottom: 4,
    },
    compactTimeContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
    },
    compactChip: {
      flexDirection: 'row',
      alignItems: 'center',
      backgroundColor: theme?.generic?.colours?.neutral?.['100'],
      borderRadius: 4,
      paddingHorizontal: 6,
      paddingVertical: 2,
    },
    compactSliderContainer: {
      height: 24,
      justifyContent: 'center',
    },
    compactSliderTrack: {
      height: 2,
      borderRadius: 1,
    },
    compactSliderThumb: {
      width: 8,
      height: 8,
      backgroundColor: theme?.generic?.colours?.brand?.primary?.default,
      borderRadius: 4,
    },
    container: {
      flex: 1,
    },
    backgroundImage: {
      position: 'absolute',
      width: width,
      height: height,
      top: 0,
      left: 0,
    },
    overlay: {
      position: 'absolute',
      width: width,
      height: height,
      top: 0,
      left: 0,
    },
    header: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      paddingHorizontal: 20,
      paddingTop: 10,
      zIndex: 1,
    },
    backButton: {
      padding: 8,
    },
    content: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      paddingHorizontal: 40,
      zIndex: 1,
    },
    readTime: {
      flexDirection: 'row',
      gap: 4,
      alignItems: 'center',
      justifyContent: 'center',
      paddingVertical: 4,
      paddingHorizontal: 8,
      borderRadius: 4,
      backgroundColor: '#12121217',
      marginVertical: 12,
    },
    audioControls: {
      alignItems: 'center',
      paddingHorizontal: 30,
      paddingBottom: 20,
    },
    playButton: {
      width: 72,
      height: 72,
      borderRadius: 999,
      backgroundColor: 'white',
      justifyContent: 'center',
      alignItems: 'center',
    },
    playButtonDisabled: {
      opacity: 0.5,
    },
    progressContainer: {
      width: '100%',
    },
    sliderContainer: {
      height: 40,
      justifyContent: 'center',
    },
    sliderTrack: {
      height: 4,
      borderRadius: 2,
    },
    sliderThumb: {
      width: 9,
      height: 9,
      backgroundColor: theme?.generic?.colours?.brand?.primary?.default,
      borderRadius: 99,
    },
    timeContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      marginTop: 4,
    },
    timeText: {
      color: 'white',
      fontSize: 14,
      fontWeight: '500',
    },
  })
}
export default AudioPlayer


can you remove the absolute positioning and use flex everywhere and keep the layout intact, (it's fine if the image and everything is inside safeArea