'use client';

import React, { createContext, useContext, useState, useCallback, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import {
  ShopwareProduct,
  getWishlist,
  addToWishlist as apiAddToWishlist,
  removeFromWishlist as apiRemoveFromWishlist,
  mergeWishlist as apiMergeWishlist,
} from './shopware-api';
import { useAuth } from './auth-context';

const PENDING_KEY = 'sw-wishlist-pending';

interface WishlistContextType {
  wishlistIds: Set<string>;
  wishlistProducts: ShopwareProduct[];
  isLoading: boolean;
  itemCount: number;
  isWishlistEnabled: boolean;
  isInWishlist: (productId: string) => boolean;
  toggleWishlist: (productId: string) => Promise<void>;
  removeFromWishlist: (productId: string) => Promise<void>;
  refreshWishlist: () => Promise<void>;
}

const WishlistContext = createContext<WishlistContextType | undefined>(undefined);

export function WishlistProvider({ children }: { children: React.ReactNode }) {
  const { isLoggedIn, customer } = useAuth();
  const isGuest = customer?.guest === true;
  const router = useRouter();
  const [wishlistIds, setWishlistIds] = useState<Set<string>>(new Set());
  const [wishlistProducts, setWishlistProducts] = useState<ShopwareProduct[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [isWishlistEnabled] = useState(true);

  const itemCount = wishlistIds.size;

  const refreshWishlist = useCallback(async () => {
    if (!isLoggedIn || isGuest) return;
    setIsLoading(true);
    try {
      const data = await getWishlist();
      const products = data?.products?.elements ?? [];
      setWishlistProducts(products);
      setWishlistIds(new Set(products.map((p: ShopwareProduct) => p.id)));
    } catch {
      // Wishlist may not be enabled in Shopware admin — silently fail
    } finally {
      setIsLoading(false);
    }
  }, [isLoggedIn]);

  // When user logs in, check for a pending product and merge/add it
  useEffect(() => {
    if (!isLoggedIn || isGuest) {
      setWishlistIds(new Set());
      setWishlistProducts([]);
      return;
    }

    async function loadAndMergePending() {
      setIsLoading(true);
      try {
        const pending = localStorage.getItem(PENDING_KEY);

        if (pending) {
          // Try merge endpoint first (handles deduplication server-side)
          try {
            await apiMergeWishlist([pending]);
          } catch {
            // Merge not supported — add directly
            try {
              await apiAddToWishlist(pending);
            } catch {
              // May already be in wishlist
            }
          }
          localStorage.removeItem(PENDING_KEY);
        }

        await refreshWishlist();
      } finally {
        setIsLoading(false);
      }
    }

    loadAndMergePending();
  }, [isLoggedIn, refreshWishlist]);

  const isInWishlist = useCallback(
    (productId: string) => wishlistIds.has(productId),
    [wishlistIds]
  );

  /**
   * Toggle wishlist state for a product.
   * - If not logged in: save productId to localStorage and redirect to login.
   * - If logged in: add or remove via API.
   */
  const toggleWishlist = useCallback(
    async (productId: string) => {
      if (!isLoggedIn) {
        localStorage.setItem(PENDING_KEY, productId);
        router.push(`/account/login?redirect=/wishlist`);
        return;
      }

      const alreadyIn = wishlistIds.has(productId);

      // Optimistic update
      setWishlistIds((prev) => {
        const next = new Set(prev);
        if (alreadyIn) {
          next.delete(productId);
        } else {
          next.add(productId);
        }
        return next;
      });
      if (alreadyIn) {
        setWishlistProducts((prev) => prev.filter((p) => p.id !== productId));
      }

      try {
        if (alreadyIn) {
          await apiRemoveFromWishlist(productId);
        } else {
          await apiAddToWishlist(productId);
          // Refresh to get full product data
          await refreshWishlist();
        }
      } catch {
        // Revert optimistic update on error
        await refreshWishlist();
      }
    },
    [isLoggedIn, wishlistIds, router, refreshWishlist]
  );

  const removeFromWishlist = useCallback(
    async (productId: string) => {
      setWishlistIds((prev) => {
        const next = new Set(prev);
        next.delete(productId);
        return next;
      });
      setWishlistProducts((prev) => prev.filter((p) => p.id !== productId));
      try {
        await apiRemoveFromWishlist(productId);
      } catch {
        await refreshWishlist();
      }
    },
    [refreshWishlist]
  );

  return (
    <WishlistContext.Provider
      value={{
        wishlistIds,
        wishlistProducts,
        isLoading,
        itemCount,
        isWishlistEnabled,
        isInWishlist,
        toggleWishlist,
        removeFromWishlist,
        refreshWishlist,
      }}
    >
      {children}
    </WishlistContext.Provider>
  );
}

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