import { Box, Text, useInput } from 'ink'
import React, { useState } from 'react'

interface ConfirmProps {
  message: string
  onConfirm: () => void
  onCancel: () => void
}

export const Confirm: React.FC<ConfirmProps> = ({
  message,
  onConfirm,
  onCancel,
}) => {
  const [selected, setSelected] = useState<'yes' | 'no'>('no')

  useInput((_, key) => {
    if (key.leftArrow || key.rightArrow) {
      setSelected(selected === 'yes' ? 'no' : 'yes')
    }

    if (key.return) {
      if (selected === 'yes') {
        onConfirm()
      } else {
        onCancel()
      }
    }
  })

  return (
    <Box flexDirection="column" marginTop={1}>
      <Text>{message}</Text>
      <Box marginTop={1}>
        <Text
          color={selected === 'yes' ? 'green' : 'gray'}
          bold={selected === 'yes'}
        >
          [Yes]
        </Text>
        <Text> </Text>
        <Text
          color={selected === 'no' ? 'red' : 'gray'}
          bold={selected === 'no'}
        >
          [No]
        </Text>
      </Box>
      <Box marginTop={1}>
        <Text dimColor>Use arrow keys to select, Enter to confirm</Text>
      </Box>
    </Box>
  )
}
