'use client'

import React, { useEffect, useState } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { setLanguage } from '@/redux/slices/languageSlice'
import { fetchLanguages } from '../../../public/mock/languageApi'
import { RootState } from '@/redux/store'
import { Tabs, Tab, Box, CircularProgress } from '@mui/material'

const LanguageSelector: React.FC = () => {
  const [languages, setLanguages] = useState<
    { lang_id: number; lang_name: string; lang_native_name: string }[]
  >([])
  const selectedLanguage = useSelector((state: RootState) => state.language)
  const dispatch = useDispatch()

  // Fetch languages on component mount
  useEffect(() => {
    const getLanguages = async () => {
      const response = await fetchLanguages()
      if (response.status === 'success') {
        setLanguages(response.data)
        // Set the first language as the default language if none is selected
        if (!selectedLanguage) {
          dispatch(setLanguage(response.data[0].lang_name))
        }
      }
    }
    getLanguages()
  }, [dispatch, selectedLanguage]) // Only depend on dispatch and selectedLanguage

  if (languages.length === 0) {
    return (
      <Box textAlign="center" mt={4}>
        <CircularProgress />
      </Box>
    )
  }

  return (
    <Box
      id="fr_languages"
      sx={{
        display: 'flex',
        justifyContent: 'center',
        padding: '8px',
        margin: '8px',
      }}
    >
      <Tabs
        className="fr_language_tabs"
        value={selectedLanguage || ''}
        onChange={(e, val) => dispatch(setLanguage(val))}
      >
        {languages.map((lang) => (
          <Tab
            className="fr_language_tab"
            key={lang.lang_id}
            value={lang.lang_name} // Use string values consistently
            label={lang.lang_native_name}
          />
        ))}
      </Tabs>
    </Box>
  )
}

export default LanguageSelector
