'use client'
import { useState, useEffect } from 'react'
import { Box, Paper, Typography, Button, Slider, FormControl, InputLabel, Select, MenuItem, useMediaQuery, useTheme, IconButton } from '@mui/material'
import { Close } from '@mui/icons-material'
import { ReadingPreference } from '@/types'
import { getPreset, loadPreferences, savePreferences } from '@/lib/reading-preferences'

const FONTS = [
  { value: 'georgia', label: 'Georgia (Serif)' },
  { value: 'merriweather', label: 'Merriweather (Serif)' },
  { value: 'inter', label: 'Inter (Sans)' },
  { value: 'atkinson', label: 'Atkinson (Dyslexia-friendly)' },
]

interface ReadingSettingsProps {
  onClose: () => void
}

export function ReadingSettings({ onClose }: ReadingSettingsProps) {
  const theme = useTheme()
  const isMobile = useMediaQuery(theme.breakpoints.down('sm'))
  const [preferences, setPreferences] = useState<ReadingPreference>(loadPreferences())

  // Reload preferences on mount
  useEffect(() => {
    setPreferences(loadPreferences())
  }, [])

  const applyPreset = (presetName: string) => {
    const preset = getPreset(presetName as any)
    setPreferences(preset)
    savePreferences(preset)
    // Trigger a storage event to notify other components
    window.dispatchEvent(new Event('storage'))
  }

  const handleChange = (key: keyof ReadingPreference, value: any) => {
    const updated: ReadingPreference = {
      ...preferences,
      [key]: value,
      preset: 'custom' as const
    }
    setPreferences(updated)
    savePreferences(updated)
    // Trigger a storage event to notify other components
    window.dispatchEvent(new Event('storage'))
  }

  const content = (
    <Box sx={{ p: 3, maxWidth: 400 }}>
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Typography variant="h6">Reading Settings</Typography>
        <IconButton size="small" onClick={onClose} aria-label="Close settings">
          <Close />
        </IconButton>
      </Box>

      {/* Presets */}
      <Box sx={{ mb: 3 }}>
        <Typography variant="subtitle2" sx={{ mb: 1 }}>Presets</Typography>
        <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
          {['default', 'dyslexia', 'highContrast', 'minimal'].map((preset) => (
            <Button
              key={preset}
              variant={preferences.preset === preset ? 'contained' : 'outlined'}
              onClick={() => applyPreset(preset)}
              size="small"
              sx={{ textTransform: 'capitalize' }}
            >
              {preset === 'highContrast' ? 'High Contrast' : preset}
            </Button>
          ))}
        </Box>
      </Box>

      {/* Font */}
      <FormControl fullWidth sx={{ mb: 2 }}>
        <InputLabel>Font</InputLabel>
        <Select
          value={preferences.fontFamily}
          label="Font"
          onChange={(e) => handleChange('fontFamily', e.target.value)}
        >
          {FONTS.map((font) => (
            <MenuItem key={font.value} value={font.value}>
              {font.label}
            </MenuItem>
          ))}
        </Select>
      </FormControl>

      {/* Font Size */}
      <Box sx={{ mb: 2 }}>
        <Typography variant="body2">Size: {preferences.fontSize}px</Typography>
        <Slider
          value={preferences.fontSize}
          onChange={(_, value) => handleChange('fontSize', value)}
          min={12}
          max={32}
          step={1}
          marks={[
            { value: 12, label: '12' },
            { value: 22, label: '22' },
            { value: 32, label: '32' },
          ]}
        />
      </Box>

      {/* Line Height */}
      <Box sx={{ mb: 2 }}>
        <Typography variant="body2">Line Height: {preferences.lineHeight.toFixed(1)}x</Typography>
        <Slider
          value={preferences.lineHeight}
          onChange={(_, value) => handleChange('lineHeight', value)}
          min={1.4}
          max={2.2}
          step={0.1}
          marks={[
            { value: 1.4, label: '1.4' },
            { value: 1.8, label: '1.8' },
            { value: 2.2, label: '2.2' },
          ]}
        />
      </Box>

      {/* Background Color */}
      <FormControl fullWidth sx={{ mb: 2 }}>
        <InputLabel>Background</InputLabel>
        <Select
          value={preferences.backgroundColor}
          label="Background"
          onChange={(e) => handleChange('backgroundColor', e.target.value)}
        >
          <MenuItem value="#faf8f3">Warm</MenuItem>
          <MenuItem value="#ffffff">White</MenuItem>
          <MenuItem value="#f5f5f5">Light Gray</MenuItem>
          <MenuItem value="#1a1a1a">Dark</MenuItem>
        </Select>
      </FormControl>
    </Box>
  )

  if (isMobile) {
    return (
      <Box
        sx={{
          position: 'fixed',
          bottom: 0,
          left: 0,
          right: 0,
          maxHeight: '80vh',
          backgroundColor: 'white',
          borderTopLeftRadius: 16,
          borderTopRightRadius: 16,
          zIndex: 100,
          overflow: 'auto',
          boxShadow: '0 -4px 20px rgba(0,0,0,0.1)',
        }}
      >
        {content}
      </Box>
    )
  }

  return (
    <Paper
      sx={{
        position: 'fixed',
        right: 0,
        top: 0,
        bottom: 0,
        width: 400,
        zIndex: 100,
        borderRadius: 0,
        overflow: 'auto',
        boxShadow: '-4px 0 20px rgba(0,0,0,0.1)',
      }}
    >
      {content}
    </Paper>
  )
}
