'use client';

import clsx from 'clsx';
import { useSession } from 'next-auth/react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  useAddFavoriteMutation,
  useGetFavoritesQuery,
  useRemoveFavoriteMutation
} from '@akinon/next/data/client/wishlist';
import { Icon } from '@theme/components';
import { pushAddToWishlist } from '@theme/utils/gtm';
import { useToast, useLocalization } from '@akinon/next/hooks';

interface FavButtonProps {
  label?: string;
  size?: number;
  className?: string;
  style?: React.CSSProperties;
}

const FAV_TOAST_OPTIONS = { position: 'bottom-right' as const }

const useFavButton = (productPk: number) => {
  const { status } = useSession();
  const { t } = useLocalization();
  const { success, error: showError } = useToast();

  const { data: favorites } = useGetFavoritesQuery(
    {
      limit: 1000
    },
    { skip: status !== 'authenticated' }
  );

  const favoriteItem = useMemo(
    () =>
      favorites?.results?.find(
        (item) => Number(item.product.pk) === Number(productPk)
      ),
    [favorites, productPk]
  );

  const isActive = Boolean(favoriteItem);
  const [isPushed, setIsPushed] = useState<boolean>(false);

  const [addFavorite] = useAddFavoriteMutation();
  const [removeFavorite] = useRemoveFavoriteMutation();

  const handleClick = useCallback(async () => {
    try {
      if (favoriteItem) {
        await removeFavorite(favoriteItem.pk).unwrap();
        success(t('product.removed_from_favorites'), FAV_TOAST_OPTIONS);
      } else {
        await addFavorite(productPk).unwrap();
        setIsPushed(true);
        success(t('product.added_to_favorites'), FAV_TOAST_OPTIONS);
      }
    } catch (err) {
      showError(t('product.favorites_error'), FAV_TOAST_OPTIONS);
    }
  }, [favoriteItem, productPk, addFavorite, removeFavorite, success, showError, t]);

  useEffect(() => {
    if (favoriteItem && isPushed) {
      pushAddToWishlist({
        base_code: favoriteItem?.product?.base_code,
        name: favoriteItem?.product?.name,
        price: favoriteItem?.product?.price,
        currency_type: favoriteItem?.product?.currency_type
      });
      setIsPushed(false);
    }
  }, [favoriteItem, isPushed]);

  const FavButton = useMemo(() => {
    const View = (props: FavButtonProps) => (
      <button
        className={clsx(
          'flex items-center hover:text-secondary-hover hover:cursor-pointer',
          props.className
        )}
        style={props.style}
        onClick={handleClick}
        data-testid="favourites-icon"
      >
        <Icon
          name={isActive ? 'fav-on' : 'fav-off'}
          size={props.size ?? 16}
          className={clsx('hover:fill-secondary-hover')}
        />
        {props.label && <span className="ml-2">{props.label}</span>}
      </button>
    );

    return View;
  }, [isActive, handleClick]);

  return {
    FavButton
  };
};

export default useFavButton;
