'use client'

import React from 'react'
import {
  Button,
  Typography,
  IconButton,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper
} 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={{ xs: 12 }} sx={{ mt: 4 }}>
      <Typography variant='h6' sx={{ mb: 2, fontWeight: 600 }}>
        Bahan Baku / Ingredients
      </Typography>

      <TableContainer component={Paper} variant='outlined'>
        <Table>
          <TableHead>
            <TableRow sx={{ backgroundColor: 'grey.50' }}>
              <TableCell sx={{ fontWeight: 'bold', minWidth: 180 }}>Bahan Baku</TableCell>
              <TableCell sx={{ fontWeight: 'bold', minWidth: 150 }}>Deskripsi</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 100 }}>Kuantitas</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 120 }}>Satuan</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 100 }}>Discount</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 120 }}>Harga</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 120 }}>Pajak</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 120 }}>Waste</TableCell>
              <TableCell sx={{ fontWeight: 'bold', width: 100, textAlign: 'right' }}>Total</TableCell>
              <TableCell sx={{ width: 50 }}></TableCell>
            </TableRow>
          </TableHead>
          <TableBody>
            {formData.ingredientItems.map((item: IngredientItem, index: number) => (
              <TableRow key={item.id}>
                <TableCell>
                  <CustomAutocomplete
                    size='small'
                    options={ingredientOptions}
                    value={item.ingredient}
                    onChange={(event, newValue) => handleIngredientChange(index, 'ingredient', newValue)}
                    renderInput={params => <CustomTextField {...params} placeholder='Pilih Bahan Baku' />}
                  />
                </TableCell>
                <TableCell>
                  <CustomTextField
                    fullWidth
                    size='small'
                    value={item.deskripsi}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                      handleIngredientChange(index, 'deskripsi', e.target.value)
                    }
                    placeholder='Deskripsi'
                  />
                </TableCell>
                <TableCell>
                  <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 }}
                  />
                </TableCell>
                <TableCell>
                  <CustomAutocomplete
                    size='small'
                    options={satuanOptions}
                    value={item.satuan}
                    onChange={(event, newValue) => handleIngredientChange(index, 'satuan', newValue)}
                    renderInput={params => <CustomTextField {...params} placeholder='Pilih...' />}
                  />
                </TableCell>
                <TableCell>
                  <CustomTextField
                    fullWidth
                    size='small'
                    value={item.discount}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
                      handleIngredientChange(index, 'discount', e.target.value)
                    }
                    placeholder='0%'
                  />
                </TableCell>
                <TableCell>
                  <CustomTextField
                    fullWidth
                    size='small'
                    type='number'
                    value={item.harga === 0 ? '' : item.harga?.toString() || ''}
                    onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                      const value = e.target.value

                      if (value === '') {
                        handleIngredientChange(index, 'harga', null)
                        return
                      }

                      const numericValue = parseFloat(value)
                      handleIngredientChange(index, 'harga', isNaN(numericValue) ? 0 : numericValue)
                    }}
                    inputProps={{ min: 0, step: 'any' }}
                    placeholder='0'
                  />
                </TableCell>
                <TableCell>
                  <CustomAutocomplete
                    size='small'
                    options={pajakOptions}
                    value={item.pajak}
                    onChange={(event, newValue) => handleIngredientChange(index, 'pajak', newValue)}
                    renderInput={params => <CustomTextField {...params} placeholder='...' />}
                  />
                </TableCell>
                <TableCell>
                  <CustomAutocomplete
                    size='small'
                    options={wasteOptions}
                    value={item.waste}
                    onChange={(event, newValue) => handleIngredientChange(index, 'waste', newValue)}
                    renderInput={params => <CustomTextField {...params} placeholder='...' />}
                  />
                </TableCell>
                <TableCell>
                  <CustomTextField
                    fullWidth
                    size='small'
                    value={item.total}
                    InputProps={{ readOnly: true }}
                    sx={{
                      '& .MuiInputBase-input': {
                        textAlign: 'right'
                      }
                    }}
                  />
                </TableCell>
                <TableCell>
                  <IconButton
                    size='small'
                    color='error'
                    onClick={() => removeIngredientItem(index)}
                    disabled={formData.ingredientItems.length === 1}
                  >
                    <i className='tabler-trash' />
                  </IconButton>
                </TableCell>
              </TableRow>
            ))}
          </TableBody>
        </Table>
      </TableContainer>

      {/* Add New Item Button */}
      <Button
        startIcon={<i className='tabler-plus' />}
        onClick={addIngredientItem}
        variant='outlined'
        size='small'
        sx={{ mt: 1 }}
      >
        Tambah bahan baku
      </Button>
    </Grid>
  )
}

export default PurchaseIngredientsTable
