import Iconify from '@/components/Iconify';
import { Divider, InputAdornment, Paper, Stack, TextField, Typography } from '@mui/material';
import { useEffect, useState } from 'react';

export default function ClaimItems({ items, setItems }) {

  const handleChangeBiayaDiajukan = (event, itemIndex: Number) => {
    setItems(items.map((item, index) => {
      if (index == itemIndex) {
        return {...item, biaya_diajukan : event.target.value}
      } else {
        return item;
      }
    }))
  }

  const handleChangeBiayaDisetujui = (event, itemIndex: Number) => {
    setItems(items.map((item, index) => {
      if (index == itemIndex) {
        return {...item, biaya_disetujui : event.target.value}
      } else {
        return item;
      }
    }))
  }

  const calculateBiayaDitolak = (biayaDiajukan: Number | null, biayaDisetujui: Number | null) => {
    return (biayaDiajukan ? biayaDiajukan : 0) - (biayaDisetujui ? biayaDisetujui : 0)
  }

  const handleDeleteItem = (itemIndex: Number) => {
    setItems(items.filter((item, index) => index != itemIndex))
  }

  return (
    <Stack spacing={2}>
      {items.length > 0 ? (
        items.map((item, index) => (
          <Paper variant="outlined" sx={{ background: 'white', p: 2 }} key={index}>
            <Stack direction="row" justifyContent="space-between">
              <Typography>#{index+1} ({item.code}) {item.description}</Typography>
              <Iconify icon="eva:trash-fill" color="red" onClick={() => {handleDeleteItem(index)}}></Iconify>
            </Stack>
            <Stack
              direction="row"
              justifyContent="space-evenly"
              divider={<Divider orientation="vertical" flexItem />}
            >
              <TextField label="Biaya Diajukan" variant="standard" fullWidth type="number" value={item.biaya_diajukan ?? 0} onChange={(event) => {handleChangeBiayaDiajukan(event, index)}}>
                <InputAdornment position="start">IDR</InputAdornment>
                {/* <InputMask mask="(0)999 999 99 99" maskChar=" " /> */}
              </TextField>
              <TextField label="Biaya Disetujui" variant="standard" fullWidth type="number" value={item.biaya_disetujui ?? 0} onChange={(event) => {handleChangeBiayaDisetujui(event, index)}}>
                <InputAdornment position="start">IDR</InputAdornment>
                {/* <InputMask mask="(0)999 999 99 99" maskChar=" " /> */}
              </TextField>
              <TextField label="Biaya Ditolak" variant="standard" fullWidth type="number" value={calculateBiayaDitolak(item.biaya_diajukan, item.biaya_disetujui)}>
                <InputAdornment position="start">IDR</InputAdornment>
                {/* <InputMask mask="(0)999 999 99 99" maskChar=" " /> */}
              </TextField>
            </Stack>
          </Paper>
        ))
      ) : (
        <Typography>No Benefit Item</Typography>
      )}
    </Stack>
  );
}
