import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';

import MuiDialog from "@/components/MuiDialog";
import { Checkbox, Typography, FormControl, Card, Grid, DialogActions } from "@mui/material";
import { Paper } from "@mui/material";
import { Stack } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { DetailFinalLogType } from "../Model/Types";
import { BenefitConfigurationListType } from "../Model/Types";
import { InputLabel, Select, FormHelperText } from "@mui/material";
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Button from '@mui/material/Button';
import { fNumber } from "@/utils/formatNumber";
import palette from "@/theme/palette";
import { Box } from "@mui/material";
import { FormProvider, RHFTextField } from "@/components/hook-form";
import RHFTextFieldMoney from '@/components/hook-form/v2/RHFTextFieldMoney';

import { useFieldArray, useForm } from 'react-hook-form';
import { LoadingButton } from '@mui/lab';
import { postAddBenefit } from '../Model/Functions';
import { useNavigate } from 'react-router';
import { description } from '@/_mock/text';


type DialogConfirmationType = {
    openDialog: boolean;
    setOpenDialog: any;
    onSubmit?: void;
    requestLog: DetailFinalLogType|undefined; 
}

type BenefitSelected = {
    id: number,
    description: string,
    benefit_id: number,
}



export default function DialogBenefit({requestLog, setOpenDialog, openDialog } : DialogConfirmationType ) {

    // Add Benefit 
    const [addBenefit, setAddBenefit] = useState(false)
    const navigate  = useNavigate()
   //Benefit Name
    const [valBenefitNames, setValBenefitNames] = useState([]);
    const [valBenefitNameError, setValBenefitNameError] = useState('');
    const benefitNameData  = requestLog?.benefit;
    const [benefitSelected, setBenefitSelected] = useState<BenefitSelected[]>([]);

    const handleConditionChangeService = (event) => {
        const selectedItem = event.target.value;

        if (valBenefitNames.includes(selectedItem)) {
            // Item is already selected, remove it
            setValBenefitNames(valBenefitNames.filter(item => item !== selectedItem));
        } else {
            // Item is not selected, add it
            setValBenefitNames([...valBenefitNames, selectedItem]);
        }
    };

    useEffect(() => {
        const datax: any[] = []

        valBenefitNames.map((data) => {
            benefitNameData?.map((row) => {
                if(row.id == data) {
                    datax.push(row)
                }
            })
        })

        // for data information
        let temp = datax.map((item, indx) => {
            return {
                benefit_id: item.id,
                description: item.description,
                request_log_id: requestLog?.id,
                amount_incurred: 0,
                amount_approved: 0,
                amount_not_approved: 0,
                excess_paid: 0,
                keterangan: '',
            }
        })
    
        reset({benefit_data: temp})

        setBenefitSelected(datax)
        
    }, [valBenefitNames])

    const handleCloseDialogBenefit = () => {
        // setOpenDialog(false);
        setAddBenefit(false)
        setBenefitSelected([])
        setValBenefitNames([])
    }

    const handleAddDialogBenefit = () => {
        setAddBenefit(true)
    }

    const defaultValues: BenefitConfigurationListType = {
        request_log_id: requestLog?.id,
        benefit_name: '',
        amount_incurred: 0,
        amount_approved: 0,
        amount_not_approved: 0,
        excess_paid: 0,
    };

    const validationSchema = Yup.object().shape({
        benefit_data: Yup.array().of(
            Yup.object().shape({
                amount_incurred     : Yup.number().typeError('').required(''),
                amount_approved     : Yup.number().typeError('').required(''),
                amount_not_approved : Yup.number().typeError('').required(''),
                excess_paid         : Yup.number().typeError('').required(''),
            })
        )
    })

    const methods = useForm<any>({
        resolver: yupResolver(validationSchema),
        defaultValues
    });

    const {fields, append, remove} = useFieldArray({name: 'benefit_data',control: methods.control})
    
    const { handleSubmit, reset, watch, setValue, formState: { isDirty, isSubmitting, errors } } = methods;
    // Submit Form
    // =====================================
    const submitHandler = async (data: BenefitConfigurationListType) => {
    
        const response = await postAddBenefit(data);

        if (response == true) {
            reset();
            // navigate('custormer-service/final-log/detail/'+requestLog?.id);
            window.location.reload()
        }
    }

    const getContent = () => !addBenefit ? (
        <Stack spacing={2} sx={{marginTop: 2, padding: 2}} direction="column">
            <Stack direction="row" spacing={2}>
                <Stack spacing={2} sx={{width:'100%'}}>
                    <Typography variant='subtitle1'>Benefit Name*</Typography>
                    <FormControl>
                    <InputLabel htmlFor="benefit_name">
                        Benefit Name
                    </InputLabel>
                    <Select
                        id="benefit_name"
                        value={valBenefitNames}
                        fullWidth
                        label="Benefit Name"
                        error={!!valBenefitNameError}
                        onChange={(e) => {
                            setValBenefitNameError(!valBenefitNames ? 'At least one item must be selected' : '');
                        }}
                        renderValue={(selected) => selected.map(value => {
                            const selectedOption = benefitNameData?.find(option => String(option.id) === value);
                            return selectedOption ? selectedOption.description : '';
                        }).join(', ')}
                    >
                        {benefitNameData?.map((item, index) => (
                            <FormGroup key={index} sx={{ marginLeft: 2 }}>
                                <FormControlLabel
                                    control={
                                        <Checkbox
                                            checked={valBenefitNames.includes(String(item.id))}
                                            onChange={handleConditionChangeService}
                                            value={String(item.id)}
                                        />
                                    }
                                    label={item.description}
                                />
                            </FormGroup>
                        ))}
                    </Select>
                    <FormHelperText style={{ color: 'red' }}>{valBenefitNameError}</FormHelperText>
                    </FormControl>
                    </Stack>
                </Stack>
        </Stack>
      ) : 
      
      (
        <FormProvider methods={methods} onSubmit={handleSubmit(submitHandler)}>
            <Stack paddingX={2} paddingY={4}>
            {/* <Card sx={{padding:2}}> */}
                {fields?.map((item, index) => 
                (
                    <Box sx={{ marginTop:'10px', marginBottom:'10px', py: '8px', px: '12px', border:'1px solid #919EAB52', borderRadius: '6px'}}>                    
                            <Grid key={item.id} container spacing={2}>
                                <Grid item xs={12}>
                                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold'}}>
                                        {item.description}
                                    </Typography>
                                   
                                </Grid>
                                <Grid item xs={2.5}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant="subtitle1" component="div">
                                                Amount Incurred*
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <RHFTextFieldMoney 
                                                key={item.id}
                                                id='amount_incurred'
                                                name={`benefit_data.${index}.amount_incurred`}
                                                placeholder='Amount Incurred'
                                                required
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={2.5}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant="subtitle1" component="div">
                                                Amount Approved*
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <RHFTextFieldMoney
                                                // onChange={() => append({amount_approved: ''}) }
                                                id='amount_approved'
                                                key={item.id}
                                                name={`benefit_data.${index}.amount_approved`}
                                                placeholder='Amount Approved'
                                                required
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={2.5}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant="subtitle1" component="div">
                                                Amount Not Approved*
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <RHFTextFieldMoney
                                                // onChange={() => append({amount_not_approved: ''}) }
                                                id='amount_not_approved'
                                                key={item.id}
                                                name={`benefit_data.${index}.amount_not_approved`}
                                                placeholder='Amount Not Approved'
                                                required
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={2.5}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant="subtitle1" component="div">
                                                Excess Paid*
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <RHFTextFieldMoney
                                                // onChange={() => append({excess_paid: ''}) }
                                                id='excess_paid'
                                                key={item.id}
                                                name={`benefit_data.${index}.excess_paid`}
                                                placeholder='Excess Paid'
                                                required
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={2}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant="subtitle1" component="div">
                                                Keterangan*
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <RHFTextField
                                                // onChange={() => append({keterangan: ''}) }
                                                id='keterangan'
                                                key={item.id}
                                                name={`benefit_data.${index}.keterangan`}
                                                placeholder='Keterangan'
                                                required
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>
                        </Grid>
                    </Box>
                ))}

                
                {/* </Card> */}
                <DialogActions>
                    <Stack direction="row" sx={{marginTop:3}} alignItems="center" justifyContent="space-between" spacing={2}>
                        <Button variant="outlined" onClick={handleCloseDialogBenefit}><Typography>Cancel</Typography></Button>
                        <LoadingButton disabled={!addBenefit} type="submit" variant="contained" loading={isSubmitting}>
                            Save
                        </LoadingButton>
                    </Stack>
                </DialogActions>
            </Stack>
        </FormProvider>
        
      );

    const getAction = () => !addBenefit ? (
        <Stack direction="row" alignItems="center" justifyContent="space-between" spacing={2}>
            <Button variant="outlined" onClick={handleCloseDialogBenefit}><Typography>Cancel</Typography></Button>
            <Button variant="contained" onClick={handleAddDialogBenefit}><Typography>Add</Typography></Button>
        </Stack>
    ) : null;


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