519 lines
20 KiB
TypeScript
519 lines
20 KiB
TypeScript
import { useState, useEffect } from "react";
|
|
import { ChatHeader } from "@/components/ChatHeader";
|
|
import { Button } from "@/components/ui/button";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
import { Download, Trash2, Sparkles, Clock, Search, ChevronLeft, ChevronRight } from "lucide-react";
|
|
import { ScrollArea } from "@/components/ui/scroll-area";
|
|
import { Input } from "@/components/ui/input";
|
|
import {
|
|
Select,
|
|
SelectContent,
|
|
SelectItem,
|
|
SelectTrigger,
|
|
SelectValue,
|
|
} from "@/components/ui/select";
|
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
|
import { useToast } from "@/hooks/use-toast";
|
|
import {
|
|
imageGenerationService,
|
|
IMAGE_SIZE_OPTIONS,
|
|
ImageSize,
|
|
ImageRecord
|
|
} from "@/services/imageGeneration";
|
|
import {
|
|
Pagination,
|
|
PaginationContent,
|
|
PaginationItem,
|
|
PaginationLink,
|
|
} from "@/components/ui/pagination";
|
|
|
|
export const ImageView = () => {
|
|
const [prompt, setPrompt] = useState("");
|
|
const [isGenerating, setIsGenerating] = useState(false);
|
|
const [selectedSize, setSelectedSize] = useState<ImageSize>("1024x1024");
|
|
const [searchQuery, setSearchQuery] = useState("");
|
|
const [images, setImages] = useState<ImageRecord[]>([]);
|
|
const [lastGeneratedImage, setLastGeneratedImage] = useState<ImageRecord | null>(null);
|
|
const [isLoadingImages, setIsLoadingImages] = useState(false);
|
|
const [currentPage, setCurrentPage] = useState(1);
|
|
const [perPage, setPerPage] = useState(10);
|
|
const { toast } = useToast();
|
|
|
|
// Carrega imagens do banco de dados ao montar o componente
|
|
const loadImages = async (page: number = currentPage, limit: number = perPage) => {
|
|
setIsLoadingImages(true);
|
|
try {
|
|
const fetchedImages = await imageGenerationService.getImages(undefined, page, limit);
|
|
|
|
// Garante que sempre seja um array
|
|
if (Array.isArray(fetchedImages)) {
|
|
setImages(fetchedImages);
|
|
} else {
|
|
console.warn('Resposta da API não é um array:', fetchedImages);
|
|
setImages([]);
|
|
}
|
|
} catch (error: any) {
|
|
console.error('Erro ao carregar imagens:', error);
|
|
toast({
|
|
title: "Erro ao carregar histórico",
|
|
description: error.message || "Não foi possível carregar o histórico de imagens.",
|
|
variant: "destructive",
|
|
});
|
|
setImages([]);
|
|
} finally {
|
|
setIsLoadingImages(false);
|
|
}
|
|
};
|
|
|
|
// Carrega imagens ao montar e quando a paginação mudar
|
|
useEffect(() => {
|
|
loadImages();
|
|
}, [currentPage, perPage]);
|
|
|
|
const handleGenerate = async () => {
|
|
// Valida a descrição antes de enviar
|
|
const validation = imageGenerationService.validateDescription(prompt);
|
|
if (!validation.valid) {
|
|
toast({
|
|
title: "Descrição inválida",
|
|
description: validation.error,
|
|
variant: "destructive",
|
|
});
|
|
return;
|
|
}
|
|
|
|
setIsGenerating(true);
|
|
|
|
try {
|
|
// Chama o serviço de geração de imagem
|
|
const response = await imageGenerationService.generateImage({
|
|
description: prompt,
|
|
size: selectedSize,
|
|
});
|
|
|
|
// Verifica se a geração foi bem-sucedida
|
|
if (response.success) {
|
|
toast({
|
|
title: "Imagem gerada com sucesso",
|
|
description: `Tamanho: ${IMAGE_SIZE_OPTIONS[selectedSize].label}`,
|
|
});
|
|
|
|
// Cria objeto da imagem recém-gerada para exibição imediata
|
|
const newGeneratedImage: ImageRecord = {
|
|
id: response.image_generation_id,
|
|
user_email: '', // Será preenchido pelo backend
|
|
estabelecimento_id: 0, // Será preenchido pelo backend
|
|
description: response.message, // Descrição original
|
|
model: 'dall-e-3', // Modelo padrão
|
|
image_url: response.image_url,
|
|
size: selectedSize,
|
|
cost_usd: '0',
|
|
total_tokens: 0,
|
|
input_tokens: 0,
|
|
output_tokens: 0,
|
|
created_at: new Date().toISOString(),
|
|
};
|
|
|
|
// Salva a última imagem gerada para exibição
|
|
setLastGeneratedImage(newGeneratedImage);
|
|
|
|
// Limpa o campo de descrição após sucesso
|
|
setPrompt("");
|
|
|
|
// Recarrega a lista de imagens (sem aguardar para não bloquear a UI)
|
|
loadImages(1, perPage);
|
|
setCurrentPage(1);
|
|
} else {
|
|
throw new Error('Erro ao gerar imagem');
|
|
}
|
|
} catch (error: any) {
|
|
console.error('Erro na geração de imagem:', error);
|
|
|
|
toast({
|
|
title: "Erro na geração",
|
|
description: error.message || "Não foi possível gerar a imagem. Tente novamente.",
|
|
variant: "destructive",
|
|
});
|
|
} finally {
|
|
setIsGenerating(false);
|
|
}
|
|
};
|
|
|
|
const handleDelete = async (id: string) => {
|
|
try {
|
|
const result = await imageGenerationService.deleteImage(id);
|
|
|
|
if (result.success) {
|
|
toast({
|
|
title: "Imagem removida",
|
|
description: "A imagem foi removida com sucesso.",
|
|
});
|
|
|
|
// Se a imagem deletada for a última gerada, limpa o preview
|
|
if (lastGeneratedImage && lastGeneratedImage.id === id) {
|
|
setLastGeneratedImage(null);
|
|
}
|
|
|
|
// Recarrega a lista de imagens
|
|
await loadImages();
|
|
} else {
|
|
throw new Error(result.message || 'Erro ao deletar imagem');
|
|
}
|
|
} catch (error: any) {
|
|
console.error('Erro ao deletar imagem:', error);
|
|
toast({
|
|
title: "Erro ao remover",
|
|
description: error.message || "Não foi possível remover a imagem.",
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
};
|
|
|
|
const handleDownload = async (image: ImageRecord) => {
|
|
try {
|
|
await imageGenerationService.downloadImage(
|
|
image.image_url,
|
|
`${image.description.substring(0, 30)}_${image.size}.png`
|
|
);
|
|
|
|
toast({
|
|
title: "Download iniciado",
|
|
description: "A imagem está sendo baixada.",
|
|
});
|
|
} catch (error) {
|
|
toast({
|
|
title: "Erro no download",
|
|
description: "Não foi possível baixar a imagem.",
|
|
variant: "destructive",
|
|
});
|
|
}
|
|
};
|
|
|
|
const handlePageChange = (page: number) => {
|
|
setCurrentPage(page);
|
|
};
|
|
|
|
const handlePerPageChange = (value: string) => {
|
|
setPerPage(parseInt(value));
|
|
setCurrentPage(1); // Reset para primeira página ao mudar itens por página
|
|
};
|
|
|
|
const filteredImages = Array.isArray(images)
|
|
? images.filter((img) =>
|
|
img.description.toLowerCase().includes(searchQuery.toLowerCase())
|
|
)
|
|
: [];
|
|
|
|
return (
|
|
<div className="flex flex-col h-full pb-16 md:pb-0">
|
|
<ChatHeader />
|
|
|
|
<div className="flex-1 flex overflow-hidden">
|
|
{/* Main Content */}
|
|
<ScrollArea className="flex-1">
|
|
<div className="max-w-5xl mx-auto p-3 md:p-6">
|
|
<Tabs defaultValue="generate" className="space-y-4 md:space-y-6">
|
|
<TabsList className="grid w-full grid-cols-2 glass-effect">
|
|
<TabsTrigger value="generate" className="text-xs md:text-sm">Gerar Imagem</TabsTrigger>
|
|
<TabsTrigger value="history" className="text-xs md:text-sm">
|
|
<Clock className="w-3 h-3 md:w-4 md:h-4 mr-1 md:mr-2" />
|
|
<span className="hidden md:inline">Histórico</span>
|
|
<span className="md:hidden">Hist.</span>
|
|
</TabsTrigger>
|
|
</TabsList>
|
|
|
|
{/* Generate Tab */}
|
|
<TabsContent value="generate" className="space-y-4 md:space-y-6">
|
|
<div className="glass-effect rounded-xl p-4 md:p-6 space-y-3 md:space-y-4">
|
|
<div className="space-y-2">
|
|
<label className="text-sm font-medium text-foreground">
|
|
Descreva a imagem
|
|
</label>
|
|
<Textarea
|
|
value={prompt}
|
|
onChange={(e) => setPrompt(e.target.value)}
|
|
placeholder="Descreva a imagem que deseja criar..."
|
|
className="min-h-[100px] resize-none"
|
|
/>
|
|
</div>
|
|
|
|
<div className="flex flex-col md:flex-row gap-3 md:gap-4 md:items-end">
|
|
<div className="flex-1 space-y-2">
|
|
<label className="text-sm font-medium text-foreground">
|
|
Tamanho
|
|
</label>
|
|
<Select value={selectedSize} onValueChange={(value) => setSelectedSize(value as ImageSize)}>
|
|
<SelectTrigger>
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent className="glass-effect bg-popover border-border z-50">
|
|
<SelectItem value="1024x1024">1024x1024 (Quadrado)</SelectItem>
|
|
<SelectItem value="1024x1792">1024x1792 (Retrato)</SelectItem>
|
|
<SelectItem value="1792x1024">1792x1024 (Paisagem)</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
|
|
<Button
|
|
onClick={handleGenerate}
|
|
disabled={!prompt.trim() || isGenerating}
|
|
className="gap-2 cyber-glow"
|
|
size="lg"
|
|
>
|
|
<Sparkles className="w-4 h-4" />
|
|
{isGenerating ? "Gerando..." : "Gerar Imagem"}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Loading State */}
|
|
{isGenerating && (
|
|
<div className="glass-effect rounded-xl p-12 flex flex-col items-center justify-center space-y-4 animate-fade-in">
|
|
<div className="relative">
|
|
<div className="w-24 h-24 rounded-full border-4 border-primary/20 border-t-primary animate-spin" />
|
|
<div className="absolute inset-0 flex items-center justify-center">
|
|
<Sparkles className="w-8 h-8 text-primary animate-pulse-glow" />
|
|
</div>
|
|
</div>
|
|
<p className="text-lg font-medium gradient-text">
|
|
Gerando sua imagem...
|
|
</p>
|
|
<p className="text-sm text-muted-foreground">
|
|
Isso pode levar alguns segundos
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
{/* Recent Images Preview */}
|
|
{!isGenerating && lastGeneratedImage && (
|
|
<div>
|
|
<h3 className="text-lg font-semibold mb-4">Última Geração</h3>
|
|
<ImageCard
|
|
image={lastGeneratedImage}
|
|
onDelete={handleDelete}
|
|
onDownload={handleDownload}
|
|
/>
|
|
</div>
|
|
)}
|
|
</TabsContent>
|
|
|
|
{/* History Tab */}
|
|
<TabsContent value="history" className="space-y-4">
|
|
{/* Search and Filters */}
|
|
<div className="flex flex-col md:flex-row gap-3">
|
|
<div className="relative flex-1">
|
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
|
|
<Input
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
placeholder="Buscar por descrição..."
|
|
className="pl-9"
|
|
/>
|
|
</div>
|
|
<Select value={perPage.toString()} onValueChange={handlePerPageChange}>
|
|
<SelectTrigger className="w-full md:w-[180px]">
|
|
<SelectValue />
|
|
</SelectTrigger>
|
|
<SelectContent className="glass-effect bg-popover border-border z-50">
|
|
<SelectItem value="5">5 por página</SelectItem>
|
|
<SelectItem value="10">10 por página</SelectItem>
|
|
<SelectItem value="20">20 por página</SelectItem>
|
|
<SelectItem value="50">50 por página</SelectItem>
|
|
</SelectContent>
|
|
</Select>
|
|
</div>
|
|
|
|
{/* Loading State */}
|
|
{isLoadingImages ? (
|
|
<div className="glass-effect rounded-xl p-12 flex flex-col items-center justify-center space-y-4">
|
|
<div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
|
|
<p className="text-muted-foreground">Carregando imagens...</p>
|
|
</div>
|
|
) : (
|
|
<>
|
|
{/* Images Grid */}
|
|
{filteredImages.length > 0 ? (
|
|
<>
|
|
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
|
{filteredImages.map((image) => (
|
|
<ImageCard
|
|
key={image.id}
|
|
image={image}
|
|
onDelete={handleDelete}
|
|
onDownload={handleDownload}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
{/* Pagination */}
|
|
{!searchQuery && images.length >= perPage && (
|
|
<div className="flex items-center justify-center gap-4 mt-6">
|
|
<Pagination>
|
|
<PaginationContent>
|
|
<PaginationItem>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => handlePageChange(currentPage - 1)}
|
|
disabled={currentPage === 1}
|
|
className="gap-1"
|
|
>
|
|
<ChevronLeft className="h-4 w-4" />
|
|
<span className="hidden md:inline">Anterior</span>
|
|
</Button>
|
|
</PaginationItem>
|
|
|
|
<PaginationItem>
|
|
<span className="text-sm text-muted-foreground px-4">
|
|
Página {currentPage}
|
|
</span>
|
|
</PaginationItem>
|
|
|
|
<PaginationItem>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
onClick={() => handlePageChange(currentPage + 1)}
|
|
disabled={images.length < perPage}
|
|
className="gap-1"
|
|
>
|
|
<span className="hidden md:inline">Próxima</span>
|
|
<ChevronRight className="h-4 w-4" />
|
|
</Button>
|
|
</PaginationItem>
|
|
</PaginationContent>
|
|
</Pagination>
|
|
</div>
|
|
)}
|
|
</>
|
|
) : (
|
|
<div className="glass-effect rounded-xl p-12 text-center">
|
|
<Clock className="w-12 h-12 mx-auto mb-4 text-muted-foreground" />
|
|
<p className="text-muted-foreground">
|
|
{searchQuery ? "Nenhuma imagem encontrada" : "Nenhuma imagem gerada ainda"}
|
|
</p>
|
|
</div>
|
|
)}
|
|
</>
|
|
)}
|
|
</TabsContent>
|
|
</Tabs>
|
|
</div>
|
|
</ScrollArea>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
interface ImageCardProps {
|
|
image: ImageRecord;
|
|
onDelete: (id: string) => void;
|
|
onDownload: (image: ImageRecord) => void;
|
|
}
|
|
|
|
const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
|
|
const [imageError, setImageError] = useState(false);
|
|
const [imageLoading, setImageLoading] = useState(true);
|
|
|
|
// Calcula tempo relativo
|
|
const getRelativeTime = (timestamp: string) => {
|
|
const now = new Date();
|
|
const date = new Date(timestamp);
|
|
const diff = now.getTime() - date.getTime();
|
|
const minutes = Math.floor(diff / 60000);
|
|
const hours = Math.floor(diff / 3600000);
|
|
const days = Math.floor(diff / 86400000);
|
|
|
|
if (minutes < 1) return 'Agora';
|
|
if (minutes < 60) return `Há ${minutes} ${minutes === 1 ? 'minuto' : 'minutos'}`;
|
|
if (hours < 24) return `Há ${hours} ${hours === 1 ? 'hora' : 'horas'}`;
|
|
return `Há ${days} ${days === 1 ? 'dia' : 'dias'}`;
|
|
};
|
|
|
|
const handleImageError = () => {
|
|
console.warn('Erro CORS ao carregar imagem:', image.image_url);
|
|
setImageError(true);
|
|
setImageLoading(false);
|
|
};
|
|
|
|
const handleImageLoad = () => {
|
|
console.log('Imagem carregada com sucesso:', image.image_url);
|
|
setImageLoading(false);
|
|
setImageError(false);
|
|
};
|
|
|
|
return (
|
|
<div className="group glass-effect rounded-xl overflow-hidden animate-fade-in">
|
|
<div className="relative aspect-square">
|
|
{imageLoading && !imageError && (
|
|
<div className="absolute inset-0 flex items-center justify-center bg-muted">
|
|
<div className="w-8 h-8 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
|
|
</div>
|
|
)}
|
|
{imageError ? (
|
|
<div className="absolute inset-0 flex flex-col items-center justify-center bg-muted text-muted-foreground p-4">
|
|
<Sparkles className="w-12 h-12 mb-2 opacity-50" />
|
|
<p className="text-sm text-center font-medium mb-1">Erro ao carregar</p>
|
|
<p className="text-xs text-center mb-2">A imagem foi gerada, mas não pode ser exibida aqui</p>
|
|
<div className="flex flex-col gap-2 w-full">
|
|
<a
|
|
href={image.image_url}
|
|
target="_blank"
|
|
rel="noopener noreferrer"
|
|
className="text-xs text-center bg-primary text-primary-foreground px-3 py-2 rounded-md hover:bg-primary/90 transition-colors"
|
|
>
|
|
Abrir imagem em nova aba
|
|
</a>
|
|
<button
|
|
onClick={() => navigator.clipboard.writeText(image.image_url)}
|
|
className="text-xs text-center bg-secondary text-secondary-foreground px-3 py-1 rounded-md hover:bg-secondary/80 transition-colors"
|
|
>
|
|
Copiar URL
|
|
</button>
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<img
|
|
src={image.image_url}
|
|
alt={image.description}
|
|
className="w-full h-full object-cover"
|
|
onError={handleImageError}
|
|
onLoad={handleImageLoad}
|
|
loading="lazy"
|
|
referrerPolicy="no-referrer"
|
|
/>
|
|
)}
|
|
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/0 to-black/0 opacity-0 group-hover:opacity-100 transition-opacity">
|
|
<div className="absolute bottom-0 left-0 right-0 p-4 space-y-2">
|
|
<p className="text-sm text-white line-clamp-2">{image.description}</p>
|
|
<div className="flex items-center justify-between text-xs text-white/70">
|
|
<span>{IMAGE_SIZE_OPTIONS[image.size as ImageSize]?.label || image.size}</span>
|
|
<span>{getRelativeTime(image.created_at)}</span>
|
|
</div>
|
|
<div className="flex gap-2">
|
|
<Button
|
|
size="sm"
|
|
variant="secondary"
|
|
className="flex-1 gap-1"
|
|
onClick={() => onDownload(image)}
|
|
>
|
|
<Download className="w-3 h-3" />
|
|
Baixar
|
|
</Button>
|
|
<Button
|
|
size="sm"
|
|
variant="destructive"
|
|
className="gap-1"
|
|
onClick={() => onDelete(image.id)}
|
|
>
|
|
<Trash2 className="w-3 h-3" />
|
|
Excluir
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
);
|
|
};
|