/**
 * Core
 * ============================================
 */
import { useRef } from 'react';
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, RHFDatepicker, RHFTextField } from '@/components/hook-form';
import RHFDatePickerV2 from '@/components/hook-form/RHFDatePickerV2';

/**
 * Icon
 * ============================================
 */
import ArrowBackIosNew from '@mui/icons-material/ArrowBackIosNew';
import Iconify from '@/components/Iconify';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';

/**
 * Utils, Types, Functions
 * ============================================
 */
import { AddLabResultDetail } from '../Model/Functions';
import { DetailLabResultListType} from '../Model/Types';

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

    // setup form
    // ====================================
    const defaultValues: DetailLabResultListType = {
        id              : '',
        claim_id        : '',
        claim_code      : '',
        date            : null,
        location        : '',
        examination     : '',
        lab_result_file : [],
        created_at      : ''
    };

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

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

    // Handle File Input
    // =====================================
    const handleInputChange = (event: any) => {
        if (event.target.files[0]) {

            let arr_lab_result_file = formValues.lab_result_file;
            arr_lab_result_file.push(event.target.files[0]);

            setValue('lab_result_file', arr_lab_result_file)
        }
        else {
            console.log('NO FILE');
        }
    };

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

        setValue('lab_result_file', arr_lab_result_file)
    };

    // Submit Form
    // =====================================
    const submitHandler = async (data: DetailLabResultListType) => {
        const response = await AddLabResultDetail(claim_code??'', data);

        if (response == true) {
            reset(defaultValues);
        }
    }

    return (
        <Page title={pageTitle}>
            <Box sx={{ display: 'flex', alignItems: 'center', pl: '22px', mb: '40px' }}>
                <IconButton size='large' color='inherit' onClick={() => navigate(`/case_management/laboratorium_result/${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}>
                            {/* Date */}
                            <Grid item xs={6}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        <Typography variant="body1" component="div">
                                            Date* :
                                        </Typography>
                                    </Grid>
                                    <Grid item xs={12} sx={{display: 'flex', gap: 1}}>
                                        <RHFDatePickerV2
                                            label=''
                                            name="date"
                                            dateFormat='dd-MMMM-yyyy'
                                            fullWidth
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

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

                            {/* Examination */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <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'
                                        />
                                    </Grid>
                                </Grid>
                            </Grid>

                            {/* list file & button upload */}
                            <Grid item xs={12}>
                                <Grid container spacing={3}>
                                    <Grid item xs={12}>
                                        {
                                            formValues.lab_result_file.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={() => handleRemoveFile(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={() => fileInput.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 Result
                                                </Typography>
                                            </Box>
                                            <input
                                                type="file"
                                                id="file"
                                                ref={fileInput}
                                                style={{ display: 'none' }}
                                                multiple
                                                onChange={handleInputChange}
                                                accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
                                            />
                                        </ButtonBase>
                                    </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(`/case_management/laboratorium_result/${member_id}/claims`)}>
                                            Cancel
                                        </Button>
                                        <LoadingButton disabled={!isDirty} type="submit" variant="contained" loading={isSubmitting}>
                                            Save Changes
                                        </LoadingButton>
                                    </Box>
                                </Box>
                            </Grid>
                        </Grid>
                    </Card>
                </FormProvider>
            </Box>
        </Page>
    )
}
