'use client'

import React from 'react'
import { Button, Typography } from '@mui/material'
import Grid from '@mui/material/Grid2'
import CustomAutocomplete from '@/@core/components/mui/Autocomplete'
import CustomTextField from '@/@core/components/mui/TextField'
import { IngredientItem, PurchaseOrderFormData } from '@/types/apps/purchaseOrderTypes'

interface PurchaseIngredientsTableProps {
  formData: PurchaseOrderFormData
  handleIngredientChange: (index: number, field: keyof IngredientItem, value: any) => void
  addIngredientItem: () => void
  removeIngredientItem: (index: number) => void
}

const PurchaseIngredientsTable: React.FC<PurchaseIngredientsTableProps> = ({
  formData,
  handleIngredientChange,
  addIngredientItem,
  removeIngredientItem
}) => {
  const ingredientOptions = [
    { label: 'Tepung Terigu Premium', value: 'tepung_terigu_premium' },
    { label: 'Gula Pasir Halus', value: 'gula_pasir_halus' },
    { label: 'Mentega Unsalted', value: 'mentega_unsalted' },
    { label: 'Telur Ayam Grade A', value: 'telur_ayam_grade_a' },
    { label: 'Vanilla Extract', value: 'vanilla_extract' },
    { label: 'Coklat Chips', value: 'coklat_chips' }
  ]

  const satuanOptions = [
    { label: 'KG', value: 'kg' },
    { label: 'GRAM', value: 'gram' },
    { label: 'LITER', value: 'liter' },
    { label: 'ML', value: 'ml' },
    { label: 'PCS', value: 'pcs' },
    { label: 'PACK', value: 'pack' }
  ]

  const pajakOptions = [
    { label: 'PPN 11%', value: 'ppn_11' },
    { label: 'PPN 0%', value: 'ppn_0' },
    { label: 'Bebas Pajak', value: 'tax_free' }
  ]

  const wasteOptions = [
    { label: '2%', value: '2' },
    { label: '5%', value: '5' },
    { label: '10%', value: '10' },
    { label: '15%', value: '15' },
    { label: 'Custom', value: 'custom' }
  ]

  return (
    <Grid size={12} sx={{ mt: 4 }}>
      <Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
        Bahan Baku / Ingredients
      </Typography>

      {/* Table Header */}
      <Grid container spacing={1} sx={{ mb: 2, px: 1 }}>
        <Grid size={1.8}>
          <Typography variant='subtitle2' fontWeight={600}>
            Bahan Baku
          </Typography>
        </Grid>
        <Grid size={1.8}>
          <Typography variant='subtitle2' fontWeight={600}>
            Deskripsi
          </Typography>
        </Grid>
        <Grid size={1}>
          <Typography variant='subtitle2' fontWeight={600}>
            Kuantitas
          </Typography>
        </Grid>
        <Grid size={1.2}>
          <Typography variant='subtitle2' fontWeight={600}>
            Satuan
          </Typography>
        </Grid>
        <Grid size={1}>
          <Typography variant='subtitle2' fontWeight={600}>
            Discount
          </Typography>
        </Grid>
        <Grid size={1.2}>
          <Typography variant='subtitle2' fontWeight={600}>
            Harga
          </Typography>
        </Grid>
        <Grid size={1.2}>
          <Typography variant='subtitle2' fontWeight={600}>
            Pajak
          </Typography>
        </Grid>
        <Grid size={1.2}>
          <Typography variant='subtitle2' fontWeight={600}>
            Waste
          </Typography>
        </Grid>
        <Grid size={1}>
          <Typography variant='subtitle2' fontWeight={600}>
            Total
          </Typography>
        </Grid>
        <Grid size={0.6}></Grid>
      </Grid>

      {/* Ingredient Items */}
      {formData.ingredientItems.map((item: IngredientItem, index: number) => (
        <Grid container spacing={1} key={item.id} sx={{ mb: 2, alignItems: 'center' }}>
          <Grid size={1.8}>
            <CustomAutocomplete
              fullWidth
              size='small'
              options={ingredientOptions}
              value={item.ingredient}
              onChange={(event, newValue) => handleIngredientChange(index, 'ingredient', newValue)}
              renderInput={params => (
                <CustomTextField {...params} placeholder='Pilih Bahan Baku' size='small' fullWidth />
              )}
            />
          </Grid>
          <Grid size={1.8}>
            <CustomTextField
              fullWidth
              size='small'
              value={item.deskripsi}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleIngredientChange(index, 'deskripsi', e.target.value)
              }
              placeholder='Deskripsi'
            />
          </Grid>
          <Grid size={1}>
            <CustomTextField
              fullWidth
              size='small'
              type='number'
              value={item.kuantitas}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleIngredientChange(index, 'kuantitas', parseInt(e.target.value) || 1)
              }
              inputProps={{ min: 1 }}
            />
          </Grid>
          <Grid size={1.2}>
            <CustomAutocomplete
              fullWidth
              size='small'
              options={satuanOptions}
              value={item.satuan}
              onChange={(event, newValue) => handleIngredientChange(index, 'satuan', newValue)}
              renderInput={params => <CustomTextField {...params} placeholder='Pilih...' size='small' fullWidth />}
            />
          </Grid>
          <Grid size={1}>
            <CustomTextField
              fullWidth
              size='small'
              value={item.discount}
              onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                handleIngredientChange(index, 'discount', e.target.value)
              }
              placeholder='0%'
            />
          </Grid>
          <Grid size={1.2}>
            <CustomTextField
              fullWidth
              size='small'
              type='number'
              value={item.harga === 0 ? '' : item.harga?.toString() || ''} // Ubah ini: 0 jadi empty string
              onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                const value = e.target.value

                if (value === '') {
                  // Jika kosong, set ke null atau undefined, bukan 0
                  handleIngredientChange(index, 'harga', null) // atau undefined
                  return
                }

                const numericValue = parseFloat(value)
                handleIngredientChange(index, 'harga', isNaN(numericValue) ? 0 : numericValue)
              }}
              inputProps={{ min: 0, step: 'any' }}
              placeholder='0'
            />
          </Grid>
          <Grid size={1.2}>
            <CustomAutocomplete
              fullWidth
              size='small'
              options={pajakOptions}
              value={item.pajak}
              onChange={(event, newValue) => handleIngredientChange(index, 'pajak', newValue)}
              renderInput={params => <CustomTextField {...params} placeholder='...' size='small' fullWidth />}
            />
          </Grid>
          <Grid size={1.2}>
            <CustomAutocomplete
              fullWidth
              size='small'
              options={wasteOptions}
              value={item.waste}
              onChange={(event, newValue) => handleIngredientChange(index, 'waste', newValue)}
              renderInput={params => <CustomTextField {...params} placeholder='...' size='small' fullWidth />}
            />
          </Grid>
          <Grid size={1}>
            <CustomTextField fullWidth size='small' value={item.total} InputProps={{ readOnly: true }} />
          </Grid>
          <Grid size={0.6}>
            <Button
              variant='outlined'
              color='error'
              size='small'
              onClick={() => removeIngredientItem(index)}
              sx={{ minWidth: 'auto', p: 1 }}
            >
              <i className='tabler-trash' />
            </Button>
          </Grid>
        </Grid>
      ))}

      {/* Add New Item Button */}
      <Grid container spacing={1}>
        <Grid size={12}>
          <Button
            variant='outlined'
            onClick={addIngredientItem}
            sx={{
              textTransform: 'none',
              color: 'primary.main',
              borderColor: 'primary.main'
            }}
          >
            + Tambah bahan baku
          </Button>
        </Grid>
      </Grid>
    </Grid>
  )
}

export default PurchaseIngredientsTable
