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

0% Statements 0/43
0% Branches 0/32
0% Functions 0/12
0% Lines 0/38

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * EventPhotosTab Component
 * Story 10.21: Event Photos Gallery — AC8
 *
 * Photo grid for organizers: upload, view, and delete event photos.
 * Uses 3-phase presigned PUT upload pattern.
 * Drag-to-reorder is explicitly OUT OF SCOPE (AC12).
 */
 
import React, { useRef, useState } from 'react';
import {
  Box,
  Button,
  Card,
  CardContent,
  CardMedia,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Typography,
  Alert,
  LinearProgress,
} from '@mui/material';
import Grid from '@mui/material/Grid';
import {
  Delete as DeleteIcon,
  PhotoLibrary as PhotoLibraryIcon,
  CloudUpload as CloudUploadIcon,
} from '@mui/icons-material';
import { useTranslation } from 'react-i18next';
import { useBreakpoints } from '@/hooks/useBreakpoints';
import { useDeleteEventPhoto, useEventPhotos, useUploadEventPhoto } from '@/hooks/useEventPhotos';
 
interface EventPhotosTabProps {
  eventCode: string;
}
 
export const EventPhotosTab: React.FC<EventPhotosTabProps> = ({ eventCode }) => {
  const { t } = useTranslation('events');
  const { isMobile } = useBreakpoints();
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [deletePhotoId, setDeletePhotoId] = useState<string | null>(null);
  const [uploadError, setUploadError] = useState<string | null>(null);
  const [uploadProgress, setUploadProgress] = useState<{ done: number; total: number } | null>(
    null
  );
 
  const { data: photos, isLoading } = useEventPhotos(eventCode);
  const uploadMutation = useUploadEventPhoto(eventCode);
  const deleteMutation = useDeleteEventPhoto(eventCode);
 
  const handleUploadClick = () => {
    fileInputRef.current?.click();
  };
 
  const handleFileChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = Array.from(e.target.files ?? []);
    if (files.length === 0) return;
 
    setUploadError(null);
    setUploadProgress({ done: 0, total: files.length });
 
    try {
      const results = await Promise.allSettled(
        files.map(async (file) => {
          try {
            await uploadMutation.mutateAsync({
              file,
              request: {
                filename: file.name,
                contentType: file.type as 'image/jpeg' | 'image/png' | 'image/webp',
                fileSize: file.size,
              },
            });
          } finally {
            setUploadProgress((prev) => prev && { ...prev, done: prev.done + 1 });
          }
        })
      );
 
      const failed = results.filter((r) => r.status === 'rejected').length;
      if (failed > 0) {
        setUploadError(
          t('photos.uploadErrorPartial', '{{failed}} of {{total}} uploads failed. Please retry.', {
            failed,
            total: files.length,
          })
        );
      }
    } finally {
      setUploadProgress(null);
    }
    // Reset file input so same files can be re-uploaded if needed
    if (fileInputRef.current) fileInputRef.current.value = '';
  };
 
  const handleDeleteConfirm = async () => {
    if (!deletePhotoId) return;
    try {
      await deleteMutation.mutateAsync(deletePhotoId);
    } finally {
      setDeletePhotoId(null);
    }
  };
 
  return (
    <Box>
      {/* Header */}
      <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <PhotoLibraryIcon color="primary" />
          <Typography variant="h6">{t('photos.title', 'Event Photos')}</Typography>
        </Box>
        <Button
          variant="contained"
          startIcon={<CloudUploadIcon />}
          onClick={handleUploadClick}
          disabled={!!uploadProgress}
        >
          {uploadProgress
            ? t('photos.uploadingProgress', 'Uploading {{done}}/{{total}}...', uploadProgress)
            : t('photos.uploadButton', 'Upload Photos')}
        </Button>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/jpeg,image/png,image/webp"
          multiple
          style={{ display: 'none' }}
          onChange={handleFileChange}
        />
      </Box>
 
      {/* Upload progress bar */}
      {uploadProgress && (
        <Box sx={{ mb: 2 }}>
          <LinearProgress
            variant="determinate"
            value={(uploadProgress.done / uploadProgress.total) * 100}
          />
        </Box>
      )}
 
      {/* Upload error */}
      {uploadError && (
        <Alert severity="error" onClose={() => setUploadError(null)} sx={{ mb: 2 }}>
          {uploadError}
        </Alert>
      )}
 
      {/* Loading */}
      {isLoading && (
        <Box sx={{ display: 'flex', justifyContent: 'center', py: 4 }}>
          <CircularProgress />
        </Box>
      )}
 
      {/* Empty state */}
      {!isLoading && (!photos || photos.length === 0) && (
        <Box sx={{ textAlign: 'center', py: 6, color: 'text.secondary' }}>
          <PhotoLibraryIcon sx={{ fontSize: 64, mb: 2, opacity: 0.3 }} />
          <Typography>{t('photos.emptyState', 'No photos yet. Upload the first one!')}</Typography>
        </Box>
      )}
 
      {/* Photo grid */}
      {!isLoading && photos && photos.length > 0 && (
        <Grid container spacing={2}>
          {photos.map((photo) => (
            <Grid size={{ xs: 12, sm: 6, md: 4, lg: 3 }} key={photo.id}>
              <Card sx={{ position: 'relative' }}>
                <CardMedia
                  component="img"
                  height="180"
                  image={photo.displayUrl}
                  alt={photo.filename || 'BATbern event photo'}
                  sx={{ objectFit: 'cover' }}
                />
                <CardContent sx={{ p: 1, '&:last-child': { pb: 1 } }}>
                  <Box sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <IconButton
                      size="small"
                      color="error"
                      onClick={() => setDeletePhotoId(photo.id ?? null)}
                      aria-label={t('photos.deleteConfirmTitle', 'Delete Photo')}
                    >
                      <DeleteIcon fontSize="small" />
                    </IconButton>
                  </Box>
                </CardContent>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}
 
      {/* Delete confirmation dialog */}
      <Dialog open={!!deletePhotoId} onClose={() => setDeletePhotoId(null)} fullScreen={isMobile}>
        <DialogTitle>{t('photos.deleteConfirmTitle', 'Delete Photo')}</DialogTitle>
        <DialogContent>
          {t(
            'photos.deleteConfirmMessage',
            'Are you sure you want to delete this photo? This cannot be undone.'
          )}
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeletePhotoId(null)}>
            {t('photos.deleteCancel', 'Cancel')}
          </Button>
          <Button
            color="error"
            variant="contained"
            onClick={handleDeleteConfirm}
            disabled={deleteMutation.isPending}
          >
            {t('photos.deleteConfirm', 'Delete')}
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};