import {
  Alert, Autocomplete,
  Button,
  Container,
  Group,
  Modal,
  Progress, SegmentedControl,
  Select, SelectItem,
  Space,
  Stack,
  Text,
  Textarea,
  TextInput
} from "@mantine/core";
import {useForm} from '@mantine/form';
import React, {useEffect, useLayoutEffect, useState} from "react";
import {useTranslation} from "react-i18next";
import {Feedback} from "./types/feedback";
import ModalTasks from "./ModalTasks";
import axios from "axios";

interface ModalFeedbackProps {
  config: Feedback.Config,
  show: boolean
  onClose: () => void
  onSubmit: (task: Feedback.Data) => void
  onRecorder: () => void
  onScreenshot: () => void
  screenshot?: Screenshot.Data
  screenshotError?: string
  record?: Record.Data
  uploadProgress?: number
  uploadProgressTusScreenshot?: number
  tusUploadedScreenshot: boolean
  recorderError?: Error
  types: Array<{ label: string, value: string }>
}

export default function ModalFeedback({
                                        config,
                                        show,
                                        onClose,
                                        onSubmit,
                                        screenshot,
                                        screenshotError,
                                        onScreenshot,
                                        record,
                                        onRecorder,
                                        uploadProgress,
                                        uploadProgressTusScreenshot,
                                        tusUploadedScreenshot,
                                        recorderError,
                                        types
                                      }: ModalFeedbackProps) {

  const {t} = useTranslation('feedbackSupport', {useSuspense: false})

  const defaultTypes = [
    {label: t('ModalFeedback.types.bug'), value: t('ModalFeedback.types.bug')},
    {label: t('ModalFeedback.types.suggestion'), value: t('ModalFeedback.types.suggestion')},
    {label: t('ModalFeedback.types.ui'), value: t('ModalFeedback.types.ui')}
  ]

  const [feedbackType, setFeedbackType] = useState<'comment' | 'close'>('comment')

  const [showTasks, setShowTasks] = useState(false)

  const [task, setTask] = useState<Api.Task>()


  const [assignData, setAssignData] = useState<SelectItem[]>([])

  const form = useForm({
    initialValues: {
      assign: '',
      type: '',
      title: '',
      description: ''
    },
    validate: {
      type: (value) => !value ? t("ModalFeedback.form.errors.type") : null,
      title: (value) => !value.length ? t("ModalFeedback.form.errors.title") : null,
      description: (value) => !value.length ? t('ModalFeedback.form.errors.description') : null
    }
  })

  const loader = (
    <Progress
      sections={[
        {
          value: uploadProgress ? uploadProgress : 0,
          color: 'primary',
          label: `Data: ${Math.round(uploadProgress || 0)}%`
        },
      ]}
      size={'xl'}
      sx={{
        width: '50%',
        position: "absolute",
        left: '25%'
      }}/>
  )

  let uploading = false
  if (uploadProgress !== undefined && uploadProgress > 0) {
    uploading = true
  }

  if (uploadProgressTusScreenshot !== undefined && uploadProgressTusScreenshot > 0 && !tusUploadedScreenshot) {
    uploading = true
  }

  const handleSubmit = (data: Feedback.Data) => {
    form.reset()
    setTask(undefined)
    onSubmit(data)
  }

  const handleClose = () => {
    form.reset()
    setTask(undefined)
    onClose()
  }

  let autocompleteData: string[] = []
  const title = form.values.title
  if (title.trim().length > 0 && title.includes('#') && title[title.length - 1] === '#') {
    const stringStart = title.substring(0, title.length - 1)

    autocompleteData = [stringStart + '#assign:', stringStart + '#comment:', stringStart + '#close']
  }

  let typeData = defaultTypes

  if (types.length) {
    typeData = types
  }


  const handleShowTask = () => {
    form.reset()
    setTask(undefined)
    form.setFieldValue('type', '')
    form.setFieldValue('title', '')
    setShowTasks(true)
  }

  const handleSelectTask = (task: Api.Task | undefined) => {
    if (task) {
      setTask(task)
      setFeedbackType('comment')
      form.setValues({
        type: task.name,
        title: `#comment:${task.id}`
      })
    }
    setShowTasks(false)
  }

  useEffect(() => {
    if (task !== undefined) {
      if (feedbackType === 'comment') {
        form.setFieldValue('title', `#comment:${task.id}`)
      } else if (feedbackType === 'close') {
        form.setValues({
          title: `#comment:${task.id} #close`,
          assign: ''
        })
      }
    }
  }, [feedbackType])

  useEffect(() => {
    if ('userRights' in config && config.userRights?.includes('assign')) {
      axios.get<{ data: { workers: Api.Worker[] } }>(`${config.url}/workers`, {
        params: {
          project: config.project
        },
        headers: config.headers || {}
      }).then((res) => {
        const data: SelectItem[] = []
        res.data.data.workers.forEach((worker) => {
          data.push({
            value: worker.id.toString(),
            label: worker.fullname
          })
        })
        setAssignData(data)
      })
    }
  }, [])


  // @ts-ignore
  return (
    <>
      <Modal
        opened={show}
        onClose={handleClose}
        closeOnClickOutside={false}
        fullScreen={true}
        withCloseButton={uploading ? false : true}
        zIndex={10000}
        className={'screenshot-hide'}
      >
        <Container sx={{
          position: 'relative'
        }}>
          <h2>{t('ModalFeedback.title')}</h2>
          {config.hotkey &&
            <>
              <Alert color='blue'>{t('ModalFeedback.shortcutInfo')}</Alert>
              <Space h={"sm"}/>
            </>
          }
          {screenshotError !== undefined && screenshotError === 'failed' &&
            <>
              <Alert color='red'>{t('ModalFeedback.screenshotError')}</Alert>
              <Space h={"sm"}/>
            </>}
          {'userRights' in config && (config.userRights?.includes("comment") || config.userRights?.includes("close")) &&
            <>
              <Button
                onClick={handleShowTask}
                fullWidth
              >
                {t('ModalFeedback.continueTask')}
              </Button>
              <Space h='sm'/>
            </>
          }
          <form onSubmit={form.onSubmit((data: any) => handleSubmit(data))}>
            {task === undefined &&
              <>
                <Select
                  color={config.color || 'primary'}
                  data={typeData}
                  withAsterisk
                  label={t('ModalFeedback.form.type.label')}
                  placeholder={`${t('ModalFeedback.form.type.placeholder')}`}
                  {...form.getInputProps('type')}
                />
                <Autocomplete
                  placeholder={`${t("ModalFeedback.form.title.placeholder")}`}
                  label={t("ModalFeedback.form.title.label")}
                  {...form.getInputProps('title')}
                  withAsterisk
                  data={autocompleteData}
                  minLength={1}
                  disabled={task !== undefined}
                />
              </>
            }
            {task !== undefined &&
              <>
                <TextInput
                  withAsterisk
                  label={t('ModalFeedback.form.task.label')}
                  disabled
                  {...form.getInputProps('type')}
                />
                {'userRights' in config && config.userRights?.includes('close') &&
                  <>
                    <Space h={'xs'}/>
                    <SegmentedControl
                      data={[
                        {value: 'comment', label: t('ModalFeedback.feedbackType.comment')},
                        {value: 'close', label: t('ModalFeedback.feedbackType.close')}
                      ]}
                      value={feedbackType}
                      color={feedbackType === 'close' ? 'green' : 'primary'}
                      onChange={(value: 'close' | 'comment') => setFeedbackType(value)}
                      fullWidth
                    />
                  </>
                }
                <TextInput
                  withAsterisk
                  label={t('ModalFeedback.form.title.label')}
                  disabled
                  {...form.getInputProps('title')}
                  sx={{display: "none"}}
                />
              </>
            }

            {'userRights' in config && config.userRights?.includes('assign') && feedbackType !== 'close' &&
              <Select
                data={assignData}
                placeholder={`${t("ModalFeedback.form.assign.placeholder")}`}
                label={t("ModalFeedback.form.assign.label")}
                {...form.getInputProps('assign')}
              />
            }
            <Textarea
              placeholder={`${t("ModalFeedback.form.description.placeholder")}`}
              label={t("ModalFeedback.form.description.label")}
              autosize
              minRows={2}
              maxRows={5}
              {...form.getInputProps('description')}
              withAsterisk
            />
            <Space h="md"/>
            <Stack>
              {!screenshot &&
                <Button fullWidth={true} onClick={onScreenshot}>
                  {t("ModalFeedback.form.buttons.takeScreenshot")}
                </Button>
              }
              {!record && false &&
                <Button fullWidth={true} onClick={onRecorder}>
                  {t("ModalFeedback.form.buttons.recordScreen")}
                </Button>
              }
              {!uploading && <Button fullWidth={true} type='submit'>
                {(screenshot || record) && t("ModalFeedback.form.buttons.send")}
                {(!screenshot && !record) && t("ModalFeedback.form.buttons.sendNoScreenshot")}
              </Button>}
              {uploading &&
                <>
                  <Text fw={700}>{t("ModalFeedback.form.buttons.uploadingFile")}</Text>
                  <Progress
                    label={`${uploadProgressTusScreenshot}%`}
                    size={"xl"}
                    color="green"
                    value={uploadProgressTusScreenshot}
                    sx={{width: '100%'}}
                  />
                </>
              }
            </Stack>
            {screenshot &&
              <>
                <Space h="md"/>
                <Container display={'center'}>
                  <img src={screenshot.image} style={{maxWidth: '100%', maxHeight: 200}} alt={'screenshot'}/>
                </Container>
              </>
            }
            {record &&
              <>
                <Space h="md"/>
                <Container display={'center'}>
                  <video src={record.blobUrl} controls autoPlay loop style={{maxWidth: '100%', maxHeight: 200}}/>
                </Container>
              </>
            }
            {/*{recorderError &&*/}
            {/*    <>*/}
            {/*        <Space h="md"/>*/}
            {/*        <Alert color={'red'} title={t('ModalFeedback.recorderError.title')}>{t(recorderError.message)}</Alert>*/}
            {/*    </>*/}
            {/*}*/}
          </form>
        </Container>
      </Modal>
      {config !== undefined &&
        <ModalTasks config={config} show={showTasks} onClose={handleSelectTask}/>
      }
    </>
  )
}
