import React, { createContext, useContext, useState, useCallback } from 'react';
import { createMedia, validateMediaData, formatMediaData, pb } from '../services/pocketbaseService'; // Import from pocketbaseService, including validation/formatting
import { useCache } from '../hooks/useCache';
import { useErrorBoundary } from '../hooks/useErrorBoundary';

const MediaContext = createContext(null);

export const MediaProvider = ({ children }) => {
  const [selectedMedia, setSelectedMedia] = useState(null);
  const { error, handleError, clearError } = useErrorBoundary();

  // Кэширование медиа-контента
  const { data: mediaList, refetch: refetchMedia } = useCache(
    'media_list',
    async () => {
      try {
        const records = await pb.collection('media').getFullList({
          sort: '-created',
          expand: 'genres,seasons'
        });
        return records;
      } catch (err) {
        handleError(err);
        return [];
      }
    },
    {
      expiry: 5 * 60 * 1000, // 5 минут
    }
  );

  // Получение медиа по ID
  const getMediaById = useCallback(async (id) => {
    try {
      clearError();
      const media = await pb.collection('media').getOne(id, {
        expand: 'genres,seasons,ratings'
      });
      return media;
    } catch (err) {
      handleError(err);
      return null;
    }
  }, [clearError, handleError]);

  // Поиск медиа
  const searchMedia = useCallback(async (query) => {
    try {
      clearError();
      const records = await pb.collection('media').getFullList({
        filter: `title ~ "${query}" || description ~ "${query}"`,
        expand: 'genres'
      });
      return records;
    } catch (err) {
      handleError(err);
      return [];
    }
  }, [clearError, handleError]);

  // Фильтрация медиа
  const filterMedia = useCallback(async (filters) => {
    try {
      clearError();
      let filterString = '';
      
      if (filters.genre) {
        filterString += `genres ?~ "${filters.genre}"`;
      }
      
      if (filters.year) {
        filterString += filterString ? ' && ' : '';
        filterString += `year = ${filters.year}`;
      }
      
      if (filters.type) {
        filterString += filterString ? ' && ' : '';
        filterString += `type = "${filters.type}"`;
      }

      const records = await pb.collection('media').getFullList({
        filter: filterString,
        expand: 'genres'
      });
      
      return records;
    } catch (err) {
      handleError(err);
      return [];
    }
  }, [clearError, handleError]);

  const value = {
    mediaList,
    selectedMedia,
    error,
    setSelectedMedia,
    getMediaById,
    searchMedia,
    filterMedia,
    refetchMedia
  };

  return (
    <MediaContext.Provider value={value}>
      {children}
    </MediaContext.Provider>
  );
};

export const useMedia = () => {
  const context = useContext(MediaContext);
  if (!context) {
    throw new Error('useMedia должен использоваться внутри MediaProvider');
  }
  return context;
};
