'use client'

import {
  Avatar,
  Badge,
  Card,
  CardContent,
  CardMedia,
  Chip,
  Divider,
  Grid,
  List,
  ListItem,
  ListItemIcon,
  ListItemText,
  Typography
} from '@mui/material'
import { useParams } from 'next/navigation'
import React, { useEffect } from 'react'
import { useDispatch } from 'react-redux'
import Loading from '../../../../../components/layout/shared/Loading'
import { setProduct } from '../../../../../redux-store/slices/product'
import { useProductById } from '../../../../../services/queries/products'
import { ProductVariant } from '../../../../../types/services/product'
import { formatCurrency, formatDate } from '../../../../../utils/transform'
// Tabler icons (using class names)
const TablerIcon = ({ name, className = '' }: { name: string; className?: string }) => (
  <i className={`tabler-${name} ${className}`} />
)

const ProductDetail = () => {
  const dispatch = useDispatch()
  const params = useParams()

  const { data: product, isLoading, error } = useProductById(params?.id as string)

  useEffect(() => {
    if (product) {
      dispatch(setProduct(product))
    }
  }, [product, dispatch])

  const getBusinessTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'restaurant':
        return 'primary'
      case 'retail':
        return 'secondary'
      case 'cafe':
        return 'info'
      default:
        return 'default'
    }
  }

  const getPrinterTypeColor = (type: string) => {
    switch (type.toLowerCase()) {
      case 'kitchen':
        return 'warning'
      case 'bar':
        return 'info'
      case 'receipt':
        return 'success'
      default:
        return 'default'
    }
  }

  const getPlainText = (html: string) => {
    const doc = new DOMParser().parseFromString(html, 'text/html')
    return doc.body.textContent || ''
  }

  if (isLoading) return <Loading />

  return (
    <div className='max-w-6xl mx-auto p-4 space-y-6'>
      {/* Header Card */}
      <Card className='shadow-lg'>
        <Grid container>
          <Grid item xs={12} md={4}>
            <CardMedia
              component='img'
              sx={{ height: 300, objectFit: 'cover' }}
              image={product.image_url || '/placeholder-image.jpg'}
              alt={product.name}
              className='rounded-l-lg'
            />
          </Grid>
          <Grid item xs={12} md={8}>
            <CardContent className='h-full flex flex-col justify-between'>
              <div>
                <div className='flex items-start justify-between mb-3'>
                  <div>
                    <Typography variant='h4' component='h1' className='font-bold text-gray-800 mb-2'>
                      {product.name}
                    </Typography>
                    <div className='flex items-center gap-2 mb-3'>
                      <Chip
                        icon={<TablerIcon name='barcode' className='text-sm' />}
                        label={product.sku}
                        size='small'
                        variant='outlined'
                      />
                      <Chip
                        icon={<TablerIcon name={product.is_active ? 'check-circle' : 'x-circle'} className='text-sm' />}
                        label={product.is_active ? 'Active' : 'Inactive'}
                        color={product.is_active ? 'success' : 'error'}
                        size='small'
                      />
                    </div>
                  </div>
                </div>

                {product.description && (
                  <Typography variant='body1' className='text-gray-600 mb-4'>
                    {getPlainText(product.description)}
                  </Typography>
                )}

                <div className='grid grid-cols-2 gap-4 mb-4'>
                  <div className='flex items-center gap-2'>
                    <TablerIcon name='currency-dollar' className='text-green-600 text-xl' />
                    <div>
                      <Typography variant='body2' className='text-gray-500'>
                        Price
                      </Typography>
                      <Typography variant='h6' className='font-semibold text-green-600'>
                        {formatCurrency(product.price)}
                      </Typography>
                    </div>
                  </div>
                  <div className='flex items-center gap-2'>
                    <TablerIcon name='receipt' className='text-orange-600 text-xl' />
                    <div>
                      <Typography variant='body2' className='text-gray-500'>
                        Cost
                      </Typography>
                      <Typography variant='h6' className='font-semibold text-orange-600'>
                        {formatCurrency(product.cost)}
                      </Typography>
                    </div>
                  </div>
                </div>

                <div className='flex gap-2'>
                  <Chip
                    icon={<TablerIcon name='building-store' className='text-sm' />}
                    label={product.business_type}
                    color={getBusinessTypeColor(product.business_type)}
                    size='small'
                  />
                  <Chip
                    icon={<TablerIcon name='printer' className='text-sm' />}
                    label={product.printer_type}
                    color={getPrinterTypeColor(product.printer_type)}
                    size='small'
                  />
                </div>
              </div>
            </CardContent>
          </Grid>
        </Grid>
      </Card>

      <Grid container spacing={3}>
        {/* Product Information */}
        <Grid item xs={12} md={8}>
          <Card className='shadow-md'>
            <CardContent>
              <Typography variant='h6' className='font-semibold mb-4 flex items-center gap-2'>
                <TablerIcon name='info-circle' className='text-blue-600 text-xl' />
                Product Information
              </Typography>
              <div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Product ID
                  </Typography>
                  <Typography variant='body1' className='font-mono text-sm bg-gray-100 p-2 rounded'>
                    {product.id}
                  </Typography>
                </div>
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Category ID
                  </Typography>
                  <Typography variant='body1' className='font-mono text-sm bg-gray-100 p-2 rounded'>
                    {product.category_id}
                  </Typography>
                </div>
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Organization ID
                  </Typography>
                  <Typography variant='body1' className='font-mono text-sm bg-gray-100 p-2 rounded'>
                    {product.organization_id}
                  </Typography>
                </div>
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Profit Margin
                  </Typography>
                  <Typography variant='body1' className='font-semibold text-green-600'>
                    {formatCurrency(product.price - product.cost)}
                    <span className='text-sm text-gray-500 ml-1'>
                      ({(((product.price - product.cost) / product.cost) * 100).toFixed(1)}%)
                    </span>
                  </Typography>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Variants Section */}
          {product.variants && product.variants.length > 0 && (
            <Card className='shadow-md mt-4'>
              <CardContent>
                <Typography variant='h6' className='font-semibold mb-4 flex items-center gap-2'>
                  <TablerIcon name='versions' className='text-purple-600 text-xl' />
                  Product Variants
                  <Badge badgeContent={product.variants.length} color='primary' />
                </Typography>
                <List>
                  {product.variants.map((variant: ProductVariant, index: number) => (
                    <React.Fragment key={variant.id}>
                      <ListItem className='px-0'>
                        <ListItemIcon>
                          <Avatar className='bg-purple-100 text-purple-600 w-8 h-8 text-sm'>
                            {variant.name.charAt(0)}
                          </Avatar>
                        </ListItemIcon>
                        <ListItemText
                          primary={
                            <div className='flex items-center justify-between'>
                              <Typography variant='subtitle1' className='font-medium'>
                                {variant.name}
                              </Typography>
                              <div className='flex gap-3'>
                                <Typography variant='body2' className='text-green-600 font-semibold'>
                                  +{formatCurrency(variant.price_modifier)}
                                </Typography>
                                <Typography variant='body2' className='text-orange-600'>
                                  Cost: {formatCurrency(variant.cost)}
                                </Typography>
                              </div>
                            </div>
                          }
                          secondary={
                            <Typography variant='caption' className='text-gray-500'>
                              Total Price: {formatCurrency(product.price + variant.price_modifier)}
                            </Typography>
                          }
                        />
                      </ListItem>
                      {index < product.variants.length - 1 && <Divider />}
                    </React.Fragment>
                  ))}
                </List>
              </CardContent>
            </Card>
          )}
        </Grid>

        {/* Metadata & Timestamps */}
        <Grid item xs={12} md={4}>
          <Card className='shadow-md'>
            <CardContent>
              <Typography variant='h6' className='font-semibold mb-4 flex items-center gap-2'>
                <TablerIcon name='clock' className='text-indigo-600 text-xl' />
                Timestamps
              </Typography>
              <div className='space-y-3'>
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Created
                  </Typography>
                  <Typography variant='body2' className='text-sm'>
                    {formatDate(product.created_at)}
                  </Typography>
                </div>
                <Divider />
                <div>
                  <Typography variant='body2' className='text-gray-500 mb-1'>
                    Last Updated
                  </Typography>
                  <Typography variant='body2' className='text-sm'>
                    {formatDate(product.updated_at)}
                  </Typography>
                </div>
              </div>

              {Object.keys(product.metadata).length > 0 && (
                <>
                  <Divider className='my-4' />
                  <Typography variant='h6' className='font-semibold mb-3'>
                    Metadata
                  </Typography>
                  <div className='space-y-2'>
                    {Object.entries(product.metadata).map(([key, value]) => (
                      <div key={key}>
                        <Typography variant='body2' className='text-gray-500 mb-1 capitalize'>
                          {key.replace(/_/g, ' ')}
                        </Typography>
                        <Typography variant='body2' className='text-sm bg-gray-50 p-2 rounded'>
                          {typeof value === 'object' ? JSON.stringify(value, null, 2) : String(value)}
                        </Typography>
                      </div>
                    ))}
                  </div>
                </>
              )}
            </CardContent>
          </Card>
        </Grid>
      </Grid>
    </div>
  )
}

export default ProductDetail
