'use client'

import type { ReactNode } from 'react'

import { useParams, useRouter } from 'next/navigation'
import { useGetProductsByCategory } from '@/@core/hooks/data/categories'
import { getImageUrl } from '@/utils'
import { Card, Typography, Grid, Button, Divider, Chip, Box, Stack, CircularProgress } from '@mui/material'

type FeedbackCardProps = {
  icon: string
  title: string
  subtitle?: string
  color?: 'primary' | 'secondary' | 'error' | 'warning' | 'info' | 'success'
  showSpinner?: boolean
  action?: ReactNode
}

const renderFeedbackCard = ({ icon, title, subtitle, color = 'primary', showSpinner, action }: FeedbackCardProps) => (
  <Box className='min-h-[60vh] w-full flex items-center justify-center p-6'>
    <Card className='w-full max-w-lg p-8 text-center shadow-lg'>
      <Stack spacing={3} alignItems='center'>
        <Box
          sx={{
            width: 90,
            height: 90,
            borderRadius: '50%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: `var(--mui-palette-${color}-light)`,
            color: `var(--mui-palette-${color}-main)`
          }}
        >
          {showSpinner ? <CircularProgress color={color} /> : <i className={`${icon} text-4xl`} />}
        </Box>
        <Stack spacing={1} alignItems='center'>
          <Typography variant='h5' fontWeight={700}>
            {title}
          </Typography>
          {subtitle && (
            <Typography variant='body2' color='text.secondary'>
              {subtitle}
            </Typography>
          )}
        </Stack>
        {action}
      </Stack>
    </Card>
  </Box>
)

export default function CategoryProductsPage() {
  const params = useParams()
  const id = params?.id as string
  const lang = (params?.lang as string) || 'ar'
  const isArabic = lang === 'ar'
  const router = useRouter()
  const { data, isLoading, isError } = useGetProductsByCategory(id)
  const t = (ar: string, en: string) => (isArabic ? ar : en)
  const currencySuffix = isArabic ? 'ر.س' : 'SAR'

  if (isLoading)
    return renderFeedbackCard({
      icon: 'tabler-loader-2',
      title: t('جاري تحميل البيانات...', 'Loading category data...'),
      subtitle: t('يرجى الانتظار للحظات بينما نقوم بإحضار بيانات الفئة والمنتجات.', 'Please wait a moment while we fetch the category and products.'),
      showSpinner: true,
      color: 'primary'
    })

  if (isError)
    return renderFeedbackCard({
      icon: 'tabler-alert-triangle',
      title: t('حدث خطأ أثناء تحميل البيانات', 'Unable to load category data'),
      subtitle: t('يمكنك إعادة تحميل الصفحة أو المحاولة لاحقاً.', 'You can refresh the page or try again later.'),
      color: 'error',
      action: (
        <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
          <Button variant='contained' color='primary' onClick={() => router.refresh()} startIcon={<i className='tabler-refresh' />}>
            {t('إعادة المحاولة', 'Retry')}
          </Button>
          <Button variant='outlined' onClick={() => router.back()} startIcon={<i className='tabler-arrow-left rtl:rotate-180' />}>
            {t('الرجوع للخلف', 'Go back')}
          </Button>
        </Stack>
      )
    })

  const category = data?.data?.category
  const products = data?.data?.products || []

  if (!category)
    return renderFeedbackCard({
      icon: 'tabler-box-off',
      title: t('لم يتم العثور على الفئة المطلوبة.', 'Category not found'),
      subtitle: t('قد تكون الفئة محذوفة أو ربما لا تملك صلاحية الوصول إليها.', 'It may have been removed or you may not have access.'),
      color: 'warning',
      action: (
        <Button variant='contained' onClick={() => router.back()} startIcon={<i className='tabler-arrow-left' />}>
          {t('العودة إلى القائمة', 'Return to list')}
        </Button>
      )
    })

  return (
    <div className='p-6 space-y-8'>
      <Button variant='outlined' onClick={() => router.back()} startIcon={<i className='tabler-arrow-left' />} sx={{ borderRadius: 3 }}>
        {t('العودة إلى الفئات', 'Back to categories')}
      </Button>

      <Card className='p-6 shadow-sm hover:shadow-md transition-all duration-300'>
        <div className='flex flex-col md:flex-row gap-6 items-center md:items-start'>
          <img
            src={getImageUrl(category.image)}
            alt={isArabic ? category.name_ar : category.name_en}
            className='w-full md:w-72 h-52 object-cover rounded-2xl shadow-sm'
          />
          <div className='space-y-2'>
            <Typography variant='h4' className='font-bold'>
              {isArabic ? category.name_ar : category.name_en} ({isArabic ? category.name_en : category.name_ar})
            </Typography>
            <Typography variant='body1' color='text.secondary'>
              {isArabic ? category.description_ar : category.description_en}
            </Typography>
            <Divider sx={{ my: 2 }} />
            <Typography variant='body2' color='textSecondary'>
              {t('الحالة', 'Status')}: {category.is_active ? t('نشطة', 'Active') : t('غير نشطة', 'Inactive')}
            </Typography>
            <Typography variant='body2' color='textSecondary'>
              {t('ترتيب العرض', 'Display order')}: {category.sort_order}
            </Typography>
          </div>
        </div>
      </Card>

      <Typography variant='h5' className='font-semibold mb-2'>
        {t('المنتجات المرتبطة بالفئة', 'Products in this category')} ({products.length})
      </Typography>

      {products.length === 0 ? (
        <Typography color='textSecondary'>{t('لا توجد منتجات مرتبطة بهذه الفئة حتى الآن.', 'No products linked to this category yet.')}</Typography>
      ) : (
        <Grid container spacing={3}>
          {products.map(product => (
            <Grid item xs={12} sm={6} md={4} lg={3} key={product.id}>
              <Card
                className='relative flex flex-col items-center p-4 transition-all duration-300 hover:shadow-2xl hover:-translate-y-1'
                sx={{
                  borderRadius: '20px',
                  height: 380,
                  display: 'flex',
                  justifyContent: 'space-between'
                }}
              >
                <Box className='relative w-full'>
                  {product.has_discount && (
                    <Chip
                      label={`${t('خصم', 'OFF')} ${product.discount_percentage}%`}
                      color='error'
                      size='small'
                      sx={{
                        position: 'absolute',
                        top: 8,
                        left: 8,
                        fontWeight: 'bold'
                      }}
                    />
                  )}
                  <img
                    src={getImageUrl(product.image)}
                    alt={isArabic ? product.name_ar : product.name_en}
                    className='w-full h-48 object-cover rounded-lg shadow-sm transition-all duration-300 hover:scale-105'
                  />
                </Box>

                <div className='text-center space-y-1 mt-2'>
                  <Typography variant='h6' className='font-semibold truncate'>
                    {isArabic ? product.name_ar : product.name_en}
                  </Typography>
                  <Typography variant='body2' color='textSecondary'>
                    {isArabic ? product.name_en : product.name_ar}
                  </Typography>

                  <div className='flex justify-center items-center gap-2'>
                    <Typography variant='body1' color='primary' fontWeight='bold'>
                      {product.discount_price ?? product.price} {currencySuffix}
                    </Typography>
                    {product.has_discount && (
                      <Typography variant='body2' color='textSecondary' sx={{ textDecoration: 'line-through', opacity: 0.6 }}>
                        {product.price} {currencySuffix}
                      </Typography>
                    )}
                  </div>

                  <Typography variant='caption' color='textSecondary'>
                    {t('السعرات الحرارية', 'Calories')}: {product.calories ?? '--'} | {t('مدة التحضير', 'Prep time')}:{' '}
                    {product.preparation_time ?? '--'} {t('دقائق', 'min')}
                  </Typography>
                </div>
              </Card>
            </Grid>
          ))}
        </Grid>
      )}
    </div>
  )
}
