/**
 * Core
 * ============================================
 */
import { useFieldArray, useForm } from 'react-hook-form';
import { useNavigate, useParams } from 'react-router-dom';
import { Box, IconButton, Typography, Grid, Card, Button, ButtonBase, Stack } from '@mui/material';
import { LoadingButton } from "@mui/lab";

/**
 * Components
 * ============================================
*/
import Page from '@/components/Page';
import { FormProvider, RHFTextField } from '@/components/hook-form';
import RHFDatePickerV2 from '@/components/hook-form/RHFDatePickerV2';

/**
 * Icon
 * ============================================
 */
import ArrowBackIosNew from '@mui/icons-material/ArrowBackIosNew';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';

/**
 * Utils, Types, Functions
 * ============================================
 */
import { AddMonitoringDetail } from '../Model/Functions';
import { DetailMonitoringListType} from '../Model/Types';
import FormCreateFilesUpload from '@/pages/CustomerService/FinalLog/Components/FormCreateFilesUpload';
import MultiFilePreview from '@/components/upload/MultiFilePreview';
import Iconify from '@/components/Iconify';
import { useRef } from 'react';

export default function DetailMonitoringList() {
    const { member_id, claim_code } = useParams();
    const navigate  = useNavigate()
    const pageTitle = claim_code??'_ _ _ _';
    const fileInput1 = useRef<HTMLInputElement>(null);
    const fileInput2 = useRef<HTMLInputElement>(null);
    const fileInput3 = useRef<HTMLInputElement>(null);

    // setup form
    // ====================================
    const defaultValues: DetailMonitoringListType = {
        id              : '',
        claim_code      : '',
        claim_id        : '',
        subject         : '',
        body_temperature: '',
        sistole         : '',
        diastole        : '',
        respiration_rate: '',
        complaints      : '',
        analysis        : '',
        medical_plan    : [{
            medical_plan_str: ''
        }],
        non_medikamentosa_plan : [{
            non_medikamentosa_plan_str: ''
        }],
        confirmation_medical_leter  : [],
        medical_action_letter       : [],
        result          : [],
        created_at      : '',
        lab_date        : '',
        provider        : '',
        examination     : '',
    };

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

    const {fields: fields1, append: append1, remove: remove1} = useFieldArray({name: 'medical_plan',control: methods.control})
    const {fields: fields2, append: append2, remove: remove2} = useFieldArray({name: 'non_medikamentosa_plan',control: methods.control})

    const { handleSubmit, reset, watch, setValue, formState: { isDirty, isSubmitting } } = methods;
    const formValues = watch();
     // Handle File Input
    // =====================================
    const handleInputChangeConfirmationMedicalLeter = (event: any) => {
        if (event.target.files[0]) {

            let arr_confirmation_medical_leter_file = formValues.confirmation_medical_leter;
            arr_confirmation_medical_leter_file.push(event.target.files[0]);

            setValue('confirmation_medical_leter', arr_confirmation_medical_leter_file);
        }
        else {
            console.log('NO FILE');
        }
    };
    const handleInputChangeMedicalActionLetter = (event: any) => {
        if (event.target.files[0]) {

            let arr_medical_action_letter = formValues.medical_action_letter;
            arr_medical_action_letter.push(event.target.files[0]);

            setValue('medical_action_letter', arr_medical_action_letter)
            console.log('test2')
        }
        else {
            console.log('NO FILE');
        }
    };

    const handleInputChangeResult = (event: any) => {
        if (event.target.files[0]) {

            let arr_result = formValues.result;
            arr_result.push(event.target.files[0]);

            setValue('result', arr_result)
            console.log('test3')
        }
        else {
            console.log('NO FILE');
        }
    };
    

     // Handle Remove File
    // =====================================
    const handleRemoveFileConfirmationMedicalLeter = (target_index: number) => {
        let arr_confirmation_medical_leter_file = formValues.confirmation_medical_leter.filter((file: any, index: number) =>{
            if (target_index !== index) {
                return file;
            }
        });

        setValue('confirmation_medical_leter', arr_confirmation_medical_leter_file)
    };
    const handleRemoveFileMedicalActionLetter = (target_index: number) => {
        let arr_medical_action_letter = formValues.medical_action_letter.filter((file: any, index: number) =>{
            if (target_index !== index) {
                return file;
            }
        });

        setValue('medical_action_letter', arr_medical_action_letter)
    };
    const handleRemoveFileResult = (target_index: number) => {
        let arr_result = formValues.result.filter((file: any, index: number) =>{
            if (target_index !== index) {
                return file;
            }
        });

        setValue('result', arr_result)
    };

    // Submit Form
    // =====================================
    const submitHandler = async (data: DetailMonitoringListType) => {
        console.log(claim_code);

        const response = await AddMonitoringDetail(claim_code??'', data);

        if (response == true) {
            reset();
            navigate('/case_management/daily_monitoring/'+member_id+'/claims', { replace: true });
            // window.location.reload()
        }
    }

    return (
        <Page title={pageTitle}>
            <Box sx={{ display: 'flex', alignItems: 'center', pl: '22px', mb: '40px' }}>
                <IconButton size='large' color='inherit' onClick={() => navigate(`/case_management/daily_monitoring/${member_id}/claims`)} >
                    <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}>
                            {/* Subject */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Subject* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <RHFTextField
                                            id="subject"
                                            name='subject'
                                            placeholder='Subjective'
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Objectif */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Objectif
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        <Grid container spacing={3}>
                                            <Grid item xs={3}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    Body Temperature* :
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={3}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    Sistole* :
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={3}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    Diastole* :
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={3}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    Respiration Rate* :
                                                </Typography>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                    <Grid item xs={12}>
                                        <Grid container spacing={3}>
                                            <Grid item xs={2}>
                                                <RHFTextField
                                                    id="body_temperature"
                                                    name='body_temperature'
                                                    placeholder='Body Temperature'
                                                />
                                            </Grid>
                                            <Grid item xs={1} sx={{ display: 'flex', alignItems: 'center' }}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    Cel
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={2}>
                                                <RHFTextField
                                                    id="sistole"
                                                    name='sistole'
                                                    placeholder='Sistole'
                                                />
                                            </Grid>
                                            <Grid item xs={1} sx={{ display: 'flex', alignItems: 'center' }}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    mm[Hg]
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={2}>
                                                <RHFTextField
                                                    id="diastole"
                                                    name='diastole'
                                                    placeholder='Diastole'
                                                />
                                            </Grid>
                                            <Grid item xs={1} sx={{ display: 'flex', alignItems: 'center' }}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    mm[Hg]
                                                </Typography>
                                            </Grid>
                                            <Grid item xs={2}>
                                                <RHFTextField
                                                    id="respiration_rate"
                                                    name='respiration_rate'
                                                    placeholder='Respiration Rate'
                                                />
                                            </Grid>
                                            <Grid item xs={1} sx={{ display: 'flex', alignItems: 'center' }}>
                                                <Typography variant="body1" component="div" color={'GrayText'}>
                                                    /min
                                                </Typography>
                                            </Grid>
                                        </Grid>
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Complaints */}
                            {/* <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Complaints* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <RHFTextField
                                            id="complaints"
                                            name='complaints'
                                            placeholder='Complaints'
                                        />
                                    </Grid>
                                </Grid>
                            </Grid> */}

                            {/* Analysis */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Analysis* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <RHFTextField
                                            id="analysis"
                                            name='analysis'
                                            placeholder='Analysis'
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Medical Plan */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Medical Plan* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        {
                                            fields1.map((field,index) => {
                                                return (
                                                    <Grid key={field.id} container sx={{ mb: 3 }}>
                                                        <Grid item xs={11}>
                                                            <RHFTextField
                                                                id="analysis"
                                                                name={`medical_plan.${index}.medical_plan_str`}
                                                                placeholder='Medical Plan'
                                                            />
                                                        </Grid>
                                                        {
                                                        index == (fields1.length-1) ?
                                                            (
                                                                <Grid item xs={1} sx={{ textAlign: 'center' }}>
                                                                    <IconButton size='large' color='primary' onClick={() => append1({medical_plan_str: ''})}>
                                                                        <AddIcon />
                                                                    </IconButton>
                                                                </Grid>
                                                            )
                                                            :
                                                            (
                                                                <Grid item xs={1} sx={{ textAlign: 'center' }}>
                                                                    <IconButton size='large' color='error' onClick={() => remove1(index)}>
                                                                        <RemoveIcon />
                                                                    </IconButton>
                                                                </Grid>
                                                            )
                                                        }
                                                    </Grid>
                                                )
                                            })
                                        }
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Non Medikamentosa Plan* */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Non Medikamentosa Plan* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        {
                                            fields2.map((field,index) => {
                                                return (
                                                    <Grid key={field.id} container sx={{ mb: 3 }}>
                                                        <Grid item xs={11}>
                                                            <RHFTextField
                                                                id="analysis"
                                                                name={`non_medikamentosa_plan.${index}.non_medikamentosa_plan_str`}
                                                                placeholder='Non Medikamentosa'
                                                            />
                                                        </Grid>
                                                        {
                                                        index == (fields2.length-1) ?
                                                            (
                                                                <Grid item xs={1} sx={{ textAlign: 'center' }}>
                                                                    <IconButton size='large' color='primary' onClick={() => append2({non_medikamentosa_plan_str: ''})}>
                                                                        <AddIcon />
                                                                    </IconButton>
                                                                </Grid>
                                                            )
                                                            :
                                                            (
                                                                <Grid item xs={1} sx={{ textAlign: 'center' }}>
                                                                    <IconButton size='large' color='error' onClick={() => remove2(index)}>
                                                                        <RemoveIcon />
                                                                    </IconButton>
                                                                </Grid>
                                                            )
                                                        }
                                                    </Grid>
                                                )
                                            })
                                        }
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* Confirmation Medical Letter */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Confirmation Medical Letter*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        {
                                            formValues.confirmation_medical_leter.map((file: any, index: number) => (
                                                <Stack direction="row" justifyContent={'space-between'} key={index} sx={{ mb: '16px' }}>
                                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                                        <InsertDriveFileIcon />
                                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                                    </Stack>
                                                    <Iconify
                                                        icon="eva:trash-2-outline"
                                                        color={'darkred'}
                                                        onClick={() => handleRemoveFileConfirmationMedicalLeter(index)}
                                                        sx={{cursor: 'pointer'}}
                                                    ></Iconify>
                                                </Stack>
                                            ))
                                        }
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',bgcolor: '#919EAB52',borderRadius: '8px',width: '100%', height: '60px'}} onClick={() => fileInput1.current?.click()}>
                                            <Box
                                                sx={{
                                                    display: 'flex',
                                                    placeItems: 'center',
                                                    gap: 1,
                                                    placeContent: 'center',
                                                }}
                                            >
                                            <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
                                                <Typography variant="body1" fontWeight="bold">
                                                    Upload File
                                                </Typography>
                                            </Box>
                                            <input
                                                type="file"
                                                id="file_input"
                                                ref={fileInput1}
                                                style={{ display: 'none' }}
                                                multiple
                                                onChange={(e) => handleInputChangeConfirmationMedicalLeter(e)}
                                                accept="application/pdf"
                                            />
                                        </ButtonBase>
                                    </Grid>
                                    
                                </Grid>
                            </Grid>
                            
                            {/* Medical Action Letter */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                                Medical Action Letter*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        {
                                            formValues.medical_action_letter.map((file: any, index: number) => (
                                                <Stack direction="row" justifyContent={'space-between'} key={index} sx={{ mb: '16px' }}>
                                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                                        <InsertDriveFileIcon />
                                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                                    </Stack>
                                                    <Iconify
                                                        icon="eva:trash-2-outline"
                                                        color={'darkred'}
                                                        onClick={() => handleRemoveFileMedicalActionLetter(index)}
                                                        sx={{cursor: 'pointer'}}
                                                    ></Iconify>
                                                </Stack>
                                            ))
                                        }
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',bgcolor: '#919EAB52',borderRadius: '8px',width: '100%', height: '60px'}} onClick={() => fileInput2.current?.click()}>
                                            <Box
                                                sx={{
                                                    display: 'flex',
                                                    placeItems: 'center',
                                                    gap: 1,
                                                    placeContent: 'center',
                                                }}
                                            >
                                            <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
                                                <Typography variant="body1" fontWeight="bold">
                                                    Upload File
                                                </Typography>
                                            </Box>
                                            <input
                                                type="file"
                                                id="file_2"
                                                ref={fileInput2}
                                                style={{ display: 'none' }}
                                                multiple
                                                onChange={handleInputChangeMedicalActionLetter}
                                                accept="application/pdf"
                                            />
                                        </ButtonBase>
                                    </Grid>
                                    
                                </Grid>
                            </Grid>

                            
                            {/* Laboratorium */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                                Laboratorium Result*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={6}>
                                        <Typography variant="body1" component="div">
                                            Date*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={6}>
                                        <Typography variant="body1" component="div">
                                            Provider*
                                        </Typography>
                                    </Grid>

                                    <Grid item xs={6} sx={{display: 'flex', gap: 1}}>
                                        <RHFDatePickerV2
                                            label='Date'
                                            name="lab_date"
                                            dateFormat='dd MMM yyyy'
                                            fullWidth
                                        />
                                    </Grid>
                                    <Grid item xs={6} sx={{display: 'flex', gap: 1}}>
                                        <RHFTextField
                                            id="provider"
                                            name='provider'
                                            placeholder='Provider'
                                            label='Provider'
                                        />
                                    </Grid>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Examination*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <RHFTextField
                                            id="examination"
                                            name='examination'
                                            placeholder='examination'
                                            label='Examination'
                                        />
                                    </Grid>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                                Laboratorium Result*
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12}>
                                        {
                                            formValues.result.map((file: any, index: number) => (
                                                <Stack direction="row" justifyContent={'space-between'} key={index} sx={{ mb: '16px' }}>
                                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                                        <InsertDriveFileIcon />
                                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                                    </Stack>
                                                    <Iconify
                                                        icon="eva:trash-2-outline"
                                                        color={'darkred'}
                                                        onClick={() => handleRemoveFileResult(index)}
                                                        sx={{cursor: 'pointer'}}
                                                    ></Iconify>
                                                </Stack>
                                            ))
                                        }
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',bgcolor: '#919EAB52',borderRadius: '8px',width: '100%', height: '60px'}} onClick={() => fileInput3.current?.click()}>
                                            <Box
                                                sx={{
                                                    display: 'flex',
                                                    placeItems: 'center',
                                                    gap: 1,
                                                    placeContent: 'center',
                                                }}
                                            >
                                            <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
                                                <Typography variant="body1" fontWeight="bold">
                                                    Upload File
                                                </Typography>
                                            </Box>
                                            <input
                                                type="file"
                                                id="file_3"
                                                ref={fileInput3}
                                                style={{ display: 'none' }}
                                                multiple
                                                onChange={handleInputChangeResult}
                                                accept="application/pdf"
                                            />
                                        </ButtonBase>
                                    </Grid>
                                    
                                </Grid>
                            </Grid>


                            {/* Button Cancel & 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(`/case_management/daily_monitoring/${member_id}/claims`)}>
                                            Cancel
                                        </Button>
                                        <LoadingButton disabled={!isDirty} type="submit" variant="contained" loading={isSubmitting}>
                                            Add
                                        </LoadingButton>
                                    </Box>
                                </Box>
                            </Grid>
                        </Grid>
                    </Card>
                </FormProvider>
            </Box>
        </Page>
    );
}
