All files / src/components/organizer/EventPage AiAssistDrawer.tsx

31.11% Statements 14/45
25.8% Branches 8/31
5.55% Functions 1/18
31.81% Lines 14/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265                                                                          3x 3x 3x 3x 3x 3x   3x 3x 3x   3x                             3x                 3x                                   3x                                   3x                                                                                                                                                                                                                                                                                                                        
import { useState } from 'react';
import {
  Drawer,
  Box,
  Typography,
  IconButton,
  Divider,
  Button,
  CircularProgress,
  Snackbar,
  Alert,
  Paper,
  Tooltip,
} from '@mui/material';
import { Close as CloseIcon, AutoAwesome, ContentCopy, Check } from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import {
  useAiGenerateDescription,
  useAiGenerateThemeImage,
  useAiApplyThemeImage,
} from '@/hooks/useAiAssist';
 
interface AiAssistDrawerProps {
  eventCode: string;
  open: boolean;
  onClose: () => void;
  onDescriptionGenerated: (text: string) => void;
  onImageGenerated: (imageUrl: string, s3Key: string) => void;
}
 
export function AiAssistDrawer({
  eventCode,
  open,
  onClose,
  onDescriptionGenerated,
  onImageGenerated,
}: AiAssistDrawerProps) {
  const { t } = useTranslation('organizer');
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [generatedDescription, setGeneratedDescription] = useState<string | null>(null);
  const [copied, setCopied] = useState(false);
  const [generatedImageUrl, setGeneratedImageUrl] = useState<string | null>(null);
  const [generatedImageS3Key, setGeneratedImageS3Key] = useState<string | null>(null);
 
  const descriptionMutation = useAiGenerateDescription(eventCode);
  const imageMutation = useAiGenerateThemeImage(eventCode);
  const applyMutation = useAiApplyThemeImage(eventCode);
 
  const handleGenerateDescription = () => {
    setErrorMessage(null);
    setGeneratedDescription(null);
    setCopied(false);
    descriptionMutation.mutate(undefined, {
      onSuccess: (data) => {
        setGeneratedDescription(data.description);
        onDescriptionGenerated(data.description);
      },
      onError: (err) => {
        setErrorMessage(err.message);
      },
    });
  };
 
  const handleCopyDescription = () => {
    if (generatedDescription) {
      navigator.clipboard.writeText(generatedDescription).then(() => {
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
      });
    }
  };
 
  const handleGenerateImage = (regenerate = false) => {
    setErrorMessage(null);
    setGeneratedImageUrl(null);
    setGeneratedImageS3Key(null);
    imageMutation.mutate(
      { seed: regenerate ? crypto.randomUUID() : undefined },
      {
        onSuccess: (data) => {
          setGeneratedImageUrl(data.imageUrl);
          setGeneratedImageS3Key(data.s3Key);
        },
        onError: (err) => {
          setErrorMessage(err.message);
        },
      }
    );
  };
 
  const handleUseImage = () => {
    if (generatedImageUrl && generatedImageS3Key) {
      applyMutation.mutate(
        { imageUrl: generatedImageUrl },
        {
          onSuccess: () => {
            onImageGenerated(generatedImageUrl, generatedImageS3Key);
            setGeneratedImageUrl(null);
            setGeneratedImageS3Key(null);
          },
          onError: (err) => {
            setErrorMessage(err.message);
          },
        }
      );
    }
  };
 
  return (
    <>
      <Drawer
        anchor="right"
        open={open}
        onClose={onClose}
        PaperProps={{ sx: { width: { xs: '100%', sm: 480 } } }}
      >
        <Box sx={{ p: 2, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <Typography variant="h6">
            <AutoAwesome sx={{ mr: 1, verticalAlign: 'middle' }} />
            {t('aiAssist.generateDescription', '✨ Generate with AI')}
          </Typography>
          <IconButton onClick={onClose} size="small">
            <CloseIcon />
          </IconButton>
        </Box>
        <Divider />
 
        <Box sx={{ p: 2, display: 'flex', flexDirection: 'column', gap: 2 }}>
          {/* Description generation */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              {t('aiAssist.generateDescription', '✨ Beschreibung generieren')}
            </Typography>
            <Button
              variant="contained"
              startIcon={
                descriptionMutation.isPending ? (
                  <CircularProgress size={16} color="inherit" />
                ) : (
                  <AutoAwesome />
                )
              }
              disabled={descriptionMutation.isPending}
              onClick={handleGenerateDescription}
              fullWidth
            >
              {descriptionMutation.isPending
                ? t('aiAssist.generating', 'Generieren...')
                : t('aiAssist.generateDescription', '✨ Beschreibung generieren')}
            </Button>
            {generatedDescription && (
              <Paper variant="outlined" sx={{ mt: 1, p: 1.5, position: 'relative' }}>
                <Typography
                  variant="body2"
                  sx={{ whiteSpace: 'pre-wrap', maxHeight: 300, overflowY: 'auto', pr: 4 }}
                >
                  {generatedDescription}
                </Typography>
                <Tooltip
                  title={
                    copied
                      ? t('aiAssist.copied', 'Copied!')
                      : t('aiAssist.copy', 'Copy to clipboard')
                  }
                >
                  <IconButton
                    size="small"
                    onClick={handleCopyDescription}
                    sx={{ position: 'absolute', top: 4, right: 4 }}
                    color={copied ? 'success' : 'default'}
                  >
                    {copied ? <Check fontSize="small" /> : <ContentCopy fontSize="small" />}
                  </IconButton>
                </Tooltip>
              </Paper>
            )}
          </Box>
 
          <Divider />
 
          {/* Image generation */}
          <Box>
            <Typography variant="subtitle1" gutterBottom>
              {t('aiAssist.generateImage', '✨ Titelbild generieren')}
            </Typography>
            <Button
              variant="outlined"
              startIcon={
                imageMutation.isPending ? (
                  <CircularProgress size={16} color="inherit" />
                ) : (
                  <AutoAwesome />
                )
              }
              disabled={imageMutation.isPending}
              onClick={() => handleGenerateImage()}
              fullWidth
            >
              {imageMutation.isPending
                ? t('aiAssist.generating', 'Generieren...')
                : t('aiAssist.generateImage', '✨ Titelbild generieren')}
            </Button>
 
            {generatedImageUrl && (
              <Box sx={{ mt: 1 }}>
                <Box
                  component="img"
                  src={generatedImageUrl}
                  alt="Generated theme"
                  sx={{ width: '100%', borderRadius: 1, mb: 1 }}
                />
                <Box sx={{ display: 'flex', gap: 1 }}>
                  <Button
                    variant="contained"
                    size="small"
                    onClick={handleUseImage}
                    disabled={applyMutation.isPending}
                    startIcon={
                      applyMutation.isPending ? (
                        <CircularProgress size={14} color="inherit" />
                      ) : undefined
                    }
                    fullWidth
                  >
                    {t('aiAssist.useImage', 'Bild verwenden')}
                  </Button>
                  <Button
                    variant="outlined"
                    size="small"
                    onClick={() => handleGenerateImage(true)}
                    fullWidth
                  >
                    {t('aiAssist.regenerateImage', '↻ Neu generieren')}
                  </Button>
                  <Button
                    variant="text"
                    size="small"
                    onClick={() => {
                      setGeneratedImageUrl(null);
                      setGeneratedImageS3Key(null);
                    }}
                  >
                    {t('aiAssist.cancelImage', 'Abbrechen')}
                  </Button>
                </Box>
              </Box>
            )}
          </Box>
        </Box>
      </Drawer>
 
      <Snackbar
        open={!!errorMessage}
        autoHideDuration={6000}
        onClose={() => setErrorMessage(null)}
        anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
      >
        <Alert severity="error" onClose={() => setErrorMessage(null)}>
          {errorMessage ?? t('aiAssist.error', 'AI generation failed, please write manually')}
        </Alert>
      </Snackbar>
    </>
  );
}