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 } 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 } from "@/services/imageGeneration";

interface GeneratedImage {
  id: string;
  url: string;
  prompt: string;
  size: ImageSize;
  timestamp: Date;
}

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<GeneratedImage[]>([]);
  const { toast } = useToast();

  // Carrega histórico do localStorage ao montar o componente
  useEffect(() => {
    const savedImages = localStorage.getItem('imageHistory');
    if (savedImages) {
      try {
        const parsedImages = JSON.parse(savedImages);
        // Converte strings de data de volta para Date objects
        const imagesWithDates = parsedImages.map((img: any) => ({
          ...img,
          timestamp: new Date(img.timestamp),
        }));
        setImages(imagesWithDates);
      } catch (error) {
        console.error('Erro ao carregar histórico de imagens:', error);
      }
    }
  }, []);

  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) {
        // Log da URL da imagem para debug
        console.log('URL da imagem gerada:', response.image_url);

        const newImage: GeneratedImage = {
          id: response.image_generation_id,
          url: response.image_url,
          prompt: response.message,
          size: selectedSize,
          timestamp: new Date(),
        };

        const newHistory = [newImage, ...images].slice(0, 20); // Mantém apenas as últimas 20 imagens
        setImages(newHistory);
        localStorage.setItem('imageHistory', JSON.stringify(newHistory));

        toast({
          title: "Imagem gerada com sucesso",
          description: `Tamanho: ${IMAGE_SIZE_OPTIONS[selectedSize].label}`,
        });

        // Limpa o campo de descrição após sucesso
        setPrompt("");
      } 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 = (id: string) => {
    const newHistory = images.filter((img) => img.id !== id);
    setImages(newHistory);
    localStorage.setItem('imageHistory', JSON.stringify(newHistory));

    toast({
      title: "Imagem removida",
      description: "A imagem foi removida do histórico.",
    });
  };

  const handleDownload = async (image: GeneratedImage) => {
    try {
      await imageGenerationService.downloadImage(
        image.url,
        `${image.prompt.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 filteredImages = images.filter((img) =>
    img.prompt.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 && images.length > 0 && (
                  <div>
                    <h3 className="text-lg font-semibold mb-4">Última Geração</h3>
                    <ImageCard
                      image={images[0]}
                      onDelete={handleDelete}
                      onDownload={handleDownload}
                    />
                  </div>
                )}
              </TabsContent>

              {/* History Tab */}
              <TabsContent value="history" className="space-y-4">
                {/* Search */}
                <div className="relative">
                  <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>

                {/* 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>
                ) : (
                  <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: GeneratedImage;
  onDelete: (id: string) => void;
  onDownload: (image: GeneratedImage) => void;
}

const ImageCard = ({ image, onDelete, onDownload }: ImageCardProps) => {
  const [imageError, setImageError] = useState(false);
  const [imageLoading, setImageLoading] = useState(true);

  // Calcula tempo relativo
  const getRelativeTime = (timestamp: Date) => {
    const now = new Date();
    const diff = now.getTime() - new Date(timestamp).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.url);
    setImageError(true);
    setImageLoading(false);
  };

  const handleImageLoad = () => {
    console.log('Imagem carregada com sucesso:', 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.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.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.url}
            alt={image.prompt}
            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.prompt}</p>
            <div className="flex items-center justify-between text-xs text-white/70">
              <span>{IMAGE_SIZE_OPTIONS[image.size].label}</span>
              <span>{getRelativeTime(image.timestamp)}</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>
  );
};
