import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import Button from '@mui/material/Button'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Stack from '@mui/material/Stack'
import Tooltip from '@mui/material/Tooltip'
import Typography from '@mui/material/Typography'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useUnit } from 'effector-react'
import { Minus, Plus, Trash2 } from 'lucide-react'
import { Link as RouterLink } from 'react-router-dom'
import { fetchMyCart, removeCartItem, setCartQty } from '@/entities/cart/api/cart-api'
import { formatPriceRub } from '@/shared/lib/format-price'
import { $user } from '@/shared/model/auth'

export function CartPage() {
  const user = useUnit($user)
  const qc = useQueryClient()

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

  const qtyMut = useMutation({
    mutationFn: (params: { id: string; qty: number }) => setCartQty(params.id, params.qty),
    onSuccess: () => void qc.invalidateQueries({ queryKey: ['me', 'cart'] }),
  })

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

  if (!user) {
    return (
      <Alert severity="info">
        Чтобы пользоваться корзиной, нужно войти. Перейдите на страницу{' '}
        <Typography component={RouterLink} to="/auth" sx={{ textDecoration: 'underline' }}>
          Вход
        </Typography>
        .
      </Alert>
    )
  }

  const items = cartQuery.data?.items ?? []
  const total = items.reduce((s, x) => s + x.product.priceCents * x.qty, 0)

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Корзина
      </Typography>

      {cartQuery.isError && <Alert severity="error">Не удалось загрузить корзину.</Alert>}

      {cartQuery.isSuccess && items.length === 0 && <Alert severity="info">Корзина пуста.</Alert>}

      {items.length > 0 && (
        <Stack spacing={2}>
          {items.map((x) =>
            (() => {
              const available = x.product.quantity
              const canInc = x.qty < available
              const over = x.qty > available
              return (
                <Box
                  key={x.id}
                  sx={{
                    border: 1,
                    borderColor: over ? 'error.light' : 'divider',
                    borderRadius: 2,
                    p: 2,
                    bgcolor: over ? 'error.50' : 'background.paper',
                  }}
                >
                  <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'center' } }}>
                    <Box sx={{ flexGrow: 1 }}>
                      <Typography sx={{ fontWeight: 700 }}>{x.product.title}</Typography>
                      <Typography color="text.secondary" variant="body2">
                        {formatPriceRub(x.product.priceCents)} · {x.qty} шт. · Доступно: {available}
                      </Typography>
                      {x.product.quantity === 0 && (
                        <Typography color="text.secondary" variant="caption">
                          Нет в наличии
                        </Typography>
                      )}
                      {over && (
                        <Typography color="error" variant="caption" sx={{ display: 'block', mt: 0.5 }}>
                          Недостаточно товара. Уменьшите количество до {available}.
                        </Typography>
                      )}
                    </Box>

                    <Stack
                      direction="row"
                      spacing={0.5}
                      sx={{
                        bgcolor: 'background.default',
                        borderRadius: 999,
                        px: 0.75,
                        height: 40,
                        alignItems: 'center',
                      }}
                    >
                      <IconButton
                        onClick={() => qtyMut.mutate({ id: x.id, qty: Math.max(0, x.qty - 1) })}
                        disabled={qtyMut.isPending}
                        aria-label="Уменьшить количество"
                        size="small"
                        sx={{ width: 32, height: 32 }}
                      >
                        <Minus />
                      </IconButton>
                      <Typography
                        sx={{
                          minWidth: 28,
                          textAlign: 'center',
                          lineHeight: 1,
                          fontWeight: 700,
                          fontVariantNumeric: 'tabular-nums',
                        }}
                      >
                        {x.qty}
                      </Typography>
                      <Tooltip title={!canInc ? `Доступно: ${available}` : 'Увеличить количество'}>
                        <span>
                          <IconButton
                            onClick={() => qtyMut.mutate({ id: x.id, qty: x.qty + 1 })}
                            disabled={qtyMut.isPending || !canInc}
                            aria-label="Увеличить количество"
                            size="small"
                            sx={{ width: 32, height: 32 }}
                          >
                            <Plus />
                          </IconButton>
                        </span>
                      </Tooltip>

                      <IconButton
                        onClick={() => removeMut.mutate(x.id)}
                        disabled={removeMut.isPending}
                        aria-label="Удалить"
                        size="small"
                        sx={{ width: 32, height: 32 }}
                      >
                        <Trash2 />
                      </IconButton>
                    </Stack>
                  </Stack>
                </Box>
              )
            })(),
          )}

          <Divider />

          <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2} sx={{ alignItems: { sm: 'center' } }}>
            <Typography variant="h6" sx={{ flexGrow: 1 }}>
              Итого: {formatPriceRub(total)}
            </Typography>
            <Button component={RouterLink} to="/checkout" variant="contained">
              Оформить заказ
            </Button>
          </Stack>
        </Stack>
      )}
    </Box>
  )
}
