import { useState } from 'react'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import FormControl from '@mui/material/FormControl'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import Select from '@mui/material/Select'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { createAvatar } from '@dicebear/core'
import { useUnit } from 'effector-react'
import { AVATAR_STYLE_LOADERS, DEFAULT_STYLE_ID, loadAvatarStyle } from '@/shared/lib/avatar-styles'
import { $user, updateProfileFx } from '@/shared/model/auth'
import { UserAvatar } from '@/shared/ui/UserAvatar'

export function AvatarSection() {
  const user = useUnit($user)
  const pendingProfile = useUnit(updateProfileFx.pending)

  const [selectedStyle, setSelectedStyle] = useState(user?.avatarStyle || DEFAULT_STYLE_ID)
  const [previewSrc, setPreviewSrc] = useState<string | null>(null)
  const [previewStyle, setPreviewStyle] = useState<string>(DEFAULT_STYLE_ID)

  const hasUnsavedPreview = previewSrc !== null

  if (!user) return null

  return (
    <Box>
      <Typography variant="h6" gutterBottom>
        Аватар
      </Typography>

      <Stack direction="row" spacing={3} sx={{ alignItems: 'flex-start', mb: 2 }}>
        <Box sx={{ textAlign: 'center' }}>
          <UserAvatar
            userId={user.id}
            avatarUrl={hasUnsavedPreview ? previewSrc : user.avatar}
            avatarStyle={hasUnsavedPreview ? previewStyle : user.avatarStyle}
            size={80}
            sx={{
              border: 2,
              borderColor: hasUnsavedPreview ? 'warning.main' : 'primary.main',
            }}
          />
          <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
            {hasUnsavedPreview ? 'Предпросмотр' : user.avatar ? 'Сохранён' : 'Авто'}
          </Typography>
        </Box>
        {hasUnsavedPreview && (
          <Box sx={{ textAlign: 'center' }}>
            <UserAvatar
              userId={user.id}
              avatarUrl={user.avatar}
              avatarStyle={user.avatarStyle}
              size={80}
              sx={{ border: 2, borderColor: 'divider', opacity: 0.6 }}
            />
            <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 0.5 }}>
              Текущий
            </Typography>
          </Box>
        )}
      </Stack>

      <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', gap: 1, mb: 1 }}>
        <FormControl size="small" sx={{ minWidth: 140 }}>
          <InputLabel>Стиль</InputLabel>
          <Select
            key={user?.avatarStyle || 'none'}
            value={selectedStyle}
            label="Стиль"
            onChange={(e) => setSelectedStyle(e.target.value)}
          >
            {AVATAR_STYLE_LOADERS.map((s) => (
              <MenuItem key={s.id} value={s.id}>
                {s.label}
              </MenuItem>
            ))}
          </Select>
        </FormControl>
        <Button
          variant="outlined"
          onClick={async () => {
            const seed = `${user.id}_${Date.now()}`
            const style = await loadAvatarStyle(selectedStyle)
            const avatar = createAvatar(style, { seed })
            setPreviewSrc(avatar.toDataUri())
            setPreviewStyle(selectedStyle)
          }}
        >
          Сгенерировать
        </Button>
      </Stack>

      {hasUnsavedPreview && (
        <Stack direction="row" spacing={1} sx={{ flexWrap: 'wrap', gap: 1, mb: 1 }}>
          <Button
            variant="contained"
            disabled={pendingProfile}
            onClick={() => {
              updateProfileFx({
                displayName: user.displayName?.trim() || null,
                avatar: previewSrc,
                avatarStyle: previewStyle,
              })
              setPreviewSrc(null)
            }}
          >
            Сохранить
          </Button>
          <Button variant="text" onClick={() => setPreviewSrc(null)}>
            Отмена
          </Button>
        </Stack>
      )}
    </Box>
  )
}
