'use client'
// React Imports
import { useState, useEffect } from 'react'

// MUI Imports
import Button from '@mui/material/Button'
import Drawer from '@mui/material/Drawer'
import IconButton from '@mui/material/IconButton'
import MenuItem from '@mui/material/MenuItem'
import Typography from '@mui/material/Typography'
import Divider from '@mui/material/Divider'
import Grid from '@mui/material/Grid2'
import Box from '@mui/material/Box'

// Third-party Imports
import { useForm, Controller } from 'react-hook-form'

// Component Imports
import CustomTextField from '@core/components/mui/TextField'
import { Ingredient } from '@/types/services/productRecipe'
import { useUnits } from '@/services/queries/units'
import { useUnitConventorMutation } from '@/services/mutations/unitConventor'

// Interface Integration
export interface IngredientUnitConverterRequest {
  ingredient_id: string
  from_unit_id: string
  to_unit_id: string
  conversion_factor: number
}

type Props = {
  open: boolean
  handleClose: () => void
  setData?: (data: IngredientUnitConverterRequest) => void
  data?: Ingredient // Contains ingredientId, unit info, and cost
}

type UnitConversionType = {
  satuan: string // This will be from_unit_id
  quantity: number
  unit: string // This will be to_unit_id (from data)
  hargaBeli: number // Calculated as factor * ingredientCost
  hargaJual: number
  isDefault: boolean
}

const IngedientUnitConversionDrawer = (props: Props) => {
  // Props
  const { open, handleClose, setData, data } = props

  // Extract values from data prop with safe defaults
  const ingredientId = data?.id || ''
  const toUnitId = data?.unit_id || data?.unit?.id || ''
  const ingredientCost = data?.cost || 0

  const {
    data: units,
    isLoading,
    error,
    isFetching
  } = useUnits({
    page: 1,
    limit: 20
  })

  // Vars - initial state with values from data
  const getInitialConversion = () => ({
    satuan: '',
    quantity: 1,
    unit: toUnitId, // Set from data
    hargaBeli: ingredientCost, // Will be calculated as factor * ingredientCost
    hargaJual: 0,
    isDefault: true
  })

  // States
  const [conversion, setConversion] = useState<UnitConversionType>(getInitialConversion())
  const { createUnitConventer } = useUnitConventorMutation()

  // Hooks
  const {
    control,
    reset: resetForm,
    handleSubmit,
    setValue,
    formState: { errors }
  } = useForm<UnitConversionType>({
    defaultValues: getInitialConversion()
  })

  // Update form when data changes
  useEffect(() => {
    if (toUnitId || ingredientCost) {
      const updatedConversion = getInitialConversion()
      setConversion(updatedConversion)
      resetForm(updatedConversion)
    }
  }, [toUnitId, ingredientCost, resetForm])

  // Functions untuk konversi unit
  const handleChangeConversion = (field: keyof UnitConversionType, value: any) => {
    const newConversion = { ...conversion, [field]: value }
    setConversion(newConversion)
    setValue(field, value)
  }

  const onSubmit = (data: UnitConversionType) => {
    // Transform form data to IngredientUnitConverterRequest
    const converterRequest: IngredientUnitConverterRequest = {
      ingredient_id: ingredientId,
      from_unit_id: conversion.satuan,
      to_unit_id: toUnitId, // Use toUnitId from data prop
      conversion_factor: conversion.quantity
    }

    console.log('Unit conversion request:', converterRequest)

    // if (setData) {
    //   setData(converterRequest)
    // }
    createUnitConventer.mutate(converterRequest, {
      onSuccess: () => {
        handleClose()
        resetForm(getInitialConversion())
      }
    })
  }

  const handleReset = () => {
    handleClose()
    const resetData = getInitialConversion()
    setConversion(resetData)
    resetForm(resetData)
  }

  const formatNumber = (value: number) => {
    return new Intl.NumberFormat('id-ID').format(value)
  }

  const parseNumber = (value: string) => {
    return parseInt(value.replace(/\./g, '')) || 0
  }

  // Calculate total purchase price: factor * ingredientCost
  const totalPurchasePrice = conversion.quantity * ingredientCost

  // Validation to ensure all required fields are provided
  const isValidForSubmit = ingredientId && conversion.satuan && toUnitId && conversion.quantity > 0

  return (
    <Drawer
      open={open}
      anchor='right'
      variant='temporary'
      onClose={handleReset}
      ModalProps={{ keepMounted: true }}
      sx={{
        '& .MuiDrawer-paper': {
          width: { xs: 350, sm: 800 },
          display: 'flex',
          flexDirection: 'column',
          height: '100%'
        }
      }}
    >
      {/* Sticky Header */}
      <Box
        sx={{
          position: 'sticky',
          top: 0,
          zIndex: 10,
          backgroundColor: 'background.paper',
          borderBottom: 1,
          borderColor: 'divider'
        }}
      >
        <div className='flex items-center justify-between plb-5 pli-6'>
          <Typography variant='h5'>Konversi Unit Bahan</Typography>
          <IconButton size='small' onClick={handleReset}>
            <i className='tabler-x text-2xl text-textPrimary' />
          </IconButton>
        </div>
        {!ingredientId && (
          <Box sx={{ px: 3, pb: 2 }}>
            <Typography variant='body2' color='error'>
              Warning: Ingredient data is required for conversion
            </Typography>
          </Box>
        )}
        {ingredientId && (
          <Box sx={{ px: 3, pb: 2 }}>
            <Typography variant='body2' color='text.secondary'>
              Converting for: {data?.name || `Ingredient ${ingredientId}`}
            </Typography>
            {ingredientCost > 0 && (
              <Typography variant='body2' color='text.secondary'>
                Base cost per {units?.data.find(u => u.id === toUnitId)?.name || 'unit'}: Rp{' '}
                {formatNumber(ingredientCost)}
              </Typography>
            )}
          </Box>
        )}
      </Box>

      {/* Scrollable Content */}
      <Box sx={{ flex: 1, overflowY: 'auto' }}>
        <form id='unit-conversion-form' onSubmit={handleSubmit(onSubmit)}>
          <div className='flex flex-col gap-6 p-6'>
            {/* Header Kolom */}
            <Grid container spacing={2} alignItems='center' className='bg-gray-50 p-3 rounded-lg'>
              <Grid size={2}>
                <Typography variant='body2' fontWeight='medium'>
                  From Unit
                </Typography>
              </Grid>
              <Grid size={1} className='text-center'>
                <Typography variant='body2' fontWeight='medium'>
                  =
                </Typography>
              </Grid>
              <Grid size={1.5}>
                <Typography variant='body2' fontWeight='medium'>
                  Factor
                </Typography>
              </Grid>
              <Grid size={1.5}>
                <Typography variant='body2' fontWeight='medium'>
                  To Unit
                </Typography>
              </Grid>
              <Grid size={2.5}>
                <Typography variant='body2' fontWeight='medium'>
                  Harga Beli
                </Typography>
              </Grid>
              <Grid size={2.5}>
                <Typography variant='body2' fontWeight='medium'>
                  Harga Jual
                </Typography>
              </Grid>
              <Grid size={1}>
                <Typography variant='body2' fontWeight='medium'>
                  Default
                </Typography>
              </Grid>
            </Grid>

            {/* Form Input Row */}
            <Grid container spacing={2} alignItems='center' className='py-2'>
              {/* From Unit (Satuan) */}
              <Grid size={2}>
                <div className='flex items-center gap-2'>
                  <Typography variant='body2' fontWeight='medium'>
                    1
                  </Typography>
                  <Controller
                    name='satuan'
                    control={control}
                    rules={{ required: 'From unit wajib dipilih' }}
                    render={({ field }) => (
                      <CustomTextField
                        {...field}
                        select
                        fullWidth
                        size='small'
                        error={!!errors.satuan}
                        onChange={e => {
                          field.onChange(e.target.value)
                          handleChangeConversion('satuan', e.target.value)
                        }}
                      >
                        {units?.data
                          .filter(unit => unit.id !== toUnitId) // Prevent selecting same unit as target
                          .map(unit => (
                            <MenuItem key={unit.id} value={unit.id}>
                              {unit.name}
                            </MenuItem>
                          )) ?? []}
                      </CustomTextField>
                    )}
                  />
                </div>
                {errors.satuan && (
                  <Typography variant='caption' color='error' className='mt-1'>
                    {errors.satuan.message}
                  </Typography>
                )}
              </Grid>

              {/* Tanda sama dengan */}
              <Grid size={1} className='text-center'>
                <Typography variant='h6'>=</Typography>
              </Grid>

              {/* Conversion Factor (Quantity) */}
              <Grid size={1.5}>
                <Controller
                  name='quantity'
                  control={control}
                  rules={{
                    required: 'Conversion factor wajib diisi',
                    min: { value: 0.01, message: 'Minimal 0.01' }
                  }}
                  render={({ field }) => (
                    <CustomTextField
                      {...field}
                      fullWidth
                      size='small'
                      type='number'
                      error={!!errors.quantity}
                      onChange={e => {
                        const value = parseFloat(e.target.value) || 0
                        field.onChange(value)
                        handleChangeConversion('quantity', value)
                      }}
                    />
                  )}
                />
                {errors.quantity && (
                  <Typography variant='caption' color='error' className='mt-1'>
                    {errors.quantity.message}
                  </Typography>
                )}
              </Grid>

              {/* To Unit - Disabled because it comes from data */}
              <Grid size={1.5}>
                <CustomTextField
                  select
                  fullWidth
                  size='small'
                  value={toUnitId}
                  disabled
                  InputProps={{
                    sx: { backgroundColor: 'grey.100' }
                  }}
                >
                  {units?.data.map(unit => (
                    <MenuItem key={unit.id} value={unit.id}>
                      {unit.name}
                    </MenuItem>
                  )) ?? []}
                </CustomTextField>
              </Grid>

              {/* Harga Beli - Calculated as factor * ingredientCost */}
              <Grid size={2.5}>
                <CustomTextField
                  fullWidth
                  size='small'
                  value={formatNumber(totalPurchasePrice)}
                  disabled
                  InputProps={{
                    sx: { backgroundColor: 'grey.100' }
                  }}
                  placeholder='Calculated purchase price'
                />
              </Grid>

              {/* Harga Jual */}
              <Grid size={2.5}>
                <Controller
                  name='hargaJual'
                  control={control}
                  rules={{
                    min: { value: 0, message: 'Tidak boleh negatif' }
                  }}
                  render={({ field }) => (
                    <CustomTextField
                      fullWidth
                      size='small'
                      error={!!errors.hargaJual}
                      value={formatNumber(conversion.hargaJual)}
                      onChange={e => {
                        const value = parseNumber(e.target.value)
                        field.onChange(value)
                        handleChangeConversion('hargaJual', value)
                      }}
                      placeholder='Optional'
                    />
                  )}
                />
                {errors.hargaJual && (
                  <Typography variant='caption' color='error' className='mt-1'>
                    {errors.hargaJual.message}
                  </Typography>
                )}
              </Grid>

              {/* Default Star */}
              <Grid size={1} className='text-center'>
                <IconButton
                  size='small'
                  onClick={() => handleChangeConversion('isDefault', !conversion.isDefault)}
                  sx={{
                    color: conversion.isDefault ? 'warning.main' : 'grey.400'
                  }}
                >
                  <i className={conversion.isDefault ? 'tabler-star-filled' : 'tabler-star'} />
                </IconButton>
              </Grid>
            </Grid>

            {/* Conversion Preview */}
            {conversion.quantity > 0 && conversion.satuan && toUnitId && (
              <Box className='bg-green-50 p-4 rounded-lg border-l-4 border-green-500'>
                <Typography variant='body2' fontWeight='medium' className='mb-2'>
                  Conversion Preview:
                </Typography>
                <Typography variant='body2' className='mb-1'>
                  <strong>1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'Unit'}</strong> ={' '}
                  <strong>
                    {conversion.quantity} {units?.data.find(u => u.id === toUnitId)?.name || 'Unit'}
                  </strong>
                </Typography>
                <Typography variant='caption' color='text.secondary'>
                  Conversion Factor: {conversion.quantity}
                </Typography>
              </Box>
            )}

            {/* Price Summary */}
            {conversion.quantity > 0 && (ingredientCost > 0 || conversion.hargaJual > 0) && (
              <Box className='bg-blue-50 p-4 rounded-lg border-l-4 border-blue-500'>
                <Typography variant='body2' fontWeight='medium' className='mb-2'>
                  Price Summary:
                </Typography>
                {ingredientCost > 0 && (
                  <>
                    <Typography variant='body2'>
                      Total Purchase Price (1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'From Unit'}):
                      Rp {formatNumber(totalPurchasePrice)}
                    </Typography>
                    <Typography variant='body2'>
                      Unit Cost per {units?.data.find(u => u.id === toUnitId)?.name || 'To Unit'}: Rp{' '}
                      {formatNumber(ingredientCost)}
                    </Typography>
                  </>
                )}
                {conversion.hargaJual > 0 && (
                  <>
                    <Typography variant='body2'>
                      Total Selling Price (1 {units?.data.find(u => u.id === conversion.satuan)?.name || 'From Unit'}):
                      Rp {formatNumber(conversion.hargaJual)}
                    </Typography>
                    <Typography variant='body2'>
                      Unit Selling Price per {units?.data.find(u => u.id === toUnitId)?.name || 'To Unit'}: Rp{' '}
                      {formatNumber(Math.round(conversion.hargaJual / conversion.quantity))}
                    </Typography>
                  </>
                )}
                {ingredientCost > 0 && conversion.hargaJual > 0 && (
                  <Typography variant='body2' className='mt-2 text-blue-700'>
                    Total Margin: Rp {formatNumber(conversion.hargaJual - totalPurchasePrice)} (
                    {totalPurchasePrice > 0
                      ? (((conversion.hargaJual - totalPurchasePrice) / totalPurchasePrice) * 100).toFixed(1)
                      : 0}
                    %)
                  </Typography>
                )}
              </Box>
            )}
          </div>
        </form>
      </Box>

      {/* Sticky Footer */}
      <Box
        sx={{
          position: 'sticky',
          bottom: 0,
          zIndex: 10,
          backgroundColor: 'background.paper',
          borderTop: 1,
          borderColor: 'divider',
          p: 3
        }}
      >
        <div className='flex items-center gap-4'>
          <Button variant='contained' type='submit' form='unit-conversion-form' disabled={!isValidForSubmit}>
            Simpan Konversi
          </Button>
          <Button variant='tonal' color='error' onClick={handleReset}>
            Batal
          </Button>
        </div>
        {!isValidForSubmit && (
          <Typography variant='caption' color='error' className='mt-2'>
            Please fill in all required fields: {!ingredientId && 'Ingredient Data, '}
            {!conversion.satuan && 'From Unit, '}
            {!toUnitId && 'To Unit (from ingredient data), '}
            {conversion.quantity <= 0 && 'Conversion Factor'}
          </Typography>
        )}
      </Box>
    </Drawer>
  )
}

export default IngedientUnitConversionDrawer
