'use client'

import { useMemo } from 'react'
import { useParams, useRouter } from 'next/navigation'
import { useTranslations, useLocale } from 'next-intl'
import Card from '@mui/material/Card'
import Box from '@mui/material/Box'
import Stack from '@mui/material/Stack'
import Typography from '@mui/material/Typography'
import Chip from '@mui/material/Chip'
import Grid from '@mui/material/Grid2'
import Divider from '@mui/material/Divider'
import Button from '@mui/material/Button'
import Alert from '@mui/material/Alert'
import Skeleton from '@mui/material/Skeleton'

import { useGetProduct } from '@/@core/hooks/data/products/useGetOneProduct'
import { getImageUrl } from '@/utils'

const ProductDetailSkeleton = () => (
  <Card className='p-6 space-y-4'>
    <Skeleton variant='text' width='40%' height={40} />
    <Skeleton variant='text' width='60%' height={20} />
    <Skeleton variant='rectangular' height={300} />
    <Grid container spacing={3}>
      {Array.from({ length: 4 }).map((_, index) => (
        <Grid size={{ xs: 12, md: 6 }} key={index}>
          <Skeleton variant='rectangular' height={140} />
        </Grid>
      ))}
    </Grid>
  </Card>
)

const InfoRow = ({ label, value }: { label: string; value?: string | number | null }) => (
  <Stack spacing={0.5}>
    <Typography variant='body2' color='text.secondary'>
      {label}
    </Typography>
    <Typography variant='subtitle2'>{value ?? '—'}</Typography>
  </Stack>
)

const ProductDetailPage = () => {
  const t = useTranslations('product')
  const listT = useTranslations('PRODUCTS')
  const router = useRouter()
  const locale = useLocale()
  const params = useParams()
  const productId = params?.productId as string | undefined

  const { data, isLoading, isError, refetch } = useGetProduct(productId)
  const product = data?.data

  const galleryImages = useMemo(() => {
    if (!product) return [] as string[]

    const main = product?.image
    const extras = product?.image_urls || []
    const urls = [main, ...extras].filter(Boolean) as string[]

    return urls?.map(url => getImageUrl(url))
  }, [product])

  if (isLoading) return <ProductDetailSkeleton />

  if (isError)
    return (
      <Alert
        severity='error'
        action={
          <Button color='inherit' size='small' onClick={() => refetch()}>
            {t('retry')}
          </Button>
        }
      >
        {t('error')}
      </Alert>
    )

  if (!product)
    return (
      <Alert
        severity='warning'
        action={
          <Button color='inherit' size='small' onClick={() => router.push(`/${locale}/products`)}>
            {listT('backToList')}
          </Button>
        }
      >
        {t('notFound')}
      </Alert>
    )

  const name = locale === 'ar' ? product.name_ar : product.name_en
  const description = locale === 'ar' ? product.description_ar : product.description_en
  const categoryName = locale === 'ar' ? product.category?.name_ar : product.category?.name_en
  const categoryDescription = locale === 'ar' ? product.category?.description_ar : product.category?.description_en

  return (
    <Stack spacing={4}>
      <Stack direction='row' justifyContent='space-between' alignItems='center' flexWrap='wrap' gap={2}>
        <Button
          startIcon={<i className='tabler-arrow-left' />}
          variant='text'
          onClick={() => router.push(`/${locale}/products`)}
        >
          {listT('backToList')}
        </Button>
        <Stack direction='row' spacing={1}>
          <Chip
            color={product.is_available ? 'success' : 'default'}
            variant={product.is_available ? 'filled' : 'outlined'}
            label={product.is_available ? t('availableBadge') : t('unavailableBadge')}
          />
          <Chip
            color={product.is_featured ? 'secondary' : 'default'}
            variant={product.is_featured ? 'filled' : 'outlined'}
            label={product.is_featured ? t('featuredBadge') : t('notFeaturedBadge')}
          />
        </Stack>
      </Stack>

      <Card className='p-6'>
        <Stack spacing={3}>
          <Box>
            <Typography variant='h4' fontWeight={600} gutterBottom>
              {name}
            </Typography>
            <Typography variant='body1' color='text.secondary'>
              {categoryName}
            </Typography>
            {categoryDescription && (
              <Typography variant='body2' color='text.secondary'>
                {categoryDescription}
              </Typography>
            )}
          </Box>

          {galleryImages?.length > 0 && (
            <Box
              className='grid gap-3'
              sx={{
                gridTemplateColumns: { xs: 'repeat(auto-fit,minmax(160px,1fr))', md: 'repeat(4, minmax(0, 1fr))' }
              }}
            >
              {galleryImages?.map((img, index) => (
                <Box key={index} component='figure' sx={{ m: 0 }}>
                  <img src={img} alt={name} className='w-full h-48 object-cover rounded-lg border border-divider' />
                </Box>
              ))}
            </Box>
          )}

          {description && <Typography>{description}</Typography>}

          <Grid container spacing={4}>
            <Grid size={{ xs: 12, md: 8 }}>
              <Card variant='outlined'>
                <Stack spacing={3} className='p-4'>
                  <Typography variant='h6'>{t('pricing')}</Typography>
                  <Stack direction={{ xs: 'column', sm: 'row' }} spacing={4} alignItems='baseline'>
                    <div>
                      <Typography variant='body2' color='text.secondary'>
                        {t('currentPrice')}
                      </Typography>
                      <Typography variant='h4'>{product.current_price}</Typography>
                    </div>
                    <div>
                      <Typography variant='body2' color='text.secondary'>
                        {t('basePrice')}
                      </Typography>
                      <Typography
                        variant='h6'
                        sx={{ textDecoration: product.has_discount ? 'line-through' : 'none' }}
                        color={product.has_discount ? 'text.secondary' : 'text.primary'}
                      >
                        {product.price}
                      </Typography>
                    </div>
                    {product.has_discount && (
                      <Chip color='success' label={`${t('discount')}: ${product.discount_percentage}%`} />
                    )}
                  </Stack>
                </Stack>
              </Card>
            </Grid>

            <Grid size={{ xs: 12, md: 4 }}>
              <Card variant='outlined' className='h-full'>
                <Stack spacing={3} className='p-4'>
                  <Typography variant='h6'>{t('metadata')}</Typography>
                  <Divider />
                  <InfoRow label='ID' value={product.id} />
                  <InfoRow label={t('sku')} value={product.sku} />
                  <InfoRow
                    label={t('preparationTime')}
                    value={product.preparation_time ? t('minutesLabel', { value: product.preparation_time }) : '—'}
                  />
                  <InfoRow
                    label={t('calories')}
                    value={product.calories ? t('caloriesLabel', { value: product.calories }) : '—'}
                  />
                  <InfoRow
                    label={t('statusLabel')}
                    value={product.is_available ? t('availableBadge') : t('unavailableBadge')}
                  />
                </Stack>
              </Card>
            </Grid>
          </Grid>
        </Stack>
      </Card>
    </Stack>
  )
}

export default ProductDetailPage
