import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useSession } from '@supabase/auth-helpers-react';
import { supabase } from '@/integrations/supabase/client';
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'; // Adjust import based on your UI library
import { Button } from '@/components/ui/button'; // Adjust import based on your UI library
import { Download } from 'lucide-react'; // Icon for download button, adjust as needed
import { Skeleton } from '@/components/ui/skeleton'; // Adjust import based on your UI library

interface GeneratedImage {
  id: string;
  created_at: string;
  user_id: string | null;
  prompt: string;
  image_url: string;
}

interface MyGeneratedLogoProps {
  userId?: string;
}

const MyGeneratedLogo: React.FC<MyGeneratedLogoProps> = ({ userId }) => {
  const { t } = useTranslation();
  const session = useSession();
  const [images, setImages] = useState<GeneratedImage[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isDownloading, setIsDownloading] = useState(false);

  useEffect(() => {
    const fetchImages = async () => {
      setLoading(true);
      setError(null);

      try {
        const { data, error } = await supabase
          .from('generated_logos')
          .select('*')
          .eq('user_id', userId ?? '')
          .order('created_at', { ascending: false });

        if (error) {
          console.error('Error fetching images:', error);
          setError(error.message);
        } else {
          setImages(data || []);
        }
      } catch (err: any) {
        console.error('Unexpected error fetching images:', err);
        setError(err.message);
      } finally {
        setLoading(false);
      }
    };

    if (userId) {
      fetchImages();
    }
  }, [userId]);

  const handleDownloadImage = async (imageUrl: string) => {
    setIsDownloading(true);
    try {
      const response = await fetch(imageUrl);
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `generated-image-${Date.now()}.png`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    } catch (err) {
      console.error('Error downloading image:', err);
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <Card className="bg-zinc-900 border-zinc-800 text-slate-100 shadow-lg mt-8">
      <CardHeader className="items-center text-center">
        <CardTitle className="text-3xl text-purple-400">{t('My Generated Logos')}</CardTitle>
        <p className="text-slate-400 max-w-2xl mx-auto">
          {t('View and download your previously generated logos.')}
        </p>
      </CardHeader>
      <CardContent className="space-y-6">
        {error ? (
          <div className="text-red-400 text-center">{error}</div>
        ) : loading ? (
          <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-4">
            {[...Array(6)].map((_, i) => (
              <Skeleton key={i} className="w-full h-48 bg-slate-700 rounded-md" />
            ))}
          </div>
        ) : images.length === 0 ? (
          <div className="text-slate-400 text-center">{t('No images created yet.')}</div>
        ) : (
          <div className="columns-1 sm:columns-3 md:columns-3 lg:columns-3 xl:columns-3 gap-1 space-y-1">
            {images.map((image) => (
              <div key={image.id} className="relative group overflow-hidden rounded-md border border-slate-600">
                <img
                  src={image.image_url}
                  alt={`Generated image for prompt: ${image.created_at}`}
                  className="w-full h-full max-w-[200px] max-h-[200px] object-cover transition-transform duration-300 group-hover:scale-105"
                  onContextMenu={(e) => e.preventDefault()}
                />
                <div className="absolute inset-0 bg-black bg-opacity-50 flex flex-col items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-300">
                  <Button
                    onClick={() => handleDownloadImage(image.image_url)}
                    size="icon"
                    className="bg-white text-gray-800 hover:bg-gray-200"
                    disabled={isDownloading}
                  >
                    <Download className="h-5 w-5" />
                  </Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </CardContent>
    </Card>
  );
};

export default MyGeneratedLogo;
