import type {FunctionComponent} from 'react'
import {useLayoutEffect, useState} from 'react'
import {View} from 'react-native'
import ColorPicker from '../../components/custom/colorPicker'
import {useNavigation} from 'expo-router'
import {useTheme} from '@react-navigation/core'
import {VStack} from '@/components/ui/vstack'
import {Input, InputField} from '@/components/ui/input'
import {HStack} from '@/components/ui/hstack'
import {Button, ButtonIcon, ButtonText} from '@/components/ui/button'
import {CheckIcon} from 'lucide-react-native'
import {useCreateLabel} from '@/db/labelsAPI'

const CreateLabel: FunctionComponent = () => {
  const [name, setName] = useState<string>('')
  const {colors} = useTheme()
  const [color, setColor] = useState<string>(colors.notification)
  const [showPicker, setShowPicker] = useState<boolean>(false)
  const navigation = useNavigation()
  const {mutate: createLabel} = useCreateLabel()

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

  return (
    <VStack className="m-4 gap-4">
      <Input>
        <InputField value={name} onChangeText={setName} placeholder="Label name" />
      </Input>

      <HStack className="p-1 h-10 border border-primary-0 rounded items-center justify-between">
        <View
          className="h-full w-[45%]"
          style={{
            backgroundColor: color,
          }}></View>
        <Button variant="link" className="p-2" onPress={() => setShowPicker(true)}>
          <ButtonText>Change color</ButtonText>
        </Button>
      </HStack>
      <ColorPicker
        color={color}
        onColorChosen={setColor}
        onClose={() => setShowPicker(false)}
        showPicker={showPicker}
      />
    </VStack>
  )
}

export default CreateLabel
