import { useState, useCallback } from 'react';
import api from '@/lib/api';

const LOCAL_STORAGE_KEY = 'recently_viewed_books';
const MAX_ITEMS = 8;

export interface RecentlyViewedBook {
  id: string;
  title: string;
  slug: string;
  price: number;
  discountPrice?: number | null;
  coverImage?: string | null;
  authorName?: string | null;
  categoryName?: string | null;
  ratingAverage: number;
  stock: number;
}

export function useRecentlyViewed() {
  const [recentlyViewed, setRecentlyViewed] = useState<RecentlyViewedBook[]>([]);
  const [loading, setLoading] = useState(false);

  const getIds = useCallback((): string[] => {
    if (typeof window === 'undefined') return [];
    try {
      const stored = localStorage.getItem(LOCAL_STORAGE_KEY);
      return stored ? JSON.parse(stored) : [];
    } catch {
      return [];
    }
  }, []);

  const addId = useCallback((id: string) => {
    if (typeof window === 'undefined' || !id) return;
    try {
      const ids = getIds();
      const filtered = ids.filter((item) => item !== id);
      filtered.unshift(id);
      const updated = filtered.slice(0, MAX_ITEMS);
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(updated));
    } catch (e) {
      console.error('Failed to save to recently viewed', e);
    }
  }, [getIds]);

  const fetchDetails = useCallback(async () => {
    const ids = getIds();
    if (ids.length === 0) {
      setRecentlyViewed([]);
      return;
    }
    setLoading(true);
    try {
      const response = await api.get(`/books`, {
        params: { ids: ids.join(','), limit: MAX_ITEMS },
      });
      const booksList: RecentlyViewedBook[] = response.data?.data?.books ?? [];
      
      // Sort retrieved books to match the chronological order of IDs in localStorage
      const sortedBooks = ids
        .map((id) => booksList.find((b) => b.id === id))
        .filter(Boolean) as RecentlyViewedBook[];
      
      setRecentlyViewed(sortedBooks);
    } catch (error) {
      console.error('Failed to fetch recently viewed books details', error);
    } finally {
      setLoading(false);
    }
  }, [getIds]);

  return {
    recentlyViewed,
    loading,
    addId,
    fetchDetails,
    getIds,
  };
}
