'use client'

import {
  Avatar,
  Box,
  Button,
  Card,
  CardContent,
  CardHeader,
  Chip,
  Grid,
  Paper,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Tooltip,
  Typography
} from '@mui/material'
import { useParams } from 'next/navigation'
import { useState } from 'react'
import { useDispatch } from 'react-redux'
import Loading from '../../../../../components/layout/shared/Loading'
import { useProductRecipesByProduct } from '../../../../../services/queries/productRecipes'
import { useProductById } from '../../../../../services/queries/products'
import { ProductVariant } from '../../../../../types/services/product'
import { formatCurrency } from '../../../../../utils/transform'
import AddRecipeDrawer from './AddRecipeDrawer'
import ConfirmDeleteDialog from '../../../../../components/dialogs/confirm-delete'
import { useProductRecipesMutation } from '../../../../../services/mutations/productRecipes'
import { setProductRecipe, setProductVariant } from '../../../../../redux-store/slices/productRecipe'
import { ProductRecipe } from '../../../../../types/services/productRecipe'

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

  const [openProductRecipe, setOpenProductRecipe] = useState(false)
  const [openConfirm, setOpenConfirm] = useState(false)
  const [productRecipeId, setProductRecipeId] = useState('')

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

  const { deleteProductRecipe } = useProductRecipesMutation()

  const handleOpenProductRecipe = (variant: any) => {
    setOpenProductRecipe(true)
    dispatch(setProductVariant(variant))
  }

  const handleOpenEditProductRecipe = (recipe: ProductRecipe) => {
    setOpenProductRecipe(true)
    dispatch(setProductRecipe(recipe))
  }

  const handleDeleteRecipe = () => {
    deleteProductRecipe.mutate(productRecipeId, {
      onSuccess: () => {
        setOpenConfirm(false)
      }
    })
  }

  if (isLoading || isLoadingProductRecipe) return <Loading />

  return (
    <>
      <div className='space-y-6'>
        {/* Header Card */}
        <Card>
          <CardHeader
            avatar={<Avatar src={product?.image_url || ''} alt={product?.name} className='w-16 h-16' />}
            title={
              <div className='flex items-center gap-3'>
                <Typography variant='h4' component='h1' className='font-bold'>
                  {product?.name}
                </Typography>
                <Chip
                  label={product?.is_active ? 'Active' : 'Inactive'}
                  color={product?.is_active ? 'success' : 'error'}
                  size='small'
                />
              </div>
            }
            subheader={
              <div className='flex flex-col gap-1 mt-2'>
                <Typography variant='body2' color='textSecondary'>
                  SKU: {product?.sku} • Category: {product?.business_type}
                </Typography>
                <div className='flex gap-4'>
                  <Typography variant='body2'>
                    <span className='font-semibold'>Price:</span> {formatCurrency(product?.price || 0)}
                  </Typography>
                  <Typography variant='body2'>
                    <span className='font-semibold'>Base Cost:</span> {formatCurrency(product?.cost || 0)}
                  </Typography>
                </div>
              </div>
            }
          />
        </Card>

        {/* {productRecipe && ( */}
        <div className='space-y-6'>
          {/* Recipe Details by Variant */}
          <div className='space-y-4'>
            <div className='flex items-center gap-2 mb-4'>
              <i className='tabler-chef-hat text-textPrimary text-xl' />
              <Typography variant='h5' component='h2' className='font-semibold'>
                Recipe Details
              </Typography>
            </div>

            <Card>
              <CardHeader
                title={
                  <div className='flex items-center justify-between'>
                    <div className='flex items-center gap-3'>
                      <i className='tabler-variant text-blue-600 text-lg' />
                      <Typography variant='h6' className='font-semibold'>
                        Original Variant
                      </Typography>
                    </div>
                    <div className='flex gap-4 text-sm'>
                      <Chip label={`Cost: ${formatCurrency(product?.cost || 0)}`} variant='outlined' color='primary' />
                      <Chip
                        label={`Price Modifier: ${formatCurrency(product?.price || 0)}`}
                        variant='outlined'
                        color='secondary'
                      />
                    </div>
                  </div>
                }
              />
              <CardContent>
                <TableContainer component={Paper} variant='outlined'>
                  <Table>
                    <TableHead>
                      <TableRow className='bg-gray-50'>
                        <TableCell className='font-semibold'>
                          <div className='flex items-center gap-2'>
                            <i className='tabler-ingredients text-green-600' />
                            Ingredient
                          </div>
                        </TableCell>
                        <TableCell className='font-semibold text-center'>
                          <div className='flex items-center justify-center gap-2'>
                            <i className='tabler-scale text-orange-600' />
                            Quantity
                          </div>
                        </TableCell>
                        <TableCell className='font-semibold text-center'>
                          <div className='flex items-center justify-center gap-2'>
                            <i className='tabler-currency-dollar text-purple-600' />
                            Unit Cost
                          </div>
                        </TableCell>
                        <TableCell className='font-semibold text-center'>
                          <div className='flex items-center justify-center gap-2'>
                            <i className='tabler-package text-blue-600' />
                            Stock Available
                          </div>
                        </TableCell>
                        <TableCell className='font-semibold text-right'>
                          <div className='flex items-center justify-end gap-2'>
                            <i className='tabler-calculator text-red-600' />
                            Total Cost
                          </div>
                        </TableCell>
                        <TableCell></TableCell>
                      </TableRow>
                    </TableHead>
                    <TableBody>
                      {productRecipe?.length ? (
                        productRecipe
                          .filter((item: ProductRecipe) => item.variant_id === null)
                          .map((item: ProductRecipe, index: number) => (
                            <TableRow key={index} className='hover:bg-gray-50'>
                              <TableCell>
                                <div className='flex items-center gap-3'>
                                  <div className='w-2 h-2 rounded-full bg-green-500' />
                                  <div>
                                    <Typography variant='body2' className='font-medium capitalize'>
                                      {item.ingredient.name}
                                    </Typography>
                                    <Typography variant='caption' color='textSecondary'>
                                      {item.ingredient.is_semi_finished ? 'Semi-finished' : 'Raw ingredient'}
                                    </Typography>
                                  </div>
                                </div>
                              </TableCell>
                              <TableCell className='text-center'>
                                <Chip label={item.quantity} size='small' variant='outlined' color='primary' />
                              </TableCell>
                              <TableCell className='text-center'>{formatCurrency(item.ingredient.cost)}</TableCell>
                              <TableCell className='text-center'>
                                <Chip
                                  label={item.ingredient.stock}
                                  size='small'
                                  color={item.ingredient.stock > 5 ? 'success' : 'warning'}
                                  variant='outlined'
                                />
                              </TableCell>
                              <TableCell className='text-right font-medium'>
                                {formatCurrency(item.ingredient.cost * item.quantity)}
                              </TableCell>
                              <TableCell className='text-right'>
                                <Button size='small' color='info' onClick={() => handleOpenEditProductRecipe(item)}>
                                  <Tooltip title='Edit'>
                                    <i className='tabler-pencil' />
                                  </Tooltip>
                                </Button>
                                <Button
                                  size='small'
                                  color='error'
                                  onClick={() => {
                                    setProductRecipeId(item.id)
                                    setOpenConfirm(true)
                                  }}
                                >
                                  <Tooltip title='Delete'>
                                    <i className='tabler-trash' />
                                  </Tooltip>
                                </Button>
                              </TableCell>
                            </TableRow>
                          ))
                      ) : (
                        <TableRow>
                          <TableCell colSpan={5} className='text-center'>
                            <Typography variant='body2' color='textSecondary'>
                              No ingredients found for this variant
                            </Typography>
                          </TableCell>
                        </TableRow>
                      )}
                    </TableBody>
                  </Table>
                </TableContainer>

                {/* Variant Summary */}
                {productRecipe?.length ? (
                  <Box className='mt-4 p-4 bg-blue-50 rounded-lg'>
                    <Grid container spacing={2}>
                      <Grid item xs={12} md={6}>
                        <Typography variant='body2' className='flex items-center gap-2'>
                          <i className='tabler-list-numbers text-blue-600' />
                          <span className='font-semibold'>Total Ingredients:</span>
                          {productRecipe.filter((item: any) => item.variant_id === null).length}
                        </Typography>
                      </Grid>
                      <Grid item xs={12} md={6}>
                        <Typography variant='body2' className='flex items-center gap-2'>
                          <i className='tabler-sum text-green-600' />
                          <span className='font-semibold'>Total Recipe Cost:</span>
                          {formatCurrency(
                            productRecipe
                              .filter((item: any) => item.variant_id === null)
                              .reduce((sum: any, item: any) => sum + item.ingredient.cost * item.quantity, 0)
                          )}
                        </Typography>
                      </Grid>
                    </Grid>
                  </Box>
                ) : (
                  <Box className='mt-4 p-4 bg-blue-50 rounded-lg'>
                    <Typography variant='body2' className='flex items-center gap-2'>
                      <i className='tabler-list-numbers text-blue-600' />
                      <span className='font-semibold'>Total Ingredients:</span>
                    </Typography>
                  </Box>
                )}

                <Button
                  variant='outlined'
                  fullWidth
                  className='mt-4'
                  startIcon={<i className='tabler-plus' />}
                  onClick={() => handleOpenProductRecipe({ variant: undefined })}
                >
                  Add Ingredient
                </Button>
              </CardContent>
            </Card>

            {product?.variants?.length &&
              product.variants.map((variantData: ProductVariant, index: number) => (
                <Card key={index}>
                  <CardHeader
                    title={
                      <div className='flex items-center justify-between'>
                        <div className='flex items-center gap-3'>
                          <i className='tabler-variant text-blue-600 text-lg' />
                          <Typography variant='h6' className='font-semibold'>
                            {variantData?.name || 'Original'} Variant
                          </Typography>
                        </div>
                        <div className='flex gap-4 text-sm'>
                          <Chip
                            label={`Cost: ${formatCurrency(variantData?.cost || 0)}`}
                            variant='outlined'
                            color='primary'
                          />
                          <Chip
                            label={`Price Modifier: ${formatCurrency(variantData?.price_modifier || 0)}`}
                            variant='outlined'
                            color='secondary'
                          />
                        </div>
                      </div>
                    }
                  />
                  <CardContent>
                    <TableContainer component={Paper} variant='outlined'>
                      <Table>
                        <TableHead>
                          <TableRow className='bg-gray-50'>
                            <TableCell className='font-semibold'>
                              <div className='flex items-center gap-2'>
                                <i className='tabler-ingredients text-green-600' />
                                Ingredient
                              </div>
                            </TableCell>
                            <TableCell className='font-semibold text-center'>
                              <div className='flex items-center justify-center gap-2'>
                                <i className='tabler-scale text-orange-600' />
                                Quantity
                              </div>
                            </TableCell>
                            <TableCell className='font-semibold text-center'>
                              <div className='flex items-center justify-center gap-2'>
                                <i className='tabler-currency-dollar text-purple-600' />
                                Unit Cost
                              </div>
                            </TableCell>
                            <TableCell className='font-semibold text-center'>
                              <div className='flex items-center justify-center gap-2'>
                                <i className='tabler-package text-blue-600' />
                                Stock Available
                              </div>
                            </TableCell>
                            <TableCell className='font-semibold text-right'>
                              <div className='flex items-center justify-end gap-2'>
                                <i className='tabler-calculator text-red-600' />
                                Total Cost
                              </div>
                            </TableCell>
                          </TableRow>
                        </TableHead>
                        <TableBody>
                          {productRecipe?.length ? (
                            productRecipe
                              .filter((item: any) => item.variant_id === variantData.id)
                              .map((item: any, index: number) => (
                                <TableRow key={index} className='hover:bg-gray-50'>
                                  <TableCell>
                                    <div className='flex items-center gap-3'>
                                      <div className='w-2 h-2 rounded-full bg-green-500' />
                                      <div>
                                        <Typography variant='body2' className='font-medium capitalize'>
                                          {item.ingredient.name}
                                        </Typography>
                                        <Typography variant='caption' color='textSecondary'>
                                          {item.ingredient.is_semi_finished ? 'Semi-finished' : 'Raw ingredient'}
                                        </Typography>
                                      </div>
                                    </div>
                                  </TableCell>
                                  <TableCell className='text-center'>
                                    <Chip label={item.quantity} size='small' variant='outlined' color='primary' />
                                  </TableCell>
                                  <TableCell className='text-center'>{formatCurrency(item.ingredient.cost)}</TableCell>
                                  <TableCell className='text-center'>
                                    <Chip
                                      label={item.ingredient.stock}
                                      size='small'
                                      color={item.ingredient.stock > 5 ? 'success' : 'warning'}
                                      variant='outlined'
                                    />
                                  </TableCell>
                                  <TableCell className='text-right font-medium'>
                                    {formatCurrency(item.ingredient.cost * item.quantity)}
                                  </TableCell>
                                  <TableCell className='text-right'>
                                    <Button size='small' color='info' onClick={() => handleOpenEditProductRecipe(item)}>
                                      <Tooltip title='Edit'>
                                        <i className='tabler-pencil' />
                                      </Tooltip>
                                    </Button>
                                    <Button
                                      size='small'
                                      color='error'
                                      onClick={() => {
                                        setProductRecipeId(item.id)
                                        setOpenConfirm(true)
                                      }}
                                    >
                                      <Tooltip title='Delete'>
                                        <i className='tabler-trash' />
                                      </Tooltip>
                                    </Button>
                                  </TableCell>
                                </TableRow>
                              ))
                          ) : (
                            <TableRow>
                              <TableCell colSpan={5} className='text-center'>
                                <Typography variant='body2' color='textSecondary'>
                                  No ingredients found for this variant
                                </Typography>
                              </TableCell>
                            </TableRow>
                          )}
                        </TableBody>
                      </Table>
                    </TableContainer>

                    {/* Variant Summary */}
                    {productRecipe?.length ? (
                      <Box className='mt-4 p-4 bg-blue-50 rounded-lg'>
                        <Grid container spacing={2}>
                          <Grid item xs={12} md={6}>
                            <Typography variant='body2' className='flex items-center gap-2'>
                              <i className='tabler-list-numbers text-blue-600' />
                              <span className='font-semibold'>Total Ingredients:</span>
                              {productRecipe.filter((item: any) => item.variant_id === variantData.id).length}
                            </Typography>
                          </Grid>
                          <Grid item xs={12} md={6}>
                            <Typography variant='body2' className='flex items-center gap-2'>
                              <i className='tabler-sum text-green-600' />
                              <span className='font-semibold'>Total Recipe Cost:</span>
                              {formatCurrency(
                                productRecipe
                                  .filter((item: any) => item.variant_id === variantData.id)
                                  .reduce((sum: any, item: any) => sum + item.ingredient.cost * item.quantity, 0)
                              )}
                            </Typography>
                          </Grid>
                        </Grid>
                      </Box>
                    ) : (
                      <Box className='mt-4 p-4 bg-blue-50 rounded-lg'>
                        <Typography variant='body2' className='flex items-center gap-2'>
                          <i className='tabler-list-numbers text-blue-600' />
                          <span className='font-semibold'>Total Ingredients:</span>
                        </Typography>
                      </Box>
                    )}

                    <Button
                      variant='outlined'
                      fullWidth
                      className='mt-4'
                      startIcon={<i className='tabler-plus' />}
                      onClick={() => handleOpenProductRecipe(variantData)}
                    >
                      Add Ingredient
                    </Button>
                  </CardContent>
                </Card>
              ))}
          </div>
        </div>
      </div>

      <AddRecipeDrawer open={openProductRecipe} handleClose={() => setOpenProductRecipe(false)} product={product!} />

      <ConfirmDeleteDialog
        open={openConfirm}
        onClose={() => setOpenConfirm(false)}
        onConfirm={handleDeleteRecipe}
        isLoading={deleteProductRecipe.isPending}
        title='Delete Product Ingredient'
        message='Are you sure you want to delete this product ingredient? This action cannot be undone.'
      />
    </>
  )
}

export default ProductDetail
