import {
    Container,
    Grid,
    Stack,
    Typography,
    Card,
    Dialog,
    TableRow,
    Tab,
    TableCell,
    Collapse,
    AccordionSummary,
    AccordionDetails,
    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, useMemo } from 'react';
import axios from '../../../utils/axios';
// pages
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import { DetailFinalLogType } from './Model/Types';
import { fDate, fDateTimesecond } from '@/utils/formatTime';
import { Button } from '@mui/material';
import DialogConfirmation from '../FinalLog/Components/DialogConfirmation';
import Label from '@/components/Label';
import { Box } from '@mui/system';
import { Accordion } from '@mui/material';
import { Delete, EditOutlined, ExpandMore } from '@mui/icons-material';
import {BenefitData } from '../FinalLog/Model/Types'
import AddIcon from '@mui/icons-material/Add';

// Import Card Detail Final LOG
import CardDetail from '../Components/CardDetail';
import CardService from '../Components/CardService';
import CardExclusion from '../Components/CardExclusion';
import CardBenefit from '../Components/CardBenefit';

// Import Dialog
import DialogHospitalCare from './Components/DialogHospitalCare';
import DialogBenefit from './Components/DialogBenefit';
import DialogMedicine from './Components/DialogMedicine';
import DialogDeleteBenfit from './Components/DialogDeleteBenefit';
import DialogEditBenefit from './Components/DialogEditBenefit'; 
import DialogDeleteMedicine from './Components/DialogDeleteMedicine'

import MoreMenu from '@/components/MoreMenu';
import { MenuItem } from '@mui/material';
import { fNumber } from '@/utils/formatNumber';
import palette from '@/theme/palette';
import CardMedicine from '../Components/CardMedicine';
import CardFile from '../Components/CardFile';
import DialogEditFinalLOG from './Components/DialogEditFinalLOG';


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

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

    const navigate = useNavigate();
    const { themeStretch } = useSettings();
    const [requestLog, setRequestLog] = useState<DetailFinalLogType>();
   

    const { id } = useParams();

    useEffect(() => {
        axios
        .get('customer-service/request/'+id)
        .then((response) => {
            setRequestLog(response.data.data)
        })
        .catch((error) => {
            console.error(error);
        })
    }, [id]);

    const style1 = {
        color: '#919EAB',
        width: '30%'
    }
    const style3 = {
        color: '#919EAB',
        width: '35%'
    }
    const style2 = {
        width: '70%'
    }
    const marginBottom1 = {
        marginBottom: 1,
    }
    const marginBottom2 = {
        marginBottom: 2,
    }

    const [openDialogSubmit, setOpenDialogSubmit] = useState(false);
    const [openDialogEditDetail, setDialogDEditDetail] = useState(false);
    const [openDialogBenefit, setDialogBenefit] = useState(false);
    const [openDialogMedicine, setDialogMedicine] = useState(false);

    // Handel Delete Detail Benefit
    const [idBenefitData, setIdBenefitData] = useState<number>();
    const [openDialogDeleteBenefit, setDialogDeleteBenefit] = useState(false)
    
    const [idMedicineData, setIdMedicineData] = useState<number>();
    const [openDialogDeleteMedicine, setDialogDeleteMedicine] = useState(false)

    const [approve, setApprove] = useState('')

    // Handle Edit Detail Benefit
    const [openDialogEditBenefit, setDialogEditBenefit] = useState(false)
    const [BenefitConfigurationData, setBenefitConfigurationData] = useState<BenefitData>();

    // Buat total data 
    const totalAmountIncurred = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
        return accumulator + (item.amount_incurred || 0);
      }, 0);
    const totalAmountApprove = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
        return accumulator + (item.amount_approved || 0);
      }, 0);
    const totalAmountNotApprove = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
        return accumulator + (item.amount_not_approved || 0);
      }, 0);
    const totalExcessPaid = (requestLog?.benefit_data || []).reduce((accumulator, item) => {
        return accumulator + (item.excess_paid || 0);
      }, 0);
      

    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}}>{(requestLog && requestLog.code ? requestLog.code : '')}</Typography>
            </Stack>
            <Grid container spacing={2}>
                {/* Detail */}
                <Grid item xs={12} md={12}>
                    <Card sx={{padding:2}}  >
                        <Grid container spacing={2}> 
                            <Grid item xs={6}>
                                <Typography variant='subtitle1' sx={{ color: '#19BBBB', marginBottom: 4 }} gutterBottom>
                                Detail
                                </Typography>
                            </Grid>
                            {requestLog?.status_final_log != 'requested' ? (
                            <Grid item xs={6} sx={{ display: 'flex', placeContent: 'end' }}>
                                <MoreMenu
                                    actions={
                                    <>
                                        <MenuItem onClick={() => {
                                            setDialogDEditDetail(true)
                                        }}>
                                        <EditOutlined />
                                        Edit
                                        </MenuItem>
                                    </>
                                    }
                                />
                            </Grid>) : null }
                        
                        </Grid>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Provider</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.provider}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Member ID</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.member_id}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Policy Number</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.policy_number}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Name</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.name}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Date Of Birth</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.date_of_birth ? fDate(requestLog?.date_of_birth) : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Marital Status</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.marital_status}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Submission Date</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.submission_date ? fDateTimesecond(requestLog?.submission_date) : '-'}</Typography>
                        </Stack>

                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Discharge Date</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.discharge_date ? fDateTimesecond(requestLog?.discharge_date) : '-'}</Typography>
                        </Stack>

                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>No KTP</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.no_identitas ? requestLog?.no_identitas : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Keterangan</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.keterangan ? requestLog?.keterangan : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Hak Kamar Pasien</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.hak_kamar_pasien ? requestLog?.hak_kamar_pasien : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Penempatan Kamar</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.penempatan_kamar ? requestLog?.penempatan_kamar : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Catatan</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.catatan ? requestLog?.catatan : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style3} gutterBottom>Diagnosis</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>
                                {requestLog?.diagnosis?.length > 0 ? (
                                    <ul>
                                        {requestLog.diagnosis.map((diagnosisItem, index) => (
                                            <li key={index}>{diagnosisItem.code} - {diagnosisItem.name}</li>
                                            // Replace 'name' with the property you want to display
                                        ))}
                                    </ul>
                                ) : (
                                    <p>No diagnosis available.</p>
                                )}
                            </Typography>
                        </Stack>
                        {/* <DialogEditFinalLOG
                        setOpenDialog={setOpenDialogEdit}
                        requestLog={requestLog}
                        openDialog={openDialogEdit}
                        /> */}
                    </Card>
                </Grid>

                {/* Service */}
                <Grid item xs={12} md={12} marginTop={2}>
                    <CardService 
                        requestLog={requestLog}
                        isFinalLog={true}
                    >
                    </CardService>
                </Grid>
                
                {/* Exclusion */}
                <Grid item xs={12} md={12} marginTop={2}>
                    {/* <CardExclusion 
                        requestLog={requestLog}
                    >
                    </CardExclusion> */}
                </Grid>

                {/* Hospital Care */}
                {/* <Grid item xs={12} md={12}>
                    <Card sx={{padding:2}}  >
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>History of Hospital Care</Typography>
                                <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => {
                                setDialogHospital(true);
                            }} >
                                    <Typography variant="button" display="block">History</Typography>
                                </Button>
                        </Stack>
                    </Card>
                    <DialogHospitalCare
                        requestLog={requestLog}
                        openDialog={openDialogHospital}
                        setOpenDialog={setDialogHospital}
                        
                    >
                    </DialogHospitalCare>
                </Grid> */}

                {/* Benefit */}
                <Grid item xs={12} md={12}>
                    <Card sx={{padding:2}}  >
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Benefit</Typography>
                                <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}}  onClick={() => {
                                    setDialogBenefit(true);
                                }} >
                                    <Typography variant="button" display="block">Benefit</Typography>
                                </Button>
                        </Stack>

                        {requestLog?.benefit_data?.map((item, index) => (
                            <Box key={index} sx={{ border: '1px solid rgba(0,0,0,0.125)', px: '24px', py: '20px', marginBottom: '24px', borderRadius: '12px'}}> 
                            <Grid container spacing={2}>
                                <Grid item xs={12}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={6}>
                                            <Typography variant="body2" sx={{ fontWeight: 'bold'}}>
                                                {item.benefit?.description}
                                            </Typography>
                                        </Grid>
                                        <Grid item xs={6} sx={{ display: 'flex', placeContent: 'end' }}>
                                            <MoreMenu actions={
                                                <>
                                                    <MenuItem onClick={() => {
                                                            setDialogEditBenefit(true)
                                                            setIdBenefitData(item.id)
                                                            setBenefitConfigurationData(item)
                                                        }}
                                                    >
                                                        <EditOutlined />
                                                        Edit
                                                    </MenuItem>
                                                    <MenuItem onClick={() => {
                                                        setIdBenefitData(item.id)
                                                        setDialogDeleteBenefit(true)
                                                    }}
                                                    >
                                                        <Delete color='error'/>
                                                        Delete
                                                    </MenuItem>
                                                </>
                                            } />
                                        </Grid>
                                    </Grid>
                                </Grid>
                                <Grid item xs={12}>
                                    <Box sx={{ py: '8px', px: '12px', background: palette.light.grey[50012], borderRadius: '6px'}}>
                                        <Grid container spacing={1}>

                                            {/* Amount Incurred */}
                                            <Grid item xs={2}>
                                                <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption">
                                                            Amount Incurred
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                                                            {fNumber(item.amount_incurred)}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </Grid>

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

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

                                            {/* Excess Paid* */}
                                            <Grid item xs={2}>
                                                <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption">
                                                            Excess Paid*
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                                                            {fNumber(item.excess_paid)}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </Grid>

                                            {/* Keterangan* */}
                                            <Grid item xs={3}>
                                                <Grid container>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption">
                                                            Keterangan*
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                                                            {item.keterangan}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </Grid>

                                        </Grid>
                                    </Box>
                                </Grid>
                             
                            </Grid>
                        </Box>
                        ))}
                        <hr/>
                        <br/>
                    {requestLog?.benefit_data && requestLog.benefit_data.length > 0 ? (
                        <Box key={requestLog.benefit_data.length+1} sx={{ border: '1px solid rgba(0,0,0,0.125)', px: '24px', py: '20px', marginBottom: '24px', borderRadius: '12px'}}> 
                            <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}>

                                            {/* Amount Incurred */}
                                            <Grid item xs={2}>
                                                <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption">
                                                            Amount Incurred
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                                                            {fNumber(totalAmountIncurred)}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </Grid>

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

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

                                            {/* Excess Paid* */}
                                            <Grid item xs={2}>
                                                <Grid container sx={{ borderRight: `0.5px solid ${palette.light.grey[400]}` }}>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption">
                                                            Excess Paid
                                                        </Typography>
                                                    </Grid>
                                                    <Grid item xs={12}>
                                                        <Typography variant="caption" sx={{ fontWeight: 'bold' }}>
                                                            {fNumber(totalExcessPaid)}
                                                        </Typography>
                                                    </Grid>
                                                </Grid>
                                            </Grid>
                                        </Grid>
                                    </Box>
                                </Grid>
                            
                            </Grid>
                        </Box>
                    ) 
                    : (
                        null
                    )}    
                    </Card>

                    {/* PR Buat pindahin ke componen */}
                    {/* <CardBenefit
                        requestLog={requestLog}
                    >

                    </CardBenefit> */}
                    <DialogBenefit
                        requestLog={requestLog}
                        openDialog={openDialogBenefit}
                        setOpenDialog={setDialogBenefit}
                        
                    />
                    {/* Dialog Edit */}
                    <DialogEditBenefit
                        id={idBenefitData}
                        data={BenefitConfigurationData}
                        openDialog={openDialogEditBenefit}
                        setOpenDialog={setDialogEditBenefit}
                    />

                    {/* Dialog Delete */}
                    <DialogDeleteBenfit 
                        id={idBenefitData}
                        openDialog={openDialogDeleteBenefit}
                        setOpenDialog={setDialogDeleteBenefit}
                    />

                    {/* Dialog Edit Detai; */}
                    <DialogEditFinalLOG 
                        setOpenDialog={setDialogDEditDetail}
                        requestLog={requestLog}
                        openDialog={openDialogEditDetail}
                    />
                </Grid>

                {/* Medicine */}
                <Grid item xs={12} md={12}>
                    <Card sx={{padding:2}}  >
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Medicine</Typography>
                                <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => {
                                    setDialogMedicine(true)
                                }} >
                                    <Typography variant="button" display="block">Medicine</Typography>
                                </Button>
                        </Stack>

                        {requestLog?.medicine.map((item, index) => (
                            <Grid
                                container
                                direction="row"
                                alignItems="center"
                                justifyContent="space-between"  // Menempatkan item ke sebelah kiri dan kanan
                                sx={{ marginBottom: 2 }}
                            >
                                <Typography variant='subtitle1'>{item.medicine}</Typography>
                                <Typography variant="subtitle1">Rp. {fNumber(item.price)}
                                    <IconButton size='large' color='error' onClick={() => {
                                        setIdMedicineData(item.id)
                                        setDialogDeleteMedicine(true)
                                    }}>
                                        <Delete color='error'/>
                                    </IconButton>
                                    </Typography>
                            </Grid>
                        ))}

                        <DialogMedicine
                            requestLog={requestLog}
                            openDialog={openDialogMedicine}
                            setOpenDialog={setDialogMedicine}
                        />
                        <DialogDeleteMedicine
                            id={idMedicineData}
                            openDialog={openDialogDeleteMedicine}
                            setOpenDialog={setDialogDeleteMedicine}
                        />
                    </Card>
                </Grid>

                {/* File */}
                <Grid item xs={12} md={12}>
                    <CardFile
                        requestLog={requestLog}
                    />
                </Grid>

                {requestLog?.status_final_log == 'requested' ? (
                    <Grid item xs={12} md={12}>
                    <Stack direction="row" padding={4} sx={{ justifyContent: 'space-between' }}>
                        <>
                        <div>
                            <Button
                            variant="outlined"
                            sx={{ color: '#FF4842', borderColor: '#FF4842' }}
                            onClick={() => {
                                setOpenDialogSubmit(true);
                                setApprove('declined');
                            }}
                            >
                            Decline
                            </Button>
                        </div>
                        <div>
                            <Button
                            variant="contained"
                            onClick={() => {
                                setOpenDialogSubmit(true);
                                setApprove('approved');
                            }}
                            >
                            Approve
                            </Button>
                        </div>
                        </>
                        <DialogConfirmation
                            setOpenDialog={setOpenDialogSubmit}
                            requestLog={requestLog}
                            openDialog={openDialogSubmit}
                            approve={approve}
                            ></DialogConfirmation>
                    </Stack>
                </Grid>
                ) : null}
                
            </Grid>
        </Container>
        </Page>
    );
}
