'use client';

import { useState, useEffect } from 'react';
import { Card } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Check, X, RefreshCw } from 'lucide-react';
import { ImageUpload } from './image-upload';

interface ImageOption {
  id: string;
  name: string;
  path: string;
}

interface ImageSelectorProps {
  type: 'header' | 'footer';
  selectedImage: string | null;
  onImageSelect: (imagePath: string | null) => void;
}

export function ImageSelector({ type, selectedImage, onImageSelect }: ImageSelectorProps) {
  const [images, setImages] = useState<ImageOption[]>([]);
  const [loading, setLoading] = useState(true);

  const fetchImages = async () => {
    try {
      const response = await fetch(`/api/${type}s`);
      const data = await response.json();
      setImages(data);
    } catch (error) {
      console.error(`Error fetching ${type} images:`, error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchImages();
  }, [type]);

  const handleUploadSuccess = () => {
    fetchImages();
  };

  const handleRefresh = () => {
    setLoading(true);
    fetchImages();
  };

  if (loading) {
    return (
      <div className="space-y-4">
        <h3 className="text-lg font-semibold text-gray-900 capitalize">
          Select {type}
        </h3>
        <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
          {[...Array(4)].map((_, i) => (
            <Card key={i} className="aspect-video bg-gray-100 animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-semibold text-gray-900 capitalize">
          Select {type}
        </h3>
        <div className="flex items-center gap-2">
          {selectedImage && (
            <Button
              variant="ghost"
              size="sm"
              onClick={() => onImageSelect(null)}
              className="text-gray-500 hover:text-gray-700"
            >
              <X className="h-4 w-4 mr-2" />
              Clear
            </Button>
          )}
          <Button
            variant="ghost"
            size="sm"
            onClick={handleRefresh}
            className="text-gray-500 hover:text-gray-700"
          >
            <RefreshCw className="h-4 w-4" />
          </Button>
        </div>
      </div>

      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        {/* Upload new image card */}
        <ImageUpload type={type} onUploadSuccess={handleUploadSuccess} />
        
        {/* Existing images */}
        {images.map((image) => (
          <Card
            key={image.id}
            className={`relative cursor-pointer transition-all duration-200 hover:shadow-md ${
              selectedImage === image.path
                ? 'ring-2 ring-blue-500 shadow-md'
                : 'hover:shadow-sm'
            }`}
            onClick={() => onImageSelect(image.path)}
          >
            <div className="aspect-video relative overflow-hidden rounded-lg">
              <img
                src={image.path}
                alt={image.name}
                className="w-full h-full object-cover"
                onError={(e) => {
                  // Fallback for missing images
                  const target = e.target as HTMLImageElement;
                  target.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='200' height='120' viewBox='0 0 200 120'%3E%3Crect width='200' height='120' fill='%23f3f4f6'/%3E%3Ctext x='100' y='60' font-family='Arial' font-size='12' fill='%23666' text-anchor='middle' dy='0.3em'%3E${image.name}%3C/text%3E%3C/svg%3E`;
                }}
              />
              {selectedImage === image.path && (
                <div className="absolute inset-0 bg-blue-500 bg-opacity-20 flex items-center justify-center">
                  <div className="bg-blue-500 rounded-full p-1">
                    <Check className="h-4 w-4 text-white" />
                  </div>
                </div>
              )}
            </div>
            <div className="p-2">
              <p className="text-xs text-gray-600 truncate">{image.name}</p>
            </div>
          </Card>
        ))}
      </div>

      {images.length === 0 && (
        <Card className="p-6 text-center">
          <p className="text-gray-500">
            No {type} images found. Upload your first {type} image above.
          </p>
        </Card>
      )}
    </div>
  );
}