'use client'

// React Imports
import { useRef, useState, useMemo } from 'react'
import { useTranslations } from 'next-intl'

// MUI Imports
import Tooltip from '@mui/material/Tooltip'
import IconButton from '@mui/material/IconButton'
import Popper from '@mui/material/Popper'
import Fade from '@mui/material/Fade'
import Paper from '@mui/material/Paper'
import ClickAwayListener from '@mui/material/ClickAwayListener'
import MenuList from '@mui/material/MenuList'
import MenuItem from '@mui/material/MenuItem'
import Divider from '@mui/material/Divider'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'

// Config Imports
import primaryColorConfig from '@configs/primaryColorConfig'

// Hook Imports
import { useSettings } from '@core/hooks/useSettings'

// Type Imports
import type { SystemMode } from '@core/types'

const ThemeColorDropdown = () => {
  const t = useTranslations('theme')

  // States
  const [open, setOpen] = useState(false)
  const [tooltipOpen, setTooltipOpen] = useState(false)
  const [previewMode, setPreviewMode] = useState<'light' | 'dark'>('light')

  // Refs
  const anchorRef = useRef<HTMLButtonElement>(null)

  // Hooks
  const { settings, updateSettings } = useSettings()

  // Get current mode
  const currentMode: SystemMode = useMemo(() => {
    if (settings.mode === 'system') {
      if (typeof window !== 'undefined') {
        return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      }
      return 'light'
    }
    return settings.mode as SystemMode
  }, [settings.mode])

  // Get selected palette
  const selectedPaletteId = settings.primaryColorPaletteId || primaryColorConfig[0].id
  const selectedPalette = primaryColorConfig.find(p => p.id === selectedPaletteId) || primaryColorConfig[0]

  const handleClose = () => {
    setOpen(false)
    setTooltipOpen(false)
  }

  const handleToggle = () => {
    setOpen(prevOpen => !prevOpen)
    // Reset preview mode to current mode when opening
    if (!open) {
      setPreviewMode(currentMode)
    }
  }

  const handlePaletteChange = (paletteId: string) => {
    handleClose()

    if (settings.primaryColorPaletteId !== paletteId) {
      updateSettings({ primaryColorPaletteId: paletteId })
    }
  }

  const handlePreviewModeChange = (mode: 'light' | 'dark') => {
    setPreviewMode(mode)
  }

  const isPaletteSelected = (paletteId: string) => {
    return selectedPaletteId === paletteId
  }

  return (
    <>
      <Tooltip
        title={t('colorPalette')}
        onOpen={() => setTooltipOpen(true)}
        onClose={() => setTooltipOpen(false)}
        open={open ? false : tooltipOpen ? true : false}
      >
        <IconButton ref={anchorRef} onClick={handleToggle} className='text-textPrimary'>
          <i className='tabler-palette' />
        </IconButton>
      </Tooltip>
      <Popper
        open={open}
        transition
        disablePortal
        placement='bottom-start'
        anchorEl={anchorRef.current}
        className='min-is-[280px] !mbs-3 z-[1]'
      >
        {({ TransitionProps, placement }) => (
          <Fade
            {...TransitionProps}
            style={{ transformOrigin: placement === 'bottom-start' ? 'left top' : 'right top' }}
          >
            <Paper className={settings.skin === 'bordered' ? 'border shadow-none' : 'shadow-lg'}>
              <ClickAwayListener onClickAway={handleClose}>
                <MenuList onKeyDown={handleClose}>
                  {/* Mode Preview Selection */}
                  <Box className='pis-4 pie-4 pbs-2 pbe-2'>
                    <Typography variant='caption' className='text-textSecondary uppercase'>
                      {t('previewMode')}
                    </Typography>
                    <Box className='flex gap-2 mts-2'>
                      <MenuItem
                        className='flex-1 gap-2 rounded'
                        onClick={() => handlePreviewModeChange('light')}
                        selected={previewMode === 'light'}
                        sx={{ minHeight: 'auto', py: 1 }}
                      >
                        <i className='tabler-sun text-sm' />
                        <span className='text-sm'>{t('light')}</span>
                      </MenuItem>
                      <MenuItem
                        className='flex-1 gap-2 rounded'
                        onClick={() => handlePreviewModeChange('dark')}
                        selected={previewMode === 'dark'}
                        sx={{ minHeight: 'auto', py: 1 }}
                      >
                        <i className='tabler-moon-stars text-sm' />
                        <span className='text-sm'>{t('dark')}</span>
                      </MenuItem>
                    </Box>
                  </Box>
                  <Divider />
                  {/* Palette Selection */}
                  {primaryColorConfig.map((palette) => {
                    const colors = previewMode === 'light' ? palette.light : palette.dark
                    const isSelected = isPaletteSelected(palette.id)

                    return (
                      <MenuItem
                        key={palette.id}
                        className='gap-3'
                        onClick={() => handlePaletteChange(palette.id)}
                        selected={isSelected}
                      >
                        <Box className='flex items-center gap-2'>
                          {/* Light Preview */}
                          <Box
                            className='is-8 bs-8 rounded-full border border-border flex items-center justify-center'
                            style={{ backgroundColor: palette.light.main }}
                            title={t('lightMode')}
                          >
                            <i className='tabler-sun text-[10px] text-white' style={{ opacity: 0.7 }} />
                          </Box>
                          {/* Dark Preview */}
                          <Box
                            className='is-8 bs-8 rounded-full border border-border flex items-center justify-center'
                            style={{ backgroundColor: palette.dark.main }}
                            title={t('darkMode')}
                          >
                            <i className='tabler-moon-stars text-[10px] text-white' style={{ opacity: 0.7 }} />
                          </Box>
                        </Box>
                        <Box className='flex flex-col flex-1'>
                          <span className='text-sm font-medium'>{t(`palettes.${palette.paletteKey}`)}</span>
                          <Box className='flex items-center gap-1 mts-1'>
                            <Box
                              className='is-4 bs-4 rounded-full border border-border'
                              style={{ backgroundColor: colors.main }}
                              title={t('main')}
                            />
                            <Box
                              className='is-4 bs-4 rounded-full border border-border'
                              style={{ backgroundColor: colors.light }}
                              title={t('light')}
                            />
                            <Box
                              className='is-4 bs-4 rounded-full border border-border'
                              style={{ backgroundColor: colors.dark }}
                              title={t('dark')}
                            />
                          </Box>
                        </Box>
                      </MenuItem>
                    )
                  })}
                </MenuList>
              </ClickAwayListener>
            </Paper>
          </Fade>
        )}
      </Popper>
    </>
  )
}

export default ThemeColorDropdown
