import { useMemo, useState } from 'react'
import Alert from '@mui/material/Alert'
import Box from '@mui/material/Box'
import Chip from '@mui/material/Chip'
import Dialog from '@mui/material/Dialog'
import Divider from '@mui/material/Divider'
import IconButton from '@mui/material/IconButton'
import Paper from '@mui/material/Paper'
import Rating from '@mui/material/Rating'
import Skeleton from '@mui/material/Skeleton'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import { useQuery } from '@tanstack/react-query'
import { useUnit } from 'effector-react'
import { Star, X } from 'lucide-react'
import { useParams } from 'react-router-dom'
import { Navigation } from 'swiper/modules'
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/css'
import 'swiper/css/navigation'
import { fetchPublicProduct } from '@/entities/product/api/product-api'
import { fetchPublicProductReviews } from '@/entities/product/api/reviews-api'
import { ToggleCartIcon } from '@/features/cart/toggle-cart-icon'
import { formatPriceRub } from '@/shared/lib/format-price'
import { reviewsCountRu } from '@/shared/lib/reviews-count-ru'
import { $user } from '@/shared/model/auth'
import { OptimizedImage } from '@/shared/ui/OptimizedImage'
import { RichTextMessageContent } from '@/shared/ui/RichTextMessageContent'

export function ProductPage() {
  const user = useUnit($user)
  const isAdmin = Boolean(user?.isAdmin)
  const { id } = useParams()
  const [viewerOpen, setViewerOpen] = useState(false)
  const [viewerIndex, setViewerIndex] = useState(0)

  const productQuery = useQuery({
    queryKey: ['products', 'public', 'byId', id],
    queryFn: () => fetchPublicProduct(id!),
    enabled: Boolean(id),
  })

  const reviewsQuery = useQuery({
    queryKey: ['products', 'public', id, 'reviews', { page: 1, pageSize: 30 }],
    queryFn: () => fetchPublicProductReviews(id!, { page: 1, pageSize: 30 }),
    enabled: Boolean(id),
  })

  const imageUrls = useMemo(() => {
    const p = productQuery.data
    if (!p) return []
    const fromImages = (p.images ?? [])
      .slice()
      .sort((a, b) => a.sort - b.sort)
      .map((x) => x.url)
    const urls = fromImages.length ? fromImages : p.imageUrl ? [p.imageUrl] : []
    return urls
  }, [productQuery.data])

  if (!id) return <Alert severity="error">Некорректная ссылка на товар.</Alert>

  if (productQuery.isLoading) {
    return (
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        <Skeleton variant="rectangular" height={420} />
        <Skeleton variant="text" width="60%" />
        <Skeleton variant="text" width="40%" />
        <Skeleton variant="text" />
      </Box>
    )
  }

  if (productQuery.isError) return <Alert severity="error">Не удалось загрузить товар.</Alert>

  const p = productQuery.data
  if (!p) return <Alert severity="error">Товар не найден.</Alert>

  return (
    <Box>
      <Box sx={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
        {imageUrls.length > 0 ? (
          <Box
            sx={{
              borderRadius: 2,
              overflow: 'hidden',
              border: 1,
              borderColor: 'divider',
              bgcolor: 'background.paper',
            }}
          >
            <Swiper modules={[Navigation]} navigation style={{ width: '100%', height: 420 }}>
              {imageUrls.map((url, idx) => (
                <SwiperSlide key={url}>
                  <Box
                    onClick={() => {
                      setViewerIndex(idx)
                      setViewerOpen(true)
                    }}
                    sx={{
                      width: '100%',
                      height: 420,
                      cursor: 'zoom-in',
                      userSelect: 'none',
                    }}
                  >
                    <OptimizedImage
                      src={url}
                      alt={p.title}
                      sizes="(max-width: 600px) 320px, (max-width: 1024px) 640px, 1024px"
                      sx={{
                        width: '100%',
                        height: '100%',
                        objectFit: 'cover',
                      }}
                    />
                  </Box>
                </SwiperSlide>
              ))}
            </Swiper>
          </Box>
        ) : (
          <Box
            sx={{
              height: 420,
              borderRadius: 2,
              overflow: 'hidden',
              border: 1,
              borderColor: 'divider',
              bgcolor: 'grey.100',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
            }}
          >
            <Typography color="text.secondary">Нет фото</Typography>
          </Box>
        )}

        <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
          {p.category?.name && <Chip label={p.category.name} />}
          {p.quantity > 0 && <Chip label="В наличии" color="success" />}
          {p.quantity === 0 && <Chip label="Нет в наличии" color="default" />}
        </Box>

        {(p.materials?.length ?? 0) > 0 && (
          <Box>
            <Typography variant="subtitle2" color="text.secondary" sx={{ mb: 1 }}>
              Материалы
            </Typography>
            <Box sx={{ display: 'flex', gap: 1, flexWrap: 'wrap' }}>
              {(p.materials ?? []).map((m) => (
                <Chip key={m} label={m} variant="outlined" />
              ))}
            </Box>
          </Box>
        )}

        <Typography variant="h4" component="h1">
          {p.title}
        </Typography>
        <Typography variant="h5" color="primary">
          {formatPriceRub(p.priceCents)}
        </Typography>

        {!isAdmin && p.quantity > 0 ? <ToggleCartIcon productId={p.id} size="medium" /> : null}

        {p.description || p.shortDescription ? (
          <Typography sx={{ whiteSpace: 'pre-wrap' }}>{p.description}</Typography>
        ) : (
          <Typography color="text.secondary">Описание появится позже.</Typography>
        )}

        <Divider sx={{ my: 2 }} />

        <Typography variant="h6" sx={{ mb: 1 }}>
          Отзывы
        </Typography>
        {p.reviewsSummary && p.reviewsSummary.approvedReviewCount > 0 && (
          <Stack direction="row" spacing={1} sx={{ alignItems: 'center', mb: 2 }}>
            <Rating
              value={p.reviewsSummary.avgRating ?? 0}
              readOnly
              precision={0.25}
              icon={<Star fontSize="inherit" />}
              emptyIcon={<Star fontSize="inherit" />}
            />
            <Typography variant="body2" color="text.secondary">
              {reviewsCountRu(p.reviewsSummary.approvedReviewCount)}
            </Typography>
          </Stack>
        )}

        {reviewsQuery.isLoading && <Typography color="text.secondary">Загрузка отзывов…</Typography>}
        {reviewsQuery.isError && <Alert severity="warning">Не удалось загрузить отзывы.</Alert>}
        {reviewsQuery.data && reviewsQuery.data.total === 0 && (
          <Typography color="text.secondary">Пока нет опубликованных отзывов на этот товар.</Typography>
        )}
        {reviewsQuery.data && reviewsQuery.data.items.length > 0 && (
          <Stack spacing={1.25}>
            {reviewsQuery.data.items.map((rv) => {
              const body = typeof rv.text === 'string' && rv.text.trim() ? rv.text.trim() : null
              return (
                <Paper key={rv.id} variant="outlined" sx={{ p: 1.5, borderRadius: 2 }}>
                  <Stack spacing={0.75}>
                    <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1} sx={{ justifyContent: 'space-between' }}>
                      <Typography sx={{ fontWeight: 700 }}>{rv.authorDisplay}</Typography>
                      <Typography variant="caption" color="text.secondary">
                        {new Date(rv.createdAt).toLocaleString('ru-RU')}
                      </Typography>
                    </Stack>
                    <Rating
                      value={rv.rating}
                      readOnly
                      size="small"
                      icon={<Star fontSize="inherit" />}
                      emptyIcon={<Star fontSize="inherit" />}
                    />
                    {body ? (
                      <Box sx={{ color: 'text.secondary' }}>
                        <RichTextMessageContent value={body} tone="review" />
                      </Box>
                    ) : (
                      <Typography variant="caption" color="text.secondary">
                        Без текстового комментария.
                      </Typography>
                    )}
                    {rv.imageUrl && (
                      <Box
                        sx={{
                          width: 140,
                          height: 140,
                          borderRadius: 1.5,
                          border: 1,
                          borderColor: 'divider',
                          overflow: 'hidden',
                        }}
                      >
                        <OptimizedImage
                          src={rv.imageUrl}
                          alt="Фото к отзыву"
                          widths={[320, 640]}
                          sizes="140px"
                          sx={{
                            width: '100%',
                            height: '100%',
                            objectFit: 'cover',
                          }}
                        />
                      </Box>
                    )}
                  </Stack>
                </Paper>
              )
            })}
            {reviewsQuery.data.total > reviewsQuery.data.items.length && (
              <Typography variant="caption" color="text.secondary" sx={{ display: 'block', mt: 1 }}>
                Всего {reviewsCountRu(reviewsQuery.data.total)} — ниже показаны последние{' '}
                {reviewsQuery.data.items.length}.
              </Typography>
            )}
          </Stack>
        )}
      </Box>

      <Dialog fullScreen open={viewerOpen} onClose={() => setViewerOpen(false)}>
        <Box sx={{ position: 'relative', height: '100%', bgcolor: 'black' }}>
          <IconButton
            onClick={() => setViewerOpen(false)}
            sx={{ position: 'absolute', top: 12, right: 12, zIndex: 2, color: 'white' }}
            aria-label="Закрыть"
          >
            <X />
          </IconButton>

          <Swiper
            modules={[Navigation]}
            navigation
            initialSlide={viewerIndex}
            style={{ width: '100%', height: '100%' }}
          >
            {imageUrls.map((url) => (
              <SwiperSlide key={`fs:${url}`}>
                <Box
                  component="img"
                  src={url}
                  alt={p.title}
                  sx={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }}
                />
              </SwiperSlide>
            ))}
          </Swiper>
        </Box>
      </Dialog>
    </Box>
  )
}
