'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { Album } from './types';

interface AlbumsContextType {
  albums: Album[];
  loading: boolean;
  addAlbum: (album: Album) => Promise<void>;
  updateAlbum: (albumId: string, updatedAlbum: Album) => Promise<void>;
  deleteAlbum: (albumId: string) => Promise<void>;
  getAlbumById: (albumId: string) => Album | undefined;
  refreshAlbums: () => Promise<void>;
}

const AlbumsContext = createContext<AlbumsContextType | undefined>(undefined);

export function AlbumsProvider({ children }: { children: ReactNode }) {
  const [albums, setAlbums] = useState<Album[]>([]);
  const [loading, setLoading] = useState(true);

  // Fetch albums from API
  const fetchAlbums = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/albums');
      if (!response.ok) {
        throw new Error('Failed to fetch albums');
      }
      const data = await response.json();
      setAlbums(data);
    } catch (error) {
      console.error('Error fetching albums:', error);
    } finally {
      setLoading(false);
    }
  };

  // Load albums on mount
  useEffect(() => {
    fetchAlbums();
  }, []);

  const addAlbum = async (album: Album) => {
    try {
      const response = await fetch('/api/albums', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(album),
      });

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

      await fetchAlbums(); // Refresh the list
    } catch (error) {
      console.error('Error adding album:', error);
      throw error;
    }
  };

  const updateAlbum = async (albumId: string, updatedAlbum: Album) => {
    try {
      const response = await fetch('/api/albums', {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(updatedAlbum),
      });

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

      await fetchAlbums(); // Refresh the list
    } catch (error) {
      console.error('Error updating album:', error);
      throw error;
    }
  };

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

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

      await fetchAlbums(); // Refresh the list
    } catch (error) {
      console.error('Error deleting album:', error);
      throw error;
    }
  };

  const getAlbumById = (albumId: string) => {
    return albums.find((album) => album.id === albumId);
  };

  return (
    <AlbumsContext.Provider value={{ albums, loading, addAlbum, updateAlbum, deleteAlbum, getAlbumById, refreshAlbums: fetchAlbums }}>
      {children}
    </AlbumsContext.Provider>
  );
}

export function useAlbums() {
  const context = useContext(AlbumsContext);
  if (context === undefined) {
    throw new Error('useAlbums must be used within an AlbumsProvider');
  }
  return context;
}
