import React, { useEffect, useState } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { Box, Button, Card, CardContent, CardMedia, Typography, Container } from '@mui/material'
import { getByGameId, getUserById, changeGameLevel } from './GameDetails.api'
import { getUserId } from '../../../Config'

import Swal from 'sweetalert2'

interface GameUserData {
  intermediateGameLevel: string
  advancedGameLevel: string
}

const GameDetails: React.FC = () => {
  const navigate = useNavigate()

  const { gameId, resourcesId } = useParams()
  const [video, setVideo] = useState<any>('')
  const [q, setQ] = useState<any>('')
  const [a1, setA1] = useState<any>('')
  const [a2, setA2] = useState<any>('')
  const [a3, setA3] = useState<any>('')
  const [a4, setA4] = useState<any>('')
  const [correct, setCorrect] = useState<any>('')
  const [level, setLevel] = useState<any>('')
  const [userdata, setUserData] = useState<GameUserData>({
    intermediateGameLevel: '',
    advancedGameLevel: '',
  })

  useEffect(() => {
    getUserById(getUserId())
      .then((result) => {
        setUserData((prevUserData) => ({
          ...prevUserData,
          ...result.data,
        }))
      })
      .catch((error) => {
        console.error('Error fetching data:', error)
      })
  }, [getUserById])

  useEffect(() => {
    if (gameId) {
      getByGameId(gameId)
        .then((result) => {
          setVideo(result.data.video)
          setQ(result.data.question)
          setA1(result.data.a1)
          setA2(result.data.a2)
          setA3(result.data.a3)
          setA4(result.data.a4)
          setCorrect(result.data.correct)
          setLevel(result.data.level)
        })
        .catch((error) => {
          console.error('Error fetching data:', error)
        })
    }
  }, [gameId])

  const handleAnswerClick = (answer: any) => {
    if (correct === answer) {
      void Swal.fire({
        position: 'center',
        icon: 'success',
        title: 'Correct Answer',
        showConfirmButton: false,
        timer: 2000,
      }).then(() => {
        if (resourcesId === 'Intermediate') {
          userdata.intermediateGameLevel = userdata.intermediateGameLevel + 1
        } else if (resourcesId === 'Advanced') {
          userdata.advancedGameLevel = userdata.advancedGameLevel + 1
        }
        changeGameLevel(getUserId(), userdata)
          .then((result) => {
            if (result.message === 'updated') {
              navigate('/game/' + level)
            }
          })
          .catch((error) => {
            console.error('Error fetching data:', error)
          })
      })
    } else {
      void Swal.fire({
        position: 'center',
        icon: 'error',
        title: 'Wornge Answer',
        showConfirmButton: false,
        timer: 2000,
      }).then(() => {
        navigate('/game/' + level)
      })
    }
  }

  return (
    <Container maxWidth='sm' sx={{ mt: 4 }}>
      <Box sx={{ maxWidth: 400, mx: 'auto' }}>
        <Card>
          <CardMedia
            component='video'
            src={video}
            controls
            autoPlay
            muted
            title='Game Video'
            sx={{ height: 240 }}
          />
          <CardContent>
            <Typography gutterBottom variant='h5' component='div' textAlign='center'>
              {q}
            </Typography>

            <Button
              variant='contained'
              color='primary'
              onClick={() => handleAnswerClick(a1)}
              sx={{ display: 'block', width: '100%', mb: 2 }}
            >
              {a1}
            </Button>
            <Button
              variant='contained'
              color='primary'
              onClick={() => handleAnswerClick(a2)}
              sx={{ display: 'block', width: '100%', mb: 2 }}
            >
              {a2}
            </Button>
            <Button
              variant='contained'
              color='primary'
              onClick={() => handleAnswerClick(a3)}
              sx={{ display: 'block', width: '100%', mb: 2 }}
            >
              {a3}
            </Button>
            <Button
              variant='contained'
              color='primary'
              onClick={() => handleAnswerClick(a4)}
              sx={{ display: 'block', width: '100%', mb: 2 }}
            >
              {a4}
            </Button>
          </CardContent>
        </Card>
      </Box>
    </Container>
  )
}

export default GameDetails
