// mui
import { Container, Grid, Stack, Typography, Card, TextField, Divider, ButtonBase, Box, IconButton } from '@mui/material';
// components
import Page from '../../components/Page';
// utils
import useSettings from '../../hooks/useSettings';
// react
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { useEffect, useState, useRef } from 'react';
import axios from '../../utils/axios';
// pages
import DetailTimeline from '../../pages/ClaimRequests/DetailTimeline';
import DetailStepper from '../../pages/ClaimRequests/DetailStepper';
import { format } from 'date-fns';
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import RemoveIcon from '@mui/icons-material/Remove';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import Iconify from '@/components/Iconify';
import { fPostFormat } from '@/utils/formatTime';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import DownloadIcon from '@mui/icons-material/Download';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import { fDateTimesecond } from '@/utils/formatTime';
import { makeFormData } from '@/utils/jsonToFormData';

import { enqueueSnackbar } from 'notistack';

// ----------------------------------------------------------------------

export default function Detail() {
    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);
    const code = queryParams.get('code');

    const navigate = useNavigate();
    const { themeStretch } = useSettings();
    const [data, setData] = useState();
    const [dataDialog, setDataDialog] = useState();
    const [document, setDocument] = useState(null);

    const { id } = useParams();

    useEffect(() => {
        axios
        .get('/claim-requests/detail/'+id)
        .then((response) => {
            setData(response.data);
            setDataDialog(response.data.data.dialog_submits);
            setDocument(response.data.data.documents);

        })
        .catch((error) => {
            console.error(error);
        });

    }, []);

    const [isInvoiceVisible, setInvoiceVisibility] = useState(false);

    const handleInvoice = () => {
        setInvoiceVisibility(!isInvoiceVisible);
    }
    const currentDate = new Date();
    const formattedCurrentDate = format(currentDate, 'dd MMM yyyy');
    const [dateInvoice, setDateInvoice] = useState(currentDate);

    const fileInvoiceInput = useRef<HTMLInputElement>(null);
    const [fileInvoices, setFileInvoices] = useState([]);

    const handleInvoiceInputChange = (event) => {
        if (event.target.files[0]) {
            setFileInvoices([...fileInvoices, ...event.target.files]);
        } else {
            console.log('NO FILE');
        }
    };
    const removeInvoiceFiles = (filesState, index) => {
        setFileInvoices(
        filesState.filter((file, fileIndex) => {
            return fileIndex != index;
        })
        );
    };
    const date = dateInvoice ? fPostFormat(dateInvoice, 'yyyy-MM-dd') : null;

    const [openDialogSubmit, setOpenDialogSubmit] = useState(false);
    const handleCloseDialogSubmit = () => {
        setOpenDialogSubmit(false);
    }
    const handleSubmitData = () => {
        // if(fileInvoices.length > 0)
        // {
            //submit data
            axios
            .post('claim-requests/'+id+'/approve')
            .then((response) => {
                enqueueSnackbar('Success Submit Claim Request', { variant: 'success' });
                setOpenDialogSubmit(false);
            })
            .catch(({ response }) => {
                enqueueSnackbar(response.data.message ?? 'Something went wrong!', { variant: 'error' });
            });
            //Upload file invoices
            const formData = makeFormData({
                date:date,
                invoice_files: fileInvoices,
            });
            axios
            .post('claim-requests/'+id+'/invoice-files', formData)
            .then((response) => {
                enqueueSnackbar(response.data.message ?? 'Success upload invoice', { variant: 'success' });
            })
            .catch(({ response }) => {
                enqueueSnackbar(response.data.message ?? 'Something Went Wrong', { variant: 'error' });
            });
        // }
        // else
        // {
        //     enqueueSnackbar('Please upload file invoice, before submit', { variant: 'warning' });
        // }

        setTimeout(() =>
        {
            window.location.reload();
        }, 5000);

    };

    const check_invoice = document?.find((dataInvoice) => dataInvoice.type === 'claim-invoice');

    return (
        <Page title='Detail'>
        <Container maxWidth={themeStretch ? false : 'xl'}>
            <Stack direction="row" alignItems="center" sx={{ marginBottom: 3 }}>
            <ArrowBackIosIcon onClick={() => navigate(-1)} sx={{cursor:'pointer'}}/>
            <Typography variant="h5" sx={{marginLeft:2}}>{(data && data.data) ? data.data.status.code : ''}</Typography>
            {data ? (
            <Stack direction="row" spacing={2} ml="auto">
                <Typography variant="body2" sx={{color: '#757575'}}>Submission Date</Typography>
                <Typography variant="body2" fontWeight="bold">{(data && data.data) ? format(new Date(data.data.status.submission_date), "d MMM yyyy") : ''}</Typography>
            </Stack>
            ) : ''}
            </Stack>
            {data ? (
            <Grid container spacing={2}>
                <Grid item xs={12} md={12}>
                    <DetailStepper data={data}/>
                </Grid>
                <Grid item xs={12} md={12}>
                    <Stack direction="row" alignItems="center">
                        <Typography variant="subtitle1">Format Claim</Typography>
                        <Button variant="outlined" color="primary" startIcon={< DownloadIcon/>} sx={{marginLeft: 'auto'}}>
                            <Typography variant="button" display="block">Import</Typography>
                        </Button>
                    </Stack>
                </Grid>
                {check_invoice ? (
                    <Grid item xs={12} md={12}>
                        <Stack direction="row" alignItems="center">
                            <Typography variant="subtitle1">Request Claim</Typography>
                            <Button variant="outlined" color="primary" startIcon={ isInvoiceVisible ? < RemoveIcon/> : < AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => handleInvoice()}>
                                <Typography variant="button" display="block">Invoice</Typography>
                            </Button>
                        </Stack>
                    </Grid>
                ) : ''}
                <Grid item xs={12} md={12} sx={{display : isInvoiceVisible ? '' : 'none',}}>
                    <Card sx={{padding: 2}}>
                        <Stack direction="column" spacing={2}>
                            <LocalizationProvider dateAdapter={AdapterDateFns}>
                                <DatePicker
                                    label="Invoice Date"
                                    value={dateInvoice}
                                    onChange={(newValue) => {
                                        setDateInvoice(newValue);
                                    }}
                                    inputFormat="dd MMM yyyy"
                                    renderInput={(params) => <TextField sx={{width:'40%'}} {...params} defaultValue={formattedCurrentDate} required/>}
                                />
                            </LocalizationProvider>
                            <Stack
                                divider={<Divider orientation="horizontal" flexItem />}
                                spacing={1}
                                sx={{ marginY: 2 }}
                            >
                                {fileInvoices &&
                                fileInvoices.map((file, index) => (
                                    <Stack direction="row" justifyContent={'space-between'} key={index}>
                                        <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={() => {
                                            removeInvoiceFiles(fileInvoices, index);
                                            }}
                                            sx={{cursor: 'pointer'}}
                                        ></Iconify>
                                    </Stack>
                                ))}
                            </Stack>
                            <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                                    bgcolor: '#919EAB52',
                                    borderRadius: '8px',
                                    width: '100%', height: '60px'}} onClick={() => fileInvoiceInput.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 Invoice
                                </Typography>
                                </Box>
                                <input
                                type="file"
                                id="file"
                                ref={fileInvoiceInput}
                                style={{ display: 'none' }}
                                multiple
                                onChange={handleInvoiceInputChange}
                                accept="application/pdf"
                                />
                            </ButtonBase>
                        </Stack>
                    </Card>
                </Grid>
                <Grid item xs={12} md={12}>
                    <DetailTimeline data={data}/>
                </Grid>
                <Grid item xs={12} md={12}>
                    <Stack direction="row" padding={4}>
                        {dataDialog && dataDialog.status === 'requested' ? (
                            <>
                            <Button variant="outlined" sx={{color: '#212B36', marginLeft: 'auto', borderColor: '#919EAB52'}} >Cancel</Button>
                            <Button sx={{backgroundColor: '#19BBBB', marginLeft: 1}} variant="contained" onClick={()=> setOpenDialogSubmit(true)}>Submit</Button>
                            </>
                        ) : ''}
                        {/* Dialog Submits */}
                        <Dialog open={openDialogSubmit} onClose={handleCloseDialogSubmit} fullWidth={true}>
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">Confirmation</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogSubmit}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                                {dataDialog ? (
                                <Stack spacing={2} padding={2}>
                                    <Typography variant='body1'>Are you sure to submit this claim ?</Typography>
                                    <Card sx={{padding:2}}  >
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Code</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{dataDialog.code}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Name</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{dataDialog.name}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Date Submission</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{fDateTimesecond(dataDialog.submission_date)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Claim Method</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>Service Type</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Service Type</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>
                                                {dataDialog.service_code === 'IP' ? 'Inpatient' : 'Outpatient'}
                                            </Typography>
                                        </Stack>
                                    </Card>
                                </Stack>
                                ) : ''}
                            </DialogContent>
                            <DialogActions>
                            <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialogSubmit}>Cancel</Button>
                            <Button sx={{backgroundColor: '#19BBBB'}} onClick={handleSubmitData} variant="contained">Submit</Button>
                            </DialogActions>
                        </Dialog>
                    </Stack>
                </Grid>
            </Grid>
            ) : ''}
        </Container>
        </Page>
    );
}
