'use client'

import React, { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useRouter } from 'next/navigation' // Use 'next/navigation' for the new Next.js App Router
import { fetchVideos } from '../../../public/mock/videoApi'
import {
  setVideos,
  addVideos,
  incrementPage,
  setSelectedVideo,
} from '@/redux/slices/videoSlice'
import { RootState } from '@/redux/store'
import { Card, CardMedia, CardContent, Typography, Button } from '@mui/material'
import Grid from '@mui/material/Grid2'
import { Video } from '@/redux/slices/types'

const VideoGrid: React.FC = () => {
  const { videos, page } = useSelector((state: RootState) => state.videos)
  const selectedCourse = useSelector((state: RootState) => state.course)
  const selectedLanguage = useSelector((state: RootState) => state.language)
  const dispatch = useDispatch()
  const router = useRouter() // Use the updated useRouter hook

  useEffect(() => {
    // Fetch initial videos based on course and language
    const fetchedVideos = fetchVideos(selectedCourse, selectedLanguage, 1)
    dispatch(setVideos({ videos: fetchedVideos }))
  }, [selectedCourse, selectedLanguage, dispatch])

  const loadMore = () => {
    // Fetch more videos for pagination
    const fetchedVideos = fetchVideos(
      selectedCourse,
      selectedLanguage,
      page + 1,
    )
    if (fetchedVideos.length) {
      dispatch(addVideos({ videos: fetchedVideos }))
      dispatch(incrementPage())
    }
  }

  const handleVideoClick = (video: Video) => {
    // Dispatch selected video to Redux
    dispatch(setSelectedVideo({ video }))
    router.push('/explorecoursedetails')
  }

  return (
    <div>
      <Grid
        container
        spacing={3}
        justifyContent="center"
        alignItems="center"
        style={{ maxWidth: '1200px', margin: '0 auto' }}
      >
        {videos.map((video) => (
          <Grid key={video.id}>
            <Card
              onClick={() => handleVideoClick(video)}
              style={{ cursor: 'pointer' }}
            >
              <CardMedia
                component="img"
                height="140"
                image={video.image}
                alt={video.title}
              />
              <CardContent>
                <Typography variant="h6">{video.title}</Typography>
              </CardContent>
            </Card>
          </Grid>
        ))}
      </Grid>
      <Button
        variant="contained"
        onClick={loadMore}
        style={{ display: 'flex', margin: '2% auto 2% auto', backgroundColor: "#16A6A7" }}
      >
        View All
      </Button>
    </div>
  )
}

export default VideoGrid
