import React, { useMemo, useState } from 'react'

import {
  Button,
  Chip,
  Group,
  Popover,
  Stack,
  Textarea,
  Title,
  Tooltip
} from '@mantine/core'
import { useForm } from '@mantine/form'
import { showNotification } from '@mantine/notifications'

import { LinguflowFeedbackInfo, sendLinguflowFeedback } from './api'
import { DislikeIcon, LikeIcon } from './FeedbackIcon'
import { Message } from './Messages/useMessages'

const FEEDBACK_TYPES = [
  'Content Errors',
  'Unclear Answer',
  'Lack of Core Information',
  'Other Suggestions'
]

const like = (id: string) => sendLinguflowFeedback(id, { score: 1 })
const dislike = (id: string) => sendLinguflowFeedback(id, { score: -1 })
const feedback = (id: string, feedback: LinguflowFeedbackInfo) =>
  sendLinguflowFeedback(id, {
    score: -1,
    comment: `feedback type: ${feedback.type}
description: ${feedback.description}
`
  })

const FeedbackComponent: React.FC<{
  message: Message
}> = ({ message }) => {
  const [disliked, setDisliked] = useState(false)
  const [liked, setLiked] = useState(false)
  const [feedbackOpened, setFeedbackOpened] = useState(false)
  const feedbackTypes = useMemo(
    () => FEEDBACK_TYPES.map((type) => ({ key: type, value: type })),
    []
  )
  const form = useForm<LinguflowFeedbackInfo>({
    initialValues: {
      type: '',
      description: ''
    }
  })
  const {
    values: { type, description }
  } = form
  const [loading, setLoading] = useState(false)

  return (
    <Button.Group className='absolute right-[-20px] bottom-[-10px]'>
      <Tooltip label='Like'>
        <Button
          variant='light'
          radius='lg'
          size='xs'
          color={liked ? 'green' : 'gray'}
          onClick={() => {
            if (liked) {
              return
            }

            setLiked(true)
            like(message.currentId!)
            showNotification({
              color: 'green',
              message: 'Thank you for your feedback'
            })
          }}
        >
          <LikeIcon />
        </Button>
      </Tooltip>

      <Popover
        withArrow={false}
        withinPortal
        width={410}
        position='right'
        radius='md'
        opened={feedbackOpened}
        onChange={setFeedbackOpened}
        onOpen={form.reset}
        zIndex={99999}
      >
        <Popover.Target>
          <Tooltip label='Dislike'>
            <Button
              variant='light'
              radius='lg'
              size='xs'
              color={disliked ? 'orange' : 'gray'}
              onClick={() => {
                setFeedbackOpened(true)
                if (disliked) {
                  return
                }

                setDisliked(true)
                dislike(message.currentId!)
                showNotification({
                  color: 'green',
                  message: 'Thank you for your feedback'
                })
              }}
            >
              <DislikeIcon />
            </Button>
          </Tooltip>
        </Popover.Target>
        <Popover.Dropdown>
          <form
            onSubmit={form.onSubmit(async (values) => {
              setLoading(true)
              await feedback(message.currentId!, values)
              setFeedbackOpened(false)
              setLoading(false)
              showNotification({
                color: 'green',
                message: 'Thank you for your feedback'
              })
            })}
          >
            <Stack>
              <Title order={4}>
                Your feedback will help us continue to improve.
              </Title>

              <Stack spacing='xs'>
                <Title order={5}>Question Type</Title>
                <Chip.Group
                  multiple
                  value={form.values.type
                    ?.split(',')
                    .filter((v: string) => !!v)}
                  onChange={(v) => form.setFieldValue('type', v.join(','))}
                >
                  <Group spacing='xs'>
                    {feedbackTypes.map((f) => (
                      <Chip value={f.key} size='sm' key={f.key}>
                        {f.value}
                      </Chip>
                    ))}
                  </Group>
                </Chip.Group>
              </Stack>

              <Stack spacing='xs'>
                <Title order={5}>Question Description</Title>
                <Textarea
                  minRows={4}
                  {...form.getInputProps('description')}
                  placeholder={`Enter detailed suggestion, please point out the part of the content that you think is problematic.\nDon't include your name, email, or other personal info.`}
                />
              </Stack>

              <Group position='center'>
                <Button
                  type='submit'
                  variant='gradient'
                  loading={loading}
                  gradient={{ from: 'teal', to: 'blue', deg: 60 }}
                  disabled={!type && !description}
                >
                  Submit
                </Button>
              </Group>
            </Stack>
          </form>
        </Popover.Dropdown>
      </Popover>
    </Button.Group>
  )
}

export default FeedbackComponent
