import { useState } from 'react'
import { Box, Button, CircularProgress, Typography } from '@mui/material'
import { Sparkles } from 'lucide-react'
import { aiService } from '../../services/aiService'

interface AiOfferEmailButtonProps {
  needTitle: string
  selectedProperties: string[]
  matchScores: number[]
  onGenerated: (subject: string, body: string) => void
}

export function AiOfferEmailButton({
  needTitle,
  selectedProperties,
  matchScores,
  onGenerated,
}: AiOfferEmailButtonProps) {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  const handleClick = async () => {
    setLoading(true)
    setError(null)
    try {
      const res = await aiService.generateOfferEmail({
        needTitle,
        properties: selectedProperties,
        matchScores,
      })
      onGenerated(res.data.subject, res.data.body)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'KI-Generierung fehlgeschlagen')
    } finally {
      setLoading(false)
    }
  }

  return (
    <Box>
      <Button
        size="small"
        startIcon={loading ? <CircularProgress size={14} /> : <Sparkles size={14} />}
        onClick={handleClick}
        disabled={loading}
        sx={{
          textTransform: 'none',
          color: '#7c3aed',
          borderColor: '#c4b5fd',
          '&:hover': { bgcolor: '#f5f3ff', borderColor: '#7c3aed' },
        }}
        variant="outlined"
      >
        KI-Mail generieren
      </Button>
      {error && (
        <Typography variant="caption" sx={{ color: 'error.main', display: 'block', mt: 0.5 }}>
          {error}
        </Typography>
      )}
    </Box>
  )
}
