import { Box, Button, Card, Typography } from '@mui/material'
import { ArrowRight, RefreshCw } from 'lucide-react'
import type { FollowUpQuestion } from '../../domain/needBuilder'
import { FollowUpQuestionCard } from './FollowUpQuestionCard'

interface Props {
  questions: FollowUpQuestion[]
  answers: Record<string, string>
  onAnswer: (id: string, answer: string) => void
  onContinue: () => void
  onReparse?: () => void
}

export function FollowUpPanel({ questions, answers, onAnswer, onContinue, onReparse }: Props) {
  const requiredUnanswered = questions
    .filter(q => q.importance === 'required')
    .filter(q => !answers[q.id])

  const sorted = [
    ...questions.filter(q => q.importance === 'required'),
    ...questions.filter(q => q.importance === 'recommended'),
    ...questions.filter(q => q.importance === 'optional'),
  ]

  return (
    <Card sx={{ p: 3, height: '100%', display: 'flex', flexDirection: 'column' }}>
      <Typography variant="subtitle1" sx={{ fontWeight: 600, mb: 0.5 }}>
        Rückfragen der KI
      </Typography>
      <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mb: 2 }}>
        Beantworten Sie die Pflichtfelder für optimale Ergebnisse. Optionale Fragen können übersprungen werden.
      </Typography>

      <Box sx={{ flex: 1, overflow: 'auto' }}>
        <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
          {sorted.map(q => (
            <FollowUpQuestionCard
              key={q.id}
              question={q}
              answer={answers[q.id] ?? ''}
              onAnswer={ans => onAnswer(q.id, ans)}
            />
          ))}
        </Box>
      </Box>

      <Box sx={{ pt: 2, mt: 'auto', display: 'flex', flexDirection: 'column', gap: 1 }}>
        {requiredUnanswered.length > 0 && (
          <Typography variant="caption" color="error">
            {requiredUnanswered.length} Pflichtfeld{requiredUnanswered.length > 1 ? 'er fehlen' : ' fehlt'} noch.
          </Typography>
        )}
        {onReparse && (
          <Button
            variant="outlined"
            size="small"
            startIcon={<RefreshCw size={14} />}
            onClick={onReparse}
          >
            Rückfragen neu generieren
          </Button>
        )}
        <Button
          variant="contained"
          fullWidth
          disabled={requiredUnanswered.length > 0}
          onClick={onContinue}
          endIcon={<ArrowRight size={16} />}
          sx={{ bgcolor: '#152642', '&:hover': { bgcolor: '#162d4a' } }}
        >
          Weiter zur Gewichtung
        </Button>
      </Box>
    </Card>
  )
}
