'use client';

import { useState } from 'react';
import { Sparkles, Loader2, ImageIcon, Video } from 'lucide-react';
import { ModelSelector } from '@/components/model-selector';
import { ImageConfig } from '@/components/image-config';
import { VideoConfig } from '@/components/video-config';
import { ImageCard } from '@/components/image-card';
import { VideoCard } from '@/components/video-card';
import { ReferenceImages } from '@/components/reference-images';

type ContentType = 'image' | 'video';

interface GeneratedImage {
  id: string;
  imageData: string;
  prompt: string;
  model: string;
  aspectRatio: string;
  timestamp: number;
}

interface GeneratedVideo {
  id: string;
  videoData: string;
  prompt: string;
  model: string;
  aspectRatio: string;
  duration: number;
  timestamp: number;
}

interface ReferenceImage {
  id: string;
  data: string;
  mimeType: string;
  preview: string;
  name: string;
}

export default function Home() {
  // Estado del tipo de contenido
  const [contentType, setContentType] = useState<ContentType>('image');

  // Estado del modelo y configuración
  const [selectedModel, setSelectedModel] = useState('gemini-2.5-flash-image');
  const [aspectRatio, setAspectRatio] = useState('1:1');
  const [numberOfImages, setNumberOfImages] = useState(1);
  const [videoDuration, setVideoDuration] = useState(5);
  const [negativePrompt, setNegativePrompt] = useState('');
  const [safetyLevel, setSafetyLevel] = useState<'block_none' | 'block_some' | 'block_most'>('block_some');
  const [referenceImages, setReferenceImages] = useState<ReferenceImage[]>([]);

  // Estado del chat
  const [prompt, setPrompt] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [generatedImages, setGeneratedImages] = useState<GeneratedImage[]>([]);
  const [generatedVideos, setGeneratedVideos] = useState<GeneratedVideo[]>([]);
  const [error, setError] = useState<string | null>(null);

  // Cambiar tipo de contenido y actualizar modelo por defecto
  const handleContentTypeChange = (type: ContentType) => {
    setContentType(type);
    if (type === 'image') {
      setSelectedModel('gemini-2.5-flash-image');
      setAspectRatio('1:1');
    } else {
      setSelectedModel('veo-3.0-generate-001');
      setAspectRatio('16:9');
    }
  };

  const handleGenerateImage = async () => {
    if (!prompt.trim()) return;

    setIsGenerating(true);
    setError(null);

    try {
      const response = await fetch('/api/generate-image', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: selectedModel,
          prompt: prompt.trim(),
          aspectRatio,
          numberOfImages,
          negativePrompt: negativePrompt.trim() || undefined,
          safetyFilterLevel: safetyLevel,
          temperature: 1,
          referenceImages: referenceImages.length > 0
            ? referenceImages.map(img => ({
                data: img.data,
                mimeType: img.mimeType,
              }))
            : undefined,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.details || data.error || 'Error generando imagen');
      }

      // Agregar imágenes generadas al historial
      const newImages: GeneratedImage[] = data.images.map((imageData: string, index: number) => ({
        id: `${Date.now()}-${index}`,
        imageData,
        prompt: prompt.trim(),
        model: selectedModel,
        aspectRatio,
        timestamp: Date.now(),
      }));

      setGeneratedImages([...newImages, ...generatedImages]);
      setPrompt(''); // Limpiar prompt después de generar

    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleGenerateVideo = async () => {
    if (!prompt.trim()) return;

    setIsGenerating(true);
    setError(null);

    try {
      const response = await fetch('/api/generate-video', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          model: selectedModel,
          prompt: prompt.trim(),
          aspectRatio,
          duration: videoDuration,
          negativePrompt: negativePrompt.trim() || undefined,
          safetyFilterLevel: safetyLevel,
          temperature: 1,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.details || data.error || 'Error generando video');
      }

      // Agregar video generado al historial
      const newVideo: GeneratedVideo = {
        id: `${Date.now()}`,
        videoData: data.videoData,
        prompt: prompt.trim(),
        model: selectedModel,
        aspectRatio,
        duration: videoDuration,
        timestamp: Date.now(),
      };

      setGeneratedVideos([newVideo, ...generatedVideos]);
      setPrompt(''); // Limpiar prompt después de generar

    } catch (err: any) {
      setError(err.message);
    } finally {
      setIsGenerating(false);
    }
  };

  const handleGenerate = () => {
    if (contentType === 'image') {
      handleGenerateImage();
    } else {
      handleGenerateVideo();
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleGenerate();
    }
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-secondary">
      <div className="container mx-auto px-4 py-8">
        {/* Header */}
        <div className="mb-8 text-center">
          <div className="flex items-center justify-center gap-3 mb-3">
            <Sparkles className="w-8 h-8 text-primary" />
            <h1 className="text-4xl font-bold bg-gradient-to-r from-primary to-purple-600 bg-clip-text text-transparent">
              AI Playground
            </h1>
          </div>
          <p className="text-muted-foreground">
            Genera imágenes y videos con Google Generative AI
          </p>
        </div>

        {/* Selector de tipo de contenido */}
        <div className="mb-6 flex justify-center">
          <div className="inline-flex bg-card border border-border rounded-lg p-1">
            <button
              onClick={() => handleContentTypeChange('image')}
              className={`
                flex items-center gap-2 px-6 py-2 rounded-md font-medium transition-all
                ${contentType === 'image'
                  ? 'bg-primary text-primary-foreground shadow-sm'
                  : 'text-muted-foreground hover:text-foreground'
                }
              `}
            >
              <ImageIcon className="w-4 h-4" />
              Imágenes
            </button>
            <button
              onClick={() => handleContentTypeChange('video')}
              className={`
                flex items-center gap-2 px-6 py-2 rounded-md font-medium transition-all
                ${contentType === 'video'
                  ? 'bg-primary text-primary-foreground shadow-sm'
                  : 'text-muted-foreground hover:text-foreground'
                }
              `}
            >
              <Video className="w-4 h-4" />
              Videos
            </button>
          </div>
        </div>

        <div className="grid lg:grid-cols-[350px,1fr] gap-6">
          {/* Panel de configuración */}
          <div className="space-y-6">
            <div className="bg-card border border-border rounded-xl p-6 shadow-lg space-y-6">
              <ModelSelector
                selectedModel={selectedModel}
                onModelChange={setSelectedModel}
                contentType={contentType}
              />

              <div className="border-t border-border pt-6">
                {contentType === 'image' ? (
                  <ImageConfig
                    model={selectedModel}
                    aspectRatio={aspectRatio}
                    onAspectRatioChange={setAspectRatio}
                    numberOfImages={numberOfImages}
                    onNumberOfImagesChange={setNumberOfImages}
                    negativePrompt={negativePrompt}
                    onNegativePromptChange={setNegativePrompt}
                    safetyLevel={safetyLevel}
                    onSafetyLevelChange={setSafetyLevel}
                  />
                ) : (
                  <VideoConfig
                    model={selectedModel}
                    aspectRatio={aspectRatio}
                    onAspectRatioChange={setAspectRatio}
                    duration={videoDuration}
                    onDurationChange={setVideoDuration}
                    negativePrompt={negativePrompt}
                    onNegativePromptChange={setNegativePrompt}
                    safetyLevel={safetyLevel}
                    onSafetyLevelChange={setSafetyLevel}
                  />
                )}
              </div>

              {contentType === 'image' && (
                <div className="border-t border-border pt-6">
                  <ReferenceImages
                    images={referenceImages}
                    onImagesChange={setReferenceImages}
                    maxImages={3}
                  />
                </div>
              )}
            </div>

            {/* Stats */}
            <div className="bg-card border border-border rounded-xl p-4">
              <div className="flex items-center gap-2 text-sm text-muted-foreground mb-2">
                {contentType === 'image' ? (
                  <ImageIcon className="w-4 h-4" />
                ) : (
                  <Video className="w-4 h-4" />
                )}
                <span className="font-medium">Estadísticas</span>
              </div>
              <div className="space-y-1 text-sm">
                {contentType === 'image' ? (
                  <p>Imágenes generadas: <strong>{generatedImages.length}</strong></p>
                ) : (
                  <p>Videos generados: <strong>{generatedVideos.length}</strong></p>
                )}
                <p>Modelo actual: <strong>{selectedModel}</strong></p>
              </div>
            </div>
          </div>

          {/* Área principal */}
          <div className="space-y-6">
            {/* Input de prompt */}
            <div className="bg-card border border-border rounded-xl p-6 shadow-lg">
              <label className="text-sm font-medium text-foreground mb-2 block">
                Describe tu {contentType === 'image' ? 'imagen' : 'video'}
              </label>
              <div className="space-y-3">
                <textarea
                  value={prompt}
                  onChange={(e) => setPrompt(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder={
                    contentType === 'image'
                      ? 'Ejemplo: Un atardecer en una playa tropical con palmeras...'
                      : 'Ejemplo: Un timelapse de una ciudad con tráfico fluido al atardecer...'
                  }
                  className="w-full px-4 py-3 bg-secondary border border-border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-primary resize-none"
                  rows={4}
                  disabled={isGenerating}
                />
                <button
                  onClick={handleGenerate}
                  disabled={isGenerating || !prompt.trim()}
                  className="w-full px-6 py-3 bg-primary text-primary-foreground rounded-lg font-medium hover:opacity-90 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
                >
                  {isGenerating ? (
                    <>
                      <Loader2 className="w-5 h-5 animate-spin" />
                      Generando...
                    </>
                  ) : (
                    <>
                      <Sparkles className="w-5 h-5" />
                      Generar {contentType === 'image' ? 'Imagen' : 'Video'}
                    </>
                  )}
                </button>
              </div>

              {/* Error message */}
              {error && (
                <div className="mt-4 p-4 bg-red-500/10 border border-red-500/20 rounded-lg">
                  <p className="text-sm text-red-500">
                    <strong>Error:</strong> {error}
                  </p>
                </div>
              )}
            </div>

            {/* Galería */}
            <div>
              <h2 className="text-lg font-semibold mb-4 flex items-center gap-2">
                {contentType === 'image' ? (
                  <>
                    <ImageIcon className="w-5 h-5" />
                    Galería {generatedImages.length > 0 && `(${generatedImages.length})`}
                  </>
                ) : (
                  <>
                    <Video className="w-5 h-5" />
                    Videos {generatedVideos.length > 0 && `(${generatedVideos.length})`}
                  </>
                )}
              </h2>

              {contentType === 'image' && generatedImages.length === 0 && !isGenerating && (
                <div className="bg-card border border-dashed border-border rounded-xl p-12 text-center">
                  <ImageIcon className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
                  <p className="text-muted-foreground">
                    Aún no has generado ninguna imagen.
                  </p>
                  <p className="text-sm text-muted-foreground mt-2">
                    Escribe un prompt y haz clic en &quot;Generar Imagen&quot; para comenzar.
                  </p>
                </div>
              )}

              {contentType === 'video' && generatedVideos.length === 0 && !isGenerating && (
                <div className="bg-card border border-dashed border-border rounded-xl p-12 text-center">
                  <Video className="w-16 h-16 text-muted-foreground mx-auto mb-4 opacity-50" />
                  <p className="text-muted-foreground">
                    Aún no has generado ningún video.
                  </p>
                  <p className="text-sm text-muted-foreground mt-2">
                    Escribe un prompt y haz clic en &quot;Generar Video&quot; para comenzar.
                  </p>
                </div>
              )}

              <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                {contentType === 'image' && generatedImages.map((image) => (
                  <ImageCard
                    key={image.id}
                    imageData={image.imageData}
                    prompt={image.prompt}
                    model={image.model}
                  />
                ))}

                {contentType === 'video' && generatedVideos.map((video) => (
                  <VideoCard
                    key={video.id}
                    videoData={video.videoData}
                    prompt={video.prompt}
                    model={video.model}
                  />
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
