import { useState } from 'react'
import { Box, Button, Card, Slider, Typography } from '@mui/material'
import { RotateCcw } from 'lucide-react'
import { WEIGHTING_KEYS, WEIGHTING_LABELS } from '../../domain/needBuilder'
import type { WeightingKey } from '../../domain/needBuilder'
import { weightingService } from '../../services/weightingService'

interface Props {
  weights: Record<WeightingKey, number>
  onChange: (weights: Record<WeightingKey, number>) => void
  assetType?: string
}

const IMPORTANCE_LABELS = ['', 'Unwichtig', 'Wenig wichtig', 'Wichtig', 'Sehr wichtig', 'Entscheidend']

function toRaw(w: Record<WeightingKey, number>): Record<WeightingKey, number> {
  const max = Math.max(...WEIGHTING_KEYS.map(k => w[k] ?? 0))
  if (max === 0) return Object.fromEntries(WEIGHTING_KEYS.map(k => [k, 3])) as Record<WeightingKey, number>
  return Object.fromEntries(
    WEIGHTING_KEYS.map(k => [k, Math.max(1, Math.round(((w[k] ?? 0) / max) * 5))])
  ) as Record<WeightingKey, number>
}

function rawToWeights(raw: Record<WeightingKey, number>): Record<WeightingKey, number> {
  const total = WEIGHTING_KEYS.reduce((s, k) => s + (raw[k] ?? 1), 0)
  return Object.fromEntries(
    WEIGHTING_KEYS.map(k => [k, (raw[k] ?? 1) / total])
  ) as Record<WeightingKey, number>
}

export function WeightingEditor({ weights, onChange, assetType }: Props) {
  const [raw, setRaw] = useState<Record<WeightingKey, number>>(() => toRaw(weights))

  function handleSlider(key: WeightingKey, value: number) {
    const updated = { ...raw, [key]: value }
    setRaw(updated)
    onChange(rawToWeights(updated))
  }

  function handleReset() {
    const defaults = weightingService.getDefaultWeights(assetType)
    setRaw(toRaw(defaults))
    onChange(defaults)
  }

  return (
    <Box sx={{ maxWidth: 720, mx: 'auto' }}>
      <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 2 }}>
        <Box>
          <Typography variant="subtitle1" sx={{ fontWeight: 600 }}>
            Wichtigkeit der Kriterien
          </Typography>
          <Typography variant="caption" color="text.secondary">
            Schieber nach rechts = wichtiger. Gewichtung wird automatisch berechnet.
          </Typography>
        </Box>
        <Button
          size="small"
          variant="outlined"
          startIcon={<RotateCcw size={14} />}
          onClick={handleReset}
        >
          Zurücksetzen
        </Button>
      </Box>

      <Card sx={{ p: 3 }}>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2.5 }}>
          {WEIGHTING_KEYS.map(key => {
            const importance = raw[key] ?? 3
            return (
              <Box key={key}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 0.5 }}>
                  <Typography variant="body2" sx={{ fontWeight: 500 }}>
                    {WEIGHTING_LABELS[key]}
                  </Typography>
                  <Typography variant="caption" color="text.secondary">
                    {IMPORTANCE_LABELS[importance]}
                  </Typography>
                </Box>
                <Slider
                  value={importance}
                  min={1}
                  max={5}
                  step={1}
                  marks
                  onChange={(_, v) => handleSlider(key, v as number)}
                  size="small"
                  sx={{ color: '#1e3a5f' }}
                />
              </Box>
            )
          })}
        </Box>
      </Card>
    </Box>
  )
}
