/**
 * Core
 * ============================================
 */
import axios from '@/utils/axios';
import { useForm } from 'react-hook-form';
import { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Box, IconButton, Typography, Grid, Card, TextField, Autocomplete, Button } from '@mui/material';

/**
 * Components
 * ============================================
*/
import Page from '../../../components/Page';
import { LoadingButton } from "@mui/lab";
import { FormProvider, RHFCustomMultiCheckbox, RHFTextField } from '@/components/hook-form';
import { enqueueSnackbar } from 'notistack';

/**
 * Icon
 * ============================================
 */
import ArrowBackIosNew from '@mui/icons-material/ArrowBackIosNew';

export default function Divisions() {
    const pageTitle = 'Edit Exclusion';
    const navigate  = useNavigate()
    const { corporate_id, exclusion_id } = useParams();                 // id di url
    const [ plans, setPlans ]            = useState<string[]>([]);      // option untuk field plans

    // checkbox option
    // ====================================
    const msc_checkbox_option = [
        {
            value: 'm',
            label: 'Member',
        },
        {
            value: 's',
            label: 'Spouse',
        },
        {
            value: 'c',
            label: 'Child',
        },
    ]

    const gender_checkbox_option = [
        {
            value: 'male',
            label: 'Male',
        },
        {
            value: 'female',
            label: 'Female',
        },
    ]

    // setup form
    // ====================================
    const defaultValues: any = {
        msc: [],
        gender: [],
        min_age: '',
        max_age: '',
        plans: [],
    };

    const methods = useForm<any>({
        defaultValues
    });

    const { setValue, handleSubmit, reset, watch, formState: { isDirty, isSubmitting } } = methods;
    const formValues = watch();

    // set form value
    // =====================================
    useEffect(() => {
        axios.get(`corporates/${corporate_id}/diagnosis-exclusions/${exclusion_id}`)
            .then((res) => {
                // plan option
                setPlans(res.data.data.plans);

                // set value
                let res_plan = res.data.data.exclusion.rules.plan;

                if (res_plan.length == 1 && res_plan[0] == '') {
                    res_plan = [];
                }

                reset({
                    msc     : res.data.data.exclusion.rules.msc[0].split(','),
                    gender  : res.data.data.exclusion.rules.gender[0].split(','),
                    min_age : res.data.data.exclusion.value_rules.min_age,
                    max_age : res.data.data.exclusion.value_rules.max_age,
                    plans   : res_plan,
                })
            })
    }, [exclusion_id]);

    // Submit Form
    // =====================================
    const submitHandler = async (data: any) => {
        let one_row = {
            msc: {
                m: data.msc.includes('m'),
                s: data.msc.includes('s'),
                c: data.msc.includes('c'),
            },
            gender : {
                male  : data.gender.includes('male') == true ? 1 : 0,
                female: data.gender.includes('female') == true ? 1 : 0,
            },
            min_age: data.min_age,
            max_age: data.max_age,
            plan   : data.plans.join(','),
            icd_id : exclusion_id,
        }

        return axios
            .post(`/corporates/${corporate_id}/diagnosis-exclusions/store`, {
                type: 'one_row',
                icd_id: exclusion_id,
                one_row
            })
            .then((res) => {
                enqueueSnackbar('Exclusion Updated', {
                    variant: 'success',
                });

                reset({
                    msc     : data.msc,
                    gender  : data.gender,
                    min_age : data.min_age,
                    max_age : data.max_age,
                    plans   : data.plans,
                })

                return true;
            })
            .catch((res) => {
                enqueueSnackbar('Terjadi kesalahan pada server', {
                    variant: 'error',
                });

                return true;
            })
    }

    return (
        <Page title={pageTitle}>
            <Box sx={{ display: 'flex', alignItems: 'center', pl: '12px', mb: '40px' }}>
                <IconButton size='large' color='inherit' onClick={() => navigate(`/corporates/${corporate_id}/diagnosis-exclusions`)} >
                    <ArrowBackIosNew/>
                </IconButton>

                <Typography variant="h5" sx={{ marginLeft: '24px' }}>
                    {pageTitle}
                </Typography>
            </Box>

            <Box sx={{ px: '28px' }}>
                <FormProvider methods={methods} onSubmit={handleSubmit(submitHandler)}>
                    <Card sx={{ padding: '24px' }}>
                        <Grid container spacing={6}>
                            {/* MSC row */}
                            <Grid item xs={12}>
                                <Grid container spacing={2}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div" color={'GrayText'}>
                                            MSC* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        <RHFCustomMultiCheckbox name="msc" options={msc_checkbox_option} sx={{ flexDirection: 'row' }} />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Gender row */}
                            <Grid item xs={12}>
                                <Grid container spacing={2}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div" color={'GrayText'}>
                                            Gender* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        <RHFCustomMultiCheckbox name="gender" options={gender_checkbox_option} sx={{ flexDirection: 'row' }} />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Age row */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div" color={'GrayText'}>
                                            Age* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <Grid container spacing={2}>
                                            <Grid item xs={3} md={3}>
                                                <RHFTextField
                                                    id="min_age"
                                                    name='min_age'
                                                />
                                            </Grid>
                                            <Grid item xs={3} md={3}>
                                                <RHFTextField
                                                    id="max_age"
                                                    name='max_age'
                                                />
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Plan Section */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div" color={'GrayText'}>
                                            Plan* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <Autocomplete
                                            options={plans}
                                            fullWidth
                                            multiple
                                            limitTags={5}
                                            getOptionLabel={(option) => {
                                                return option ?? false
                                            }}
                                            value={formValues.plans}
                                            isOptionEqualToValue={(option, value) =>{
                                                return option === value
                                            }}
                                            renderInput={(params) => (
                                                <TextField {...params} label="Plan" variant="outlined" />
                                            )}
                                            onChange={(event,value) => {
                                                setValue('plans', value, {shouldDirty: true});
                                            }}
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Button Cancle & Save */}
                            <Grid item xs={12} md={12}>
                                <Box display="flex" justifyContent={'flex-end'}>
                                    <Box display="flex" gap={1}>
                                        <Button variant="outlined" color="inherit" onClick={() => navigate(`/corporates/${corporate_id}/diagnosis-exclusions`)}>
                                            Cancel
                                        </Button>
                                        <LoadingButton disabled={!isDirty} type="submit" variant="contained" loading={isSubmitting}>
                                            Save Changes
                                        </LoadingButton>
                                    </Box>
                                </Box>
                            </Grid>
                        </Grid>
                    </Card>
                </FormProvider>
            </Box>
        </Page>
    );
}
