import {useState, useEffect} from 'react';
import type {Artwork} from '@/types';

interface ArtworkResponse {
  id: string;
  title: string;
  filename: string;
  mimetype: string;
  size: number;
  created_at: string;
  updated_at: string;
}

export const useArtwork = () => {
  const [artworks, setArtworks] = useState<Artwork[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchArtworks = async () => {
    setLoading(true);
    setError(null);
    try {
      const response = await fetch('/api/artworks');
      if (!response.ok) {
        throw new Error('Failed to fetch artworks');
      }
      const data: ArtworkResponse[] = await response.json();
      
      // Transform backend data to frontend format
      const transformedArtworks: Artwork[] = data.map(artwork => ({
        id: artwork.id,
        title: artwork.title,
        imageUrl: `/api/artworks/${artwork.id}/image`
      }));
      
      setArtworks(transformedArtworks);
    } catch (err) {
      console.error('Error fetching artworks:', err);
      setError(err instanceof Error ? err.message : 'Failed to load artworks');
      setArtworks([]);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchArtworks();
  }, []);

  const addArtwork = async (artwork: Omit<Artwork, 'id'>, file: File) => {
    try {
      const formData = new FormData();
      formData.append('title', artwork.title);
      formData.append('image', file);

      const response = await fetch('/api/artworks', {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.message || 'Failed to upload artwork');
      }

      const newArtworkData: ArtworkResponse = await response.json();
      
      const newArtwork: Artwork = {
        id: newArtworkData.id,
        title: newArtworkData.title,
        imageUrl: `/api/artworks/${newArtworkData.id}/image`
      };
      
      setArtworks(prev => [...prev, newArtwork]);
      return newArtwork;
    } catch (err) {
      console.error('Error adding artwork:', err);
      throw err;
    }
  };

  const deleteArtwork = async (id: string) => {
    try {
      const response = await fetch(`/api/artworks/${id}`, {
        method: 'DELETE'
      });

      if (!response.ok) {
        throw new Error('Failed to delete artwork');
      }

      setArtworks(prev => prev.filter(art => art.id !== id));
    } catch (err) {
      console.error('Error deleting artwork:', err);
      throw err;
    }
  };

  return {
    artworks,
    loading,
    error,
    addArtwork,
    deleteArtwork,
    refetch: fetchArtworks
  };
};
