'use client';

import React, { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { useUserStore } from '../../store/useUserStore';

const WishlistContext = createContext();

// Improved key generation with type separation
function getWishlistKey(item) {
  if (!item) return '';
  const type = (item.type || '').toLowerCase(); // force lowercase
  const id = item.id || item.course_id || item.university_id;

  if (type === 'course' || item.course_id) return `course-${id}`;
  if (type === 'university' || item.university_id) return `university-${id}`;
  return `${type}-${id}`;
}


// Normalize item structure for consistency
function normalizeWishlistItem(item) {
  const type = (item.type || item.label || '').toLowerCase(); // normalize to lowercase
  const id = item.id || item.course_id || item.university_id;

  return {
    key: getWishlistKey({ type, id }),
    type,
    id,
    title: item.title || item.course_name || item.university_name || item.name,
    imageSrc: item.imageSrc || item.image || item.course?.image || item.university?.logo || '/university-placeholder.png',
    subtitle: item.subtitle || item.university_name || item.university_address || '',
    slug: item.slug || item.course?.slug || item.university?.slug || '',
    original: item
  };
}


export function WishlistProvider({ children }) {
  const { isLoggedIn } = useUserStore();
  const [wishlist, setWishlist] = useState([]);

  const fetchWishlist = useCallback(async () => {
    if (isLoggedIn) {
      try {
        // Sync localStorage to DB on login
        const local = localStorage.getItem('wishlist');
        if (local) {
          const localItems = JSON.parse(local);
          
          // Send local items to server
          for (const item of localItems) {
            try {
              await fetch('/api/frontend/wishlist', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                  course_id: item.type === 'course' ? item.id : undefined,
                  university_id: item.type === 'university' ? item.id : undefined,
                }),
              });
            } catch (error) {
              console.error('Error syncing item:', error);
            }
          }
          localStorage.removeItem('wishlist');
        }

        // Fetch updated wishlist from API
        const res = await fetch('/api/frontend/wishlist');
        const data = await res.json();
        
        if (Array.isArray(data.data)) {
          const normalizedWishlist = data.data.map(item => 
            normalizeWishlistItem({
              ...item,
              type: item.course_id ? 'Course' : 'University',
              id: item.course_id || item.university_id
            })
          );
          setWishlist(normalizedWishlist);
        }
      } catch (error) {
        console.error('Error fetching wishlist:', error);
        setWishlist([]);
      }
    } else {
      // For guest users
      const stored = localStorage.getItem('wishlist');
      if (stored) {
        const items = JSON.parse(stored);
        const normalizedItems = items.map(item => normalizeWishlistItem(item));
        setWishlist(normalizedItems);
      } else {
        setWishlist([]);
      }
    }
  }, [isLoggedIn]);

  useEffect(() => {
    const pathname = window.location.pathname;
    const wishlistRelatedPages = ['/wishlist', '/comparison', '/institutions', '/courses', '/'];
    
    if (wishlistRelatedPages.some(page => pathname.startsWith(page))) {
      fetchWishlist();
    }
  }, [isLoggedIn, fetchWishlist]);

  const addToWishlist = useCallback(async (item) => {

    const normalizedItem = normalizeWishlistItem(item);
     
    if (isLoggedIn) {
      try {
        const response = await fetch('/api/frontend/wishlist', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            course_id: normalizedItem.type === 'Course' ? normalizedItem.id : undefined,
            university_id: normalizedItem.type === 'University' ? normalizedItem.id : undefined,
          }),
        });
        
        if (response.ok) {
          setWishlist(prev => [...prev, normalizedItem]);
        } else {
          console.error('Failed to add to wishlist');
        }
      } catch (error) {
        console.error('Error adding to wishlist:', error);
      }
    } else {
      const updated = [...wishlist, normalizedItem];
      setWishlist(updated);
      localStorage.setItem('wishlist', JSON.stringify(updated));
    }
  }, [isLoggedIn, wishlist]);

  const removeFromWishlist = useCallback(async (item) => {
    const key = getWishlistKey(item);
    
    if (isLoggedIn) {
      try {
        const response = await fetch('/api/frontend/wishlist', {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            course_id: item.type === 'Course' ? item.id : undefined,
            university_id: item.type === 'University' ? item.id : undefined,
          }),
        });
        
        if (response.ok) {
          setWishlist(prev => prev.filter(w => w.key !== key));
        }
      } catch (error) {
        console.error('Error removing from wishlist:', error);
      }
    } else {
      const updated = wishlist.filter(w => w.key !== key);
      setWishlist(updated);
      localStorage.setItem('wishlist', JSON.stringify(updated));
    }
  }, [isLoggedIn, wishlist]);

  const toggleWishlist = useCallback((item) => {
    if (isWishlisted(item)) {
      removeFromWishlist(item);
    } else {
      addToWishlist(item);
    }
  }, [addToWishlist, removeFromWishlist]);

  const isWishlisted = useCallback((item) => {
    const key = getWishlistKey(item);
    return wishlist.some(w => w.key === key);
  }, [wishlist]);

  return (
    <WishlistContext.Provider value={{
      wishlist,
      addToWishlist,
      removeFromWishlist,
      toggleWishlist,
      isWishlisted,
      fetchWishlist,
    }}>
      {children}
    </WishlistContext.Provider>
  );
}

export function useWishlist() {
  const context = useContext(WishlistContext);
  if (context === undefined) {
    throw new Error('useWishlist must be used within a WishlistProvider');
  }
  return context;
}