import type {FunctionComponent} from 'react'
import {useLayoutEffect, useState} from 'react'
import {ScrollView, useWindowDimensions, View} from 'react-native'
import {useNavigation} from 'expo-router'
import {Button, ButtonIcon} from '@/components/ui/button'
import {CameraIcon} from 'lucide-react-native'
import CameraUI from '@/components/custom/cameraUI'
import type {PhotoFile} from 'react-native-vision-camera'
import {useMMKVObject} from 'react-native-mmkv'
import FlexSpaceBetweenLastRowFix from '@/components/custom/flexSpaceBetweenLastRowFix'
import calculateImageHeight from '@/utils/calculateImageHeight'
import ImageWithGestures from '@/components/custom/imageWithGestures'

const Index: FunctionComponent = () => {
  const navigation = useNavigation()
  const [showCamera, setShowCamera] = useState<boolean>(false)
  const [photos, setPhotos] = useMMKVObject<PhotoFile[]>('lecture4Photos')
  const dimension = useWindowDimensions()
  // Drie foto's naast elkaar, met een gap van 8px padding tussen de foto's en een marge langs de randen van 8px.
  const width = Math.ceil(dimension.width / 3 - 4 * 8)

  useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: ({tintColor}: {tintColor: string}) => (
        <Button size="lg" className="rounded-full p-3.5" variant="link" onPress={() => setShowCamera(true)}>
          <ButtonIcon as={CameraIcon} color={tintColor} size="xl" />
        </Button>
      ),
    })
  }, [navigation])

  return (
    <>
      <CameraUI
        showCamera={showCamera}
        cameraType="back"
        onClose={photo => {
          if (photo) {
            setPhotos([...(photos ?? []), photo])
          }
          setShowCamera(false)
        }}
      />
      <ScrollView>
        <View className="m-4 gap-2 flex justify-between flex-row flex-wrap">
          {photos?.map((photo, index) => (
            <ImageWithGestures
              style={{width, height: calculateImageHeight(width, photo)}}
              source={{...photo, uri: photo.path}}
              key={index}
              resizeMode="contain"
            />
          ))}

          <FlexSpaceBetweenLastRowFix itemsPerRow={3} totalItems={photos?.length ?? 0} style={{width}} />
        </View>
      </ScrollView>
    </>
  )
}

export default Index
