import { Box, Button, CircularProgress, Typography } from '@mui/material'
import { Sparkles } from 'lucide-react'
import { useGenerateOfferEmail } from '../../hooks/useAI'

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

export function AiOfferEmailButton({
  needTitle,
  selectedProperties,
  matchScores,
  onGenerated,
}: AiOfferEmailButtonProps) {
  const generateOfferEmail = useGenerateOfferEmail()

  const handleClick = () => {
    generateOfferEmail.mutate(
      { needTitle, properties: selectedProperties, matchScores },
      {
        onSuccess: (res) => {
          onGenerated(res.data.subject, res.data.body)
        },
      },
    )
  }

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