import IconButton from '@mui/material/IconButton'
import Tooltip from '@mui/material/Tooltip'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useUnit } from 'effector-react'
import { ShoppingCart } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { addToCart, fetchMyCart, removeCartItem } from '@/entities/cart/api/cart-api'
import { $user } from '@/shared/model/auth'

export function ToggleCartIcon(props: {
  productId: string
  size?: 'small' | 'medium'
  disabledReason?: string | null
}) {
  const { productId, size = 'small', disabledReason = null } = props
  const user = useUnit($user)
  const qc = useQueryClient()
  const navigate = useNavigate()

  const cartQuery = useQuery({
    queryKey: ['me', 'cart'],
    queryFn: fetchMyCart,
    enabled: Boolean(user),
  })

  const existing = cartQuery.data?.items.find((x) => x.product.id === productId) ?? null
  const inCart = Boolean(existing)

  const addMut = useMutation({
    mutationFn: () => addToCart({ productId, qty: 1 }),
    onSuccess: () => void qc.invalidateQueries({ queryKey: ['me', 'cart'] }),
  })

  const removeMut = useMutation({
    mutationFn: () => removeCartItem(existing!.id),
    onSuccess: () => void qc.invalidateQueries({ queryKey: ['me', 'cart'] }),
  })

  const disabled = Boolean(disabledReason)
  const busy = addMut.isPending || removeMut.isPending

  const onClick = (e: React.MouseEvent) => {
    e.preventDefault()
    e.stopPropagation()
    if (disabledReason) return
    if (!user) {
      navigate('/auth')
      return
    }
    if (inCart) removeMut.mutate()
    else addMut.mutate()
  }

  const tooltip = disabledReason
    ? disabledReason
    : !user
      ? 'Авторизуйтесь для совершения покупок'
      : inCart
        ? 'Убрать из корзины'
        : 'В корзину'

  return (
    <Tooltip title={tooltip}>
      <span>
        <IconButton size={size} onClick={onClick} disabled={disabled || busy} aria-label={tooltip} type="button">
          {user ? inCart ? <ShoppingCart fill="currentColor" /> : <ShoppingCart /> : <ShoppingCart />}
        </IconButton>
      </span>
    </Tooltip>
  )
}
