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 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 { fetchPublicProduct } from '@/entities/product/api/product-api'
import { ToggleCartIcon } from '@/features/cart/toggle-cart-icon'
import { ProductReviewsList } from '@/features/product-review'
import { formatPriceRub } from '@/shared/lib/format-price'
import { getOriginalWebpUrl } from '@/shared/lib/get-original-webp-url'
import { reviewsCountRu } from '@/shared/lib/reviews-count-ru'
import { usePageTitle } from '@/shared/lib/use-page-title'
import { $user } from '@/shared/model/auth'
import { OptimizedImage } from '@/shared/ui/OptimizedImage'

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),
  })

  usePageTitle(productQuery.data?.title ?? null)

  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" sx={{ width: '100%', aspectRatio: '3/4' }} />
        <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>
      <Stack direction={{ xs: 'column', md: 'row' }} spacing={{ xs: 3, md: 4 }}>
        <Box sx={{ flex: { md: '1 1 50%' }, minWidth: 0 }}>
          {imageUrls.length > 0 ? (
            <Box
              sx={{
                borderRadius: '20px 20px 12px 12px',
                overflow: 'hidden',
                border: 'none',
                boxShadow: '0 4px 20px rgba(0,0,0,0.08)',
                bgcolor: 'background.paper',
                width: '100%',
                aspectRatio: '3/4',
              }}
            >
              <Swiper modules={[Navigation]} navigation style={{ width: '100%', height: '100%' }}>
                {imageUrls.map((url, idx) => (
                  <SwiperSlide key={url}>
                    <Box
                      onClick={() => {
                        setViewerIndex(idx)
                        setViewerOpen(true)
                      }}
                      sx={{
                        width: '100%',
                        height: '100%',
                        cursor: 'zoom-in',
                        userSelect: 'none',
                      }}
                    >
                      <OptimizedImage
                        src={url}
                        alt={p.title}
                        sizes="(max-width: 900px) 100vw, 50vw"
                        sx={{
                          width: '100%',
                          height: '100%',
                          objectFit: 'cover',
                        }}
                      />
                    </Box>
                  </SwiperSlide>
                ))}
              </Swiper>
            </Box>
          ) : (
            <Box
              sx={{
                width: '100%',
                aspectRatio: '3/4',
                borderRadius: 2,
                overflow: 'hidden',
                border: 1,
                borderColor: 'divider',
                bgcolor: 'grey.100',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            >
              <Typography color="text.secondary">Нет фото</Typography>
            </Box>
          )}
        </Box>

        <Box sx={{ flex: { md: '1 1 50%' }, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 3 }}>
          <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="h3" component="h1" sx={{ fontWeight: 700, letterSpacing: '-0.75px' }}>
            {p.title}
          </Typography>
          <Typography variant="h4" color="primary" sx={{ fontWeight: 700, fontVariantNumeric: 'tabular-nums' }}>
            {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>
          )}
        </Box>
      </Stack>

      <Divider sx={{ my: { xs: 3, md: 4 } }} />

      <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>
      )}

      <ProductReviewsList productId={id} />

      <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={getOriginalWebpUrl(url)}
                  alt={p.title}
                  sx={{ width: '100%', height: '100%', objectFit: 'contain', display: 'block' }}
                />
              </SwiperSlide>
            ))}
          </Swiper>
        </Box>
      </Dialog>
    </Box>
  )
}
