'use client'

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

// MUI Imports
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 Typography from '@mui/material/Typography'
import Checkbox from '@mui/material/Checkbox'
import FormControlLabel from '@mui/material/FormControlLabel'
import Switch from '@mui/material/Switch'
import Divider from '@mui/material/Divider'
import List from '@mui/material/List'
import ListItem from '@mui/material/ListItem'
import ListItemText from '@mui/material/ListItemText'
import Box from '@mui/material/Box'
import CircularProgress from '@mui/material/CircularProgress'

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

// Config
import type { RowId, CardId } from '@views/dashboards/farm/farmDashboardConfig'
import { ROW_IDS } from '@views/dashboards/farm/farmDashboardConfig'

type RowCardsType = Record<RowId, CardId[]>
type RowLabelsType = Record<RowId, string>
type CardLabelsType = Record<CardId, string>

type FarmDashboardSettingsDropdownProps = {
  disabledCardIds: string[]
  onToggleCard: (cardId: CardId, disabled: boolean) => void
  enableDragReorder: boolean
  onToggleDragReorder: (enabled: boolean) => void
  cardLabels: CardLabelsType
  rowLabels: RowLabelsType
  rowCards: RowCardsType
  saving?: boolean
}

const FarmDashboardSettingsDropdown = (props: FarmDashboardSettingsDropdownProps) => {
  const t = useTranslations('farmDashboard')
  const { disabledCardIds, onToggleCard, enableDragReorder, onToggleDragReorder, cardLabels, rowLabels, rowCards, saving } = props
  const { settings } = useSettings()
  const [open, setOpen] = useState(false)
  const anchorRef = useRef<HTMLButtonElement>(null)
  const disabledSet = new Set(disabledCardIds)

  const handleClose = () => setOpen(false)
  const handleToggle = () => setOpen(prev => !prev)

  return (
    <>
      <Box display='flex' alignItems='center' gap={0.5}>
        {saving && <CircularProgress size={20} />}
        <IconButton
          ref={anchorRef}
          onClick={handleToggle}
          aria-label={t('settings.ariaLabel')}
          className='text-textPrimary'
        >
          <i className='tabler-settings' />
        </IconButton>
      </Box>
      <Popper
        open={open}
        transition
        disablePortal
        placement='bottom-start'
        anchorEl={anchorRef.current}
        className='min-is-[300px] max-is-[360px] !mbs-3 z-[1400]'
      >
        {({ 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}>
                <Box className='flex flex-col max-bs-[70vh]'>
                  <Box className='p-4'>
                    <Typography variant='h6'>{t('settings.title')}</Typography>
                    <Typography variant='body2' color='text.secondary' sx={{ mt: 0.5 }}>
                      {t('settings.toggleCards')}
                    </Typography>
                  </Box>
                  <Box className='px-4 pb-2'>
                    <FormControlLabel
                      control={
                        <Switch
                          checked={enableDragReorder}
                          onChange={e => onToggleDragReorder(e.target.checked)}
                          size='small'
                        />
                      }
                      label={
                        <Typography variant='body2'>{t('settings.enableDragReorder')}</Typography>
                      }
                      sx={{ m: 0 }}
                    />
                  </Box>
                  <Divider />
                  <List
                    className='overflow-y-auto flex-1 px-4 pb-4'
                    sx={{ maxHeight: 'calc(70vh - 100px)' }}
                  >
                    {ROW_IDS.map(rowId => (
                      <Box key={rowId}>
                        <Typography variant='caption' color='text.secondary' sx={{ px: 0, py: 1, display: 'block' }}>
                          {rowLabels[rowId]}
                        </Typography>
                        {rowCards[rowId].map(cardId => {
                          const isDisabled = disabledSet.has(cardId)
                          return (
                            <ListItem key={cardId} disablePadding sx={{ py: 0.25 }}>
                              <FormControlLabel
                                control={
                                  <Checkbox
                                    checked={!isDisabled}
                                    onChange={e => onToggleCard(cardId, !e.target.checked)}
                                    size='small'
                                  />
                                }
                                label={
                                  <ListItemText
                                    primary={cardLabels[cardId]}
                                    primaryTypographyProps={{ variant: 'body2' }}
                                  />
                                }
                                sx={{ m: 0, width: '100%' }}
                              />
                            </ListItem>
                          )
                        })}
                      </Box>
                    ))}
                  </List>
                </Box>
              </ClickAwayListener>
            </Paper>
          </Fade>
        )}
      </Popper>
    </>
  )
}

export default FarmDashboardSettingsDropdown
