// UploadQueue.tsx
import React, { useCallback } from 'react';
import { Box, Button, Card, CardContent, CardMedia, IconButton, LinearProgress, Typography } from '@mui/material';
import { Delete, Replay } from '@mui/icons-material';
import { FileQueueItem, WeddingPhoto } from './types';
import { uploadFileXHR, toAbsoluteUrl } from './apis';

type Props = {
    queue: FileQueueItem[];
    setQueue: React.Dispatch<React.SetStateAction<FileQueueItem[]>>;
    newPhotoTitle?: string;
    onUploaded?: (photo: WeddingPhoto) => void;
};

const UploadQueue: React.FC<Props> = ({ queue, setQueue, newPhotoTitle, onUploaded }) => {
    const uploadSingle = useCallback(
        async (item: FileQueueItem) => {
            setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'uploading', progress: 0, error: undefined } : q)));
            const res = await uploadFileXHR(
                item.file,
                (pct) => setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, progress: pct } : q))),
                newPhotoTitle
            );
            if (res.success) {
                const it = res.data;
                const uploadedPhoto: WeddingPhoto = {
                    id: it.id ?? it._id,
                    url: toAbsoluteUrl(it.path ?? it.url),
                    title: it.title ?? it.filename ?? item.file.name,
                    date: it.created_at ?? it.createdAt,
                    filename: it.filename,
                    path: it.path,
                    created_at: it.created_at ?? it.createdAt,
                };
                setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'done', progress: 100, uploadedPhoto } : q)));
                onUploaded?.(uploadedPhoto);
                return true;
            } else {
                setQueue((prev) => prev.map((q) => (q.id === item.id ? { ...q, status: 'error', error: res.error } : q)));
                return false;
            }
        },
        [newPhotoTitle, setQueue, onUploaded]
    );

    const uploadAll = useCallback(async () => {
        for (const item of queue.filter((q) => q.status === 'pending' || q.status === 'error')) {
             
            await uploadSingle(item);
        }
    }, [queue, uploadSingle]);

    const retryOne = (id: string) => {
        const item = queue.find((q) => q.id === id);
        if (item) uploadSingle(item);
    };

    const removeOne = (id: string) => {
        const item = queue.find((q) => q.id === id);
        if (item) URL.revokeObjectURL(item.previewUrl);
        setQueue((prev) => prev.filter((q) => q.id !== id));
    };

    return (
        <Box>
            <Box sx={{ display: 'flex', gap: 1, mb: 1 }}>
                <Button onClick={uploadAll} disabled={!queue.some((q) => q.status === 'pending' || q.status === 'error')} variant="contained">
                    Upload All
                </Button>
            </Box>

            <Box sx={{ display: 'flex', gap: 2, flexWrap: 'wrap' }}>
                {queue.map((q) => (
                    <Card key={q.id} sx={{ width: 180 }}>
                        <CardMedia component="img" height={110} image={q.previewUrl} />
                        <CardContent>
                            <Typography variant="body2" noWrap>
                                {q.file.name}
                            </Typography>

                            {q.status === 'uploading' && <Typography variant="caption">Uploading — {q.progress}%</Typography>}
                            {q.status === 'pending' && <Typography variant="caption">Pending</Typography>}
                            {q.status === 'done' && <Typography variant="caption" color="success.main">Uploaded</Typography>}
                            {q.status === 'error' && <Typography variant="caption" color="error.main">{q.error ?? 'Upload failed'}</Typography>}
                            <LinearProgress variant="determinate" value={q.progress} sx={{ mt: 1 }} />
                            <Box sx={{ display: 'flex', gap: 1, mt: 1 }}>
                                {q.status === 'error' && <IconButton size="small" onClick={() => retryOne(q.id)}><Replay fontSize="small" /></IconButton>}
                                <IconButton size="small" onClick={() => removeOne(q.id)}><Delete fontSize="small" /></IconButton>
                            </Box>
                        </CardContent>
                    </Card>
                ))}
            </Box>
        </Box>
    );
};

export default UploadQueue;
