import React, { useEffect } from 'react'
import {
  Box,
  Button,
  HStack,
  Text,
  Textarea,
  VStack,
} from '@chakra-ui/react'

import type { ChallengeTask } from '../../__data__/types'
import { useChallenge } from '../../context/ChallengeContext'
import { useSubmission } from '../../hooks/useSubmission'
import { CheckStatusView } from './CheckStatusView'
import { ResultView } from './ResultView'

interface TaskWorkspaceProps {
  task: ChallengeTask
  onTaskComplete?: () => void
}

export const TaskWorkspace = ({ task, onTaskComplete }: TaskWorkspaceProps) => {
  const { refreshStats } = useChallenge()
  const { result, setResult, submit, reset, queueStatus, finalSubmission, isSubmitting } = useSubmission({
    taskId: task.id,
  })

  const descriptionBg = 'gray.50'

  useEffect(() => {
    if (finalSubmission) {
      refreshStats()
    }
  }, [finalSubmission, refreshStats])

  if (queueStatus) {
    return <CheckStatusView status={queueStatus} />
  }

  if (finalSubmission) {
    return (
      <ResultView submission={finalSubmission} onRetry={reset} onNext={onTaskComplete} />
    )
  }

  return (
    <VStack align="stretch" spacing={4}>
      <Box borderWidth="1px" borderRadius="lg" borderColor="gray.200" p={4} bg={descriptionBg}>
        <Text fontSize="lg" fontWeight="semibold" mb={2}>
          {task.title}
        </Text>
        <Text whiteSpace="pre-line" color="gray.700">
          {task.description}
        </Text>
      </Box>

      <Box>
        <Text fontWeight="medium" mb={2}>
          Ваше решение
        </Text>
        <Textarea
          value={result}
          onChange={(event) => setResult(event.target.value)}
          placeholder="Напишите ваше решение..."
          rows={14}
          bg="white"
        />
      </Box>

      <HStack justify="flex-end" spacing={3}>
        <Button onClick={reset} variant="ghost">
          Сбросить
        </Button>
        <Button onClick={submit} colorScheme="teal" isLoading={isSubmitting} isDisabled={!result.trim()}>
          Отправить на проверку
        </Button>
      </HStack>
    </VStack>
  )
}

