import MuiDialog from "@/components/MuiDialog";
import { Button, Checkbox, Typography } from "@mui/material";
import { Paper } from "@mui/material";
import { Stack } from '@mui/material';
import { useState } from "react";


export default function DialogMemberBenefit({member, setOpenDialog, openDialog, onSubmit}) {

    const benefits = member?.current_plan?.benefits ?? [];
    const [selectedBenefits, setSelectedBenefits] = useState([]);

    const toggleBenefit = (benefit) => {
        if (selectedBenefits.includes(benefit)) {
            console.log('removing', benefit)
            setSelectedBenefits(selectedBenefits.filter((throughBenefit) => benefit.id != throughBenefit.id))
        } else {
            console.log('adding', benefit)
            setSelectedBenefits([...selectedBenefits, benefit])
        }
    }

    const handleSubmit = () => {
        onSubmit(selectedBenefits);
        console.log ('submitting')
        setOpenDialog(false);
        setSelectedBenefits([]);
    }

    const getContent = () => (
        <Stack spacing={1} marginTop={2}>
            { benefits.map((benefit, index) => (

                <Paper sx={{ background: 'white', marginTop: 2, p: 2 }} key={index}>
                <Stack direction="row" justifyContent="space-between" alignItems='center'>
                    <Stack>
                    <Typography variant="body1" fontWeight={600}>{benefit.description}</Typography>
                    <Typography variant="body2">{benefit.code}</Typography>
                    </Stack>
                    <Checkbox checked={selectedBenefits.includes(benefit)} onClick={() => { toggleBenefit(benefit) }}></Checkbox>
                </Stack>
                </Paper>
            ))}

            <Button variant="contained" onClick={() => {handleSubmit()}}>Tambah</Button>
        </Stack>
      );


    return (
        <MuiDialog
          title={{name: "Add Member Benefit"}}
          openDialog={openDialog}
          setOpenDialog={setOpenDialog}
          content={getContent()}
          maxWidth="xl"
        />
      );
}