import ClearIcon from '@mui/icons-material/Clear'
import InputIcon from '@mui/icons-material/Input'
import IosShareIcon from '@mui/icons-material/IosShare'
import {
  List,
  ListItemButton,
  ListItemIcon,
  ListItemText,
  ListSubheader,
  useTheme
} from '@mui/material'
import { useState } from 'react'
import { toast } from 'react-toastify'
import { localCache } from '../../../services'
import { LoadingSpinner } from '../../../components/LoadingSpinner'
import { Container } from '../../../components/Container'
import { Footer } from '../../../components/Footer/Footer'

export const CacheSettingsPage = () => {
  const theme = useTheme()

  const [isLoading, setIsLoading] = useState(false)
  const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')

  const handleClearData = async () => {
    setIsLoading(true)
    setLoadingSpinnerDesc('Clearing cache data')
    localCache
      .clearCacheData()
      .then(() => {
        toast.success('cleared cached data')
      })
      .catch((err) => {
        console.log('An error occurred in clearing cache data', err)
        toast.error(err.message || 'An error occurred in clearing cache data')
      })
      .finally(() => {
        setIsLoading(false)
      })
  }

  const listItem = (label: string) => {
    return (
      <ListItemText
        primary={label}
        sx={{
          color: theme.palette.text.primary
        }}
      />
    )
  }

  return (
    <>
      <Container>
        {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
        <List
          sx={{
            width: '100%',
            bgcolor: 'background.paper',
            marginTop: 2
          }}
          subheader={
            <ListSubheader
              sx={{
                fontSize: '1.5rem',
                borderBottom: '0.5px solid',
                paddingBottom: 2,
                paddingTop: 2
              }}
            >
              Cache Setting
            </ListSubheader>
          }
        >
          <ListItemButton disabled>
            <ListItemIcon>
              <IosShareIcon />
            </ListItemIcon>
            {listItem('Export (coming soon)')}
          </ListItemButton>

          <ListItemButton disabled>
            <ListItemIcon>
              <InputIcon />
            </ListItemIcon>
            {listItem('Import (coming soon)')}
          </ListItemButton>

          <ListItemButton onClick={handleClearData}>
            <ListItemIcon>
              <ClearIcon sx={{ color: theme.palette.error.main }} />
            </ListItemIcon>
            {listItem('Clear Cache')}
          </ListItemButton>
        </List>
      </Container>
      <Footer />
    </>
  )
}
