import { useMemo } from 'react'
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 Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useQuery } from '@tanstack/react-query'
import { Link as RouterLink } from 'react-router-dom'
import { fetchMyOrders } from '@/entities/order/api/order-api'
import { ORDER_STATUSES } from '@/shared/constants/order'
import { formatPriceRub } from '@/shared/lib/format-price'
import { groupOrdersByStatus } from '@/shared/lib/group-orders-by-status'
import { orderStatusLabelRu } from '@/shared/lib/order-status-labels'

export function OrdersPage() {
  const ordersQuery = useQuery({
    queryKey: ['me', 'orders'],
    queryFn: fetchMyOrders,
  })

  const items = useMemo(() => ordersQuery.data?.items ?? [], [ordersQuery.data?.items])
  const groups = useMemo(() => groupOrdersByStatus(items, ORDER_STATUSES), [items])

  return (
    <Box>
      <Typography variant="h4" gutterBottom>
        Заказы
      </Typography>

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

      {ordersQuery.isSuccess && items.length === 0 && (
        <Alert severity="info">Заказов пока нет. Оформите заказ из корзины.</Alert>
      )}

      <Stack spacing={3}>
        {groups.map((group) => (
          <Box key={group.status}>
            <Typography variant="h6" sx={{ mb: 1 }}>
              {orderStatusLabelRu(group.status)} ({group.items.length})
            </Typography>
            <Stack spacing={2}>
              {group.items.map((o) => (
                <Box
                  key={o.id}
                  sx={{
                    border: 1,
                    borderColor: 'divider',
                    borderRadius: 2,
                    p: 2,
                    bgcolor: 'background.paper',
                  }}
                >
                  <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} sx={{ alignItems: { sm: 'center' } }}>
                    <Box sx={{ flexGrow: 1 }}>
                      <Typography sx={{ fontWeight: 700 }}>Заказ #{o.id.slice(-6)}</Typography>
                      <Typography color="text.secondary" variant="body2">
                        {new Date(o.createdAt).toLocaleString('ru-RU')} · {o.itemsCount} поз.
                      </Typography>
                    </Box>
                    <Typography sx={{ fontWeight: 700 }}>{formatPriceRub(o.totalCents)}</Typography>
                  </Stack>

                  <Stack direction="row" spacing={1} sx={{ mt: 1.5 }}>
                    <Button component={RouterLink} to={`/me/orders/${o.id}`} size="small" variant="outlined">
                      Открыть
                    </Button>
                  </Stack>
                </Box>
              ))}
            </Stack>
            <Divider sx={{ mt: 2 }} />
          </Box>
        ))}
      </Stack>
    </Box>
  )
}
