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

import MuiDialog from "@/components/MuiDialog";
import { Checkbox, Typography, FormControl, Card, Grid, DialogActions, IconButton, Autocomplete } 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, useWatch } from 'react-hook-form';
import { LoadingButton } from '@mui/lab';
import { postAddBenefit } from '../Model/Functions';
import { useNavigate } from 'react-router';
import { description } from '@/_mock/text';
import { Delete } from '@mui/icons-material';
import { TextField } from '@mui/material';
import RHFAutocomplete from '@/components/hook-form/RHFAutocomplete';


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

type BenefitSelected = {
    id: number,
    description: string,
    benefit_id: number,
    family_plan: string,
    family_plan_plans: string,
    limit_amount: number,
    limit_amount_plan: number,
    max_frequency_period: number,
}



export default function DialogBenefit({requestLog, setOpenDialog, openDialog, claimInput = false } : 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]);
        }
    };

    const reasons = [
        { value: 'Wrong Setting', label: 'Wrong Setting' },
        { value: 'Hospital Request', label: 'Hospital Request' }
    ];

    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: '',
                reason: null
            }
        })
    
        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,
        reason: null
    };

    const validationSchema = Yup.object().shape({
        benefit_data: Yup.array().of(
            claimInput ? 
            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(''),
                // reason              : Yup.string().required(''),
            }) : 
            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,
        reValidateMode: "onChange"
    });

    let width = claimInput ? 2 : 2.36;

    const {fields, append, remove} = useFieldArray({name: 'benefit_data',control: methods.control,});
    const { handleSubmit, reset, watch, setValue, setError, clearErrors, formState: { isDirty, isSubmitting, errors,isValid } } = methods
    
    const errorsExist = errors ? Object.keys(errors).length > 0 : false;
    // Calculate 
    const benefitData = watch('benefit_data');
    const totalAll = () => {
        let totalAmountIncurred = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
            return accumulator + (item.amount_incurred || 0);
        }, 0);
        let totalAmountApproved = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
            return accumulator + (item.amount_approved || 0);
        }, 0);
        let totalAmountNotApproved = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
            return accumulator + (item.amount_not_approved || 0);
        }, 0);
        let totalExcessPaid = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
            return accumulator + (item.excess_paid || 0);
        }, 0);

        benefitData?.map((item, index) => {
            totalAmountIncurred += parseFloat(item.amount_incurred);
            totalAmountApproved += parseFloat(item.amount_approved);
            totalAmountNotApproved += parseFloat(item.amount_not_approved);
            totalExcessPaid += parseFloat(item.excess_paid);    
        });

        return {
            totalAmountIncurred,
            totalAmountApproved,
            totalAmountNotApproved,
            totalExcessPaid
        }
    }

    const handleOnChangeNominal = (key) => {
        if (benefitSelected[key].family_plan == 'S' || benefitSelected[key].family_plan == 'F'){
            if (requestLog?.member_usage_benefit && benefitSelected[key] && benefitData[key]) {
                let limitAmount = Number(benefitSelected[key].limit_amount) || 0;
                let limitAmountPlan = Number(benefitSelected[key].limit_amount_plan) || 0;
                // Periksa apakah limitAmount Benefit lebih besar dari realTimeUsage
                if (limitAmountPlan != 999999999){
                    let realTimeUsage = 0;
                    let value = 0;
                    for (let key in requestLog?.member_usage_benefit) {
                        if (requestLog?.member_usage_benefit.hasOwnProperty(key)) {
                            let value = requestLog?.member_usage_benefit[key];
                            // Menggunakan parseFloat() untuk mengonversi nilai menjadi angka
                            let numericValue = parseFloat(value);
                            // Memeriksa apakah numericValue adalah angka yang valid
                            if (!isNaN(numericValue)) {
                                realTimeUsage += numericValue;
                            }
                        }
                    }
                    // console.log(benefitData, 'test')
                    let totalAmount = 0;

                    for (let key in benefitData) {
                        // Menambahkan nilai amount_approved ke totalAmount
                        totalAmount += Number(benefitData[key].amount_approved);
                    }
                    
                    // Hitung penggunaan waktu nyata
                    realTimeUsage += totalAmount;
                    console.log(realTimeUsage, 'test')
                    if (limitAmountPlan < realTimeUsage) {
                        setError(`benefit_data.${key}.amount_approved`, { message: `Total Amount Approve sudah melebihi limit ${ fNumber(limitAmountPlan) } , silakan isikan di Amount Excess` });
                    } else if (totalAll().totalAmountApproved > totalAll().totalAmountIncurred) {
                        setError(`benefit_data.${key}.amount_approved`, { message: 'Total Amount Approve tidak boleh lebih dari Total Amount Incurred' });
                    } else {
                        clearErrors(`benefit_data.${key}.amount_approved`);
                    }
                } else if (limitAmount != 999999999) { // Periksa apakah limitAmount Benefit lebih besar dari realTimeUsage
                     // Konversi nilai ke angka dengan aman
                    let memberUsage = Number(requestLog.member_usage_benefit[benefitSelected[key].id]) || 0;
                    let amountApproved = Number(benefitData[key].amount_approved) || 0;
                    // Hitung penggunaan waktu nyata
                    let realTimeUsage = memberUsage + amountApproved;

                    if (limitAmount < realTimeUsage) {
                        setError(`benefit_data.${key}.amount_approved`, { message: `Total Amount Approve sudah melebihi limit ${ fNumber(limitAmount) } , silakan isikan di Amount Excess` });
                    } else if (totalAll().totalAmountApproved > totalAll().totalAmountIncurred) {
                        setError(`benefit_data.${key}.amount_approved`, { message: 'Total Amount Approve tidak boleh lebih dari Total Amount Incurred' });
                    } else {
                        clearErrors(`benefit_data.${key}.amount_approved`);
                    }
                } else {
                    if (totalAll().totalAmountApproved > totalAll().totalAmountIncurred) {
                        setError(`benefit_data.${key}.amount_approved`, { message: 'Total Amount Approve tidak boleh lebih dari Total Amount Incurred' });
                    } else {
                        clearErrors(`benefit_data.${key}.amount_approved`);
                    }
                }

                if (totalAll().totalAmountApproved + totalAll().totalAmountNotApproved === totalAll().totalAmountIncurred) {
                    clearErrors(`benefit_data.${key}.excess_paid`);
                } else {
                    setError(`benefit_data.${key}.excess_paid`, { message: 'Total Amount Excess tidak sama dengan Total Amount Incurred' });
                }
            }
        } else {
            if (totalAll().totalAmountApproved > totalAll().totalAmountIncurred){
                setError(`benefit_data.${key}.amount_approved`, {message: 'Amount Approve tidak boleh lebih dari Amount Incurred'});
            } else {
                clearErrors(`benefit_data.${key}.amount_approved`);
            }
        }
    }

    const handleOnChangeNotApprove = (key, value) => {
        setValue(`benefit_data.${key}.excess_paid`, value);
        if (totalAll().totalAmountApproved + totalAll().totalAmountNotApproved === totalAll().totalAmountIncurred) {
            clearErrors(`benefit_data.${key}.excess_paid`);
        } else {
            setError(`benefit_data.${key}.excess_paid`, { message: 'Total Amount Excess tidak sama dengan Total Amount Incurred' });
        }
    };

    // Submit Form
    // =====================================
    const submitHandler = async (data: BenefitConfigurationListType) => {
        const mapData = data.benefit_data.map((item) => ({
            ...item,
            reason: item.reason ? item.reason.value : null
        }));
        
        const newData = {
            ...data,
            benefit_data: mapData
        };
        
        const response = await postAddBenefit(newData);

        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} alignItems="center">
                                <Grid item xs={12}>
                                    <Typography variant="subtitle1" sx={{ fontWeight: 'bold'}}>
                                        {item.description}
                                    </Typography>
                                   
                                </Grid>
                                <Grid item xs={width}>
                                    <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
                                                onChange={(event) => {
                                                    setValue(`benefit_data.${index}.amount_incurred`, event.target.value)
                                                    handleOnChangeNominal(index)}
                                                }
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={width}>
                                    <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
                                                onChange={(event) => {
                                                    setValue(`benefit_data.${index}.amount_approved`, event.target.value)
                                                    handleOnChangeNominal(index)}
                                                }
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={width}>
                                    <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
                                                onChange={(event) => {
                                                    setValue(`benefit_data.${index}.amount_not_approved`, event.target.value)
                                                    handleOnChangeNotApprove(index, event.target.value)}
                                                }
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>

                                <Grid item xs={width}>
                                    <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'
                                            />
                                        </Grid>
                                    </Grid>
                                </Grid>
                                {claimInput ? (
                                    <Grid item xs={1.4}>
                                        <Grid container spacing={2}>
                                            <Grid item xs={12}>
                                                <Typography variant="subtitle1" component="div">
                                                    Reason*
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                            <Autocomplete
                                                options={reasons}
                                                getOptionLabel={(option) => option.label}
                                                fullWidth
                                                value={benefitData[index]?.reason} // Use find to match the default value
                                                onChange={(event, newValue) => {
                                                    // Update the value in the form data
                                                    setValue(`benefit_data.${index}.reason`, newValue);
                                                }}
                                                renderInput={(params) => (
                                                    <TextField
                                                        {...params}
                                                        label="Reason"
                                                        variant="outlined"
                                                        required
                                                    />
                                                )}
                                            />
                                            </Grid>

                                        </Grid>
                                    </Grid>
                                ) : null}
                                { fields.length > 1 ? (
                                    <Grid item xs={0} sx={{ textAlign: 'center' }}>
                                        <IconButton size='large' color='error' onClick={() => remove(index)}>
                                            <Delete />
                                        </IconButton>
                                    </Grid>
                                ) : null }
                        </Grid>
                    </Box>
                ))}

                <br/>
                <hr/>
                <br/>
                <Grid container spacing={2}>
                    <Grid item xs={12}>
                        <Grid container spacing={2}>
                            <Grid item xs={6}>
                                <Typography variant="body2" sx={{ fontWeight: 'bold'}}>
                                    Total Benefit
                                </Typography>
                            </Grid>
                            
                        </Grid>
                    </Grid>
                    <Grid item xs={12}>
                        <Box sx={{ py: '8px', px: '12px', background: palette.light.grey[50012], borderRadius: '6px'}}>
                            <Grid container spacing={1} alignItems={'end'}>
                                {/* Amount Incurred */}
                                <Grid item xs={width}>
                                    <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ textAlign: 'right' }}>
                                                Amount Incurred
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ fontWeight: 'bold', textAlign: 'right' }}>
                                                {fNumber(totalAll().totalAmountIncurred)}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>

                                {/* Amount Approved */}
                                <Grid item xs={width}>
                                    <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ textAlign: 'right' }}>
                                                Amount Approved
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ fontWeight: 'bold', textAlign: 'right' }}>
                                                {fNumber(totalAll().totalAmountApproved)}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>

                                {/* Amount Not Approved */}
                                <Grid item xs={width}>
                                    <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ textAlign: 'right' }}>
                                                Amount Not Approved
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ fontWeight: 'bold', textAlign: 'right' }}>
                                                {fNumber(totalAll().totalAmountNotApproved)}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>

                                {/* Excess Paid* */}
                                <Grid item xs={width}>
                                    <Grid container>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ textAlign: 'right' }}>
                                                Excess Paid
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant="caption" sx={{ fontWeight: 'bold', textAlign: 'right' }}>
                                                {fNumber(totalAll().totalExcessPaid)}
                                            </Typography>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>
                        </Box>
                    </Grid>

                
                </Grid>

                
                {/* </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={errorsExist} 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"
        />
      );
}