import * as Yup from 'yup';
import { yupResolver } from '@hookform/resolvers/yup';
import { NumericFormat } from "react-number-format";
import {
    Container,
    Grid,
    Stack,
    Typography,
    Card,
    Dialog,
    TableRow,
    Tab,
    TableCell,
    Collapse,
    AccordionSummary,
    AccordionDetails,
    IconButton,
    Divider,
    ButtonBase
 } from '@mui/material';
// components
import Page from '../../../components/Page';
import Iconify from '@/components/Iconify';
import { FormProvider, RHFDatepicker, RHFSelect, RHFTextField } from '@/components/hook-form';
import RHFTextFieldMoney from '@/components/hook-form/v2/RHFTextFieldMoney';
import { DatePicker, LocalizationProvider, MobileDatePicker } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
// utils
import useSettings from '../../../hooks/useSettings';
import { useFieldArray, useForm } from 'react-hook-form';
// react
import { useNavigate, useParams, useLocation } from 'react-router-dom';
import { useEffect, useState, useRef, useMemo } from 'react';
import axios from '../../../utils/axios';
import { enqueueSnackbar } from 'notistack';
// pages
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import { DetailFinalLogType } from './Model/Types';
import { fDate, fDateTimesecond } from '@/utils/formatTime';
import { Button, Autocomplete, FormHelperText} 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 { LoadingButton } from '@mui/lab';
import { makeFormData } from '@/utils/jsonToFormData';
import TextField from '@mui/material/TextField';
import { fPostFormat } from '@/utils/formatTime';
import { parse  } from 'date-fns';





// 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';
import DialogDeleteFileLog from './Components/DialogDeleteFileLog';
import DialogUploadFileFinalLog from './Components/DialogUploadFileFinalLog';
import DialogSendWa from './Components/DialogSendWa';
import { set } from 'nprogress';
import { format } from 'date-fns';



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

export default function Detail() {
    //dari hospital portal
//   const [dischargeDate, setDischargeDate] = useState<string>(format(new Date(), "yyyy MMM d HH:mm:ss"));
const [dischargeDate, setDischargeDate] = useState<Date | null>(null)


//   const [serviceOptions, setServiceOptions] = useState([
//     { value: '-', label: '-' }
// ]);
// const [specialisOptions, setSpecialisOptions] = useState([
//     { value: '-', label: '-' }
// ]);

const [serviceOptions, setServiceOptions] = useState<
{ value: string; label: string }[]
>([])

const [specialisOptions, setSpecialisOptions] = useState<
{ value: number; label: string }[]
>([])
const [serviceCode, setServiceCode] = useState<string>("");
const [idSpecialities, setIdSpecialities] = useState<number | null>(null)

const [inputDppj, setInputDppj] = useState("");
const [requestLog, setRequestLog] = useState<DetailFinalLogType>();
function submitRequestFinalLog() {
    if(dischargeDate == '')
    {
        enqueueSnackbar('Tanggal Keluar', { variant: 'warning' });
        return false;
    }
    //cek spesialis
    if(!idSpecialities)
    {
        enqueueSnackbar('Spesialis', { variant: 'warning' });
        return false;
    }
    //cek dpjp
    if(!inputDppj)
    {
        enqueueSnackbar('DPJP', { variant: 'warning' });
        return false;
    }
    setSubmitLoading(true);
    const formData = makeFormData({
    //   request_logs_id: member.id,
    //   result_files: fileHasilPenunjangs,
    //   diagnosa_files: fileDiagnosas,
    //   kondisi_files: fileKondisis,
        request_logs_id: requestLog?.id,
      discharge_date: fPostFormat(dischargeDate, 'yyyy-MM-dd HH:mm:ss'),
      service_code: serviceCode,
      spescialis_id: idSpecialities,
      dppj: inputDppj,
    });
    axios
      .post('/request-final-log', formData)
      .then((response) => {
        enqueueSnackbar(response.data.meta.message ?? 'Berhasil membuat data', { variant: 'success' });
        // handleSubmitSuccess();
        // onClose({ someData: 'example data' }, getData);
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.meta.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .then(() => {
        setSubmitLoading(false);
      });
  }
//end dari hospital portal


    const location = useLocation();
    const queryParams = new URLSearchParams(location.search);

    const navigate = useNavigate();
    const { themeStretch } = useSettings();

    const [isReversal, setIsReversal] = useState(false);
    const [submitLoading, setSubmitLoading] = useState(false);

    const defaultValues: any = {nominal : 0};
    const validationSchema = Yup.object().shape({nominal: Yup.number().typeError('Nominal harus berupa angka').required('Nominal harus diisi')})

    const methods = useForm<any>({
        resolver: yupResolver(validationSchema),
        defaultValues
    });

    const { handleSubmit, reset, watch, setValue, formState: { isDirty, isSubmitting, errors } } = methods;

    const onSubmit = async (data: any) => {
        setSubmitLoading(true);
        const formData = makeFormData({
            request_logs_id: id,
            approval_files: fileApprovals,
            nominal: data.nominal,
        });
        axios
            .post(`/customer-service/request/${id}/approval_files`, formData)
            .then((response) => {
            enqueueSnackbar('Berhasil membuat data', { variant: 'success' });

            window.location.reload()
            })
            .catch(({ response }) => {
            enqueueSnackbar('Something Went Wrong', { variant: 'error' });
            })
            .then(() => {
            setSubmitLoading(false);
            });
    }

    useEffect(() => {
        if (!requestLog?.id_member) return
        axios.get('service-member/'+ (requestLog?.id_member ?? null))
          .then((response) => {
            setServiceOptions(response.data);
        }).catch((error) => {
          console.error('Error fetching ICD options:', error);
        });

        axios.get('specialis')
          .then((response) => {
            setSpecialisOptions(response.data);
        }).catch((error) => {
          console.error('Error fetching ICD options:', error);
        });

      }, [requestLog?.id_member]);

    const updateApproval = async () => {
        setSubmitLoading(true);
        axios
            .put(`/customer-service/request/${id}`, {
            status_approval: 'approved',
            })
            .then((response) => {
            enqueueSnackbar('Berhasil Approve', { variant: 'success' });
            window.location.reload();
            })
            .catch(({ response }) => {
            enqueueSnackbar(response?.data?.message || 'Something Went Wrong', { variant: 'error' });
            })
            .finally(() => {
            setSubmitLoading(false);
        });
    };


    const updateDecline = async () => {
        setSubmitLoading(true);
        axios
            .put(`/customer-service/request/${id}`, {
            status_approval: 'declined',
            })
            .then((response) => {
            enqueueSnackbar('Berhasil Approve', { variant: 'success' });
            window.location.reload();
            })
            .catch(({ response }) => {
            enqueueSnackbar(response?.data?.message || 'Something Went Wrong', { variant: 'error' });
            })
            .finally(() => {
            setSubmitLoading(false);
        });
    }

    const { id, approval } = useParams();

    useEffect(() => {
        axios
        .get('customer-service/request/'+id)
        .then((response) => {
            setRequestLog(response.data.data)
            setIsReversal(response.data.data.is_reversal)
        })
        .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);
    const [openDialogSendWa, setDialogSendWa] = useState(false);
    const [shareLink, setShareLink] = 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);

    const total = {
        totalAmountIncurred :  totalAmountIncurred,
        totalAmountApproved :  totalAmountApprove,
        totalAmountNotApproved :  totalAmountNotApprove,
        totalExcessPaid :  totalExcessPaid,
        totalLimit : requestLog?.member_usage_benefit,
        benefit : requestLog?.benefit,
    }
    // Handle Delete File LOG
    const [pathFile, setPathFile] = useState('')
    const [dialogDeleteFIleLog, setDialogDeleteFileLog] = useState(false)

    // Handle Upload File LOG
    const [dialogUploadFileLog, setDialogUploadFileLog] = useState(false)


    const fileDiagnosaInput = useRef<HTMLInputElement>(null);
    const [fileApprovals, setFileApproval] = useState<any>([]);
    const handleDiagnosaInputChange = (event:any) => {
        if (event.target.files[0]) {
        setFileApproval([...fileApprovals, ...event.target.files]);
        } else {
        console.log('NO FILE');
        }
    };
    const removeApprovalFiles = (filesState:any, index:any) => {
        setFileApproval(
        filesState.filter((file:any, fileIndex:any) => {
            return fileIndex != index;
        })
        );
    };

    useEffect(() => {
        if (requestLog?.discharge_date) {
          setDischargeDate(
            parse(
              requestLog.discharge_date,
              'yyyy-MM-dd HH:mm:ss',
              new Date()
            )
          )
        }
      }, [requestLog?.discharge_date])
      useEffect(() => {
        if (!requestLog) return
        setServiceCode(requestLog.service_code ?? '')
        setIdSpecialities(requestLog.specialitiesID ?? null)
        setInputDppj(requestLog.dppj ?? '')
    }, [requestLog])
      const selectedService = useMemo(
        () =>
            serviceOptions.find(
            (o) => String(o.value) === String(serviceCode)
            ) || null,
        [serviceOptions, serviceCode]
        )
        console.log(serviceOptions);
        console.log(serviceCode);
        const selectedSpecialis = useMemo(
        () =>
            specialisOptions.find(
            (o) => Number(o.value) === Number(idSpecialities)
            ) || null,
        [specialisOptions, idSpecialities]
        )

    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 != 'approved' ? (
                            <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>Invoice Number</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.invoice_no ? requestLog?.invoice_no : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Billing Number</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.billing_no ? requestLog?.billing_no : '-'}</Typography>
                        </Stack>
                        <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>Type Of Member</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.type_of_member}</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>Admission Date</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.admission_date ? fDateTimesecond(requestLog?.admission_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>Spesialis</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.specialities_id ? requestLog?.specialities_id : '-'}</Typography>
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>DPJP</Typography>
                            <Typography variant='subtitle2' sx={style2} gutterBottom>{requestLog?.dppj ? requestLog?.dppj : '-'}</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.value} - {diagnosisItem.label}</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> */}
                <Grid item xs={12}>
                    <Card sx={{p:3}}>
                        <Stack direction="row" spacing={2} sx={{ width: '100%' }}>
                            {/* Kolom Tanggal Discharge */}
                            <Stack spacing={2} sx={{ flex: 1 }}>
                            <Typography variant="subtitle1">Tanggal Keluar </Typography>
                            <LocalizationProvider dateAdapter={AdapterDateFns}>
                                <DatePicker
                                label="Tanggal Keluar"
                                value={dischargeDate}
                                onChange={(newValue: any) => {
                                    setDischargeDate(newValue);
                                }}
                                inputFormat="dd-MM-yyyy HH:mm"
                                renderInput={(params) => <TextField {...params} fullWidth required />}
                                />
                            </LocalizationProvider>
                            </Stack>

                            {/* Kolom Service Type */}
                            <Stack spacing={2} sx={{ flex: 1 }}>
                            <Typography variant="subtitle1">Tipe Service </Typography>
                            {/* <Autocomplete
                                id="service_type"
                                options={serviceOptions}
                                getOptionLabel={(option) => option.label || ""}
                                value={serviceOptions.find((opt) => opt.value == serviceCode) || null}
                                onChange={(event, newValue) => {
                                setServiceCode(newValue?.value || "");
                                }}
                                renderInput={(params) => (
                                <TextField {...params} label='Tipe Service' fullWidth />
                                )}
                            /> */}
                            <Autocomplete
                                options={serviceOptions}
                                value={selectedService}
                                getOptionLabel={(o) => o.label}
                                isOptionEqualToValue={(o, v) => o.value === v.value}
                                onChange={(_, v) => setServiceCode(v?.value ?? '')}
                                renderInput={(params) => (
                                    <TextField {...params} label="Tipe Service" fullWidth />
                                )}
                                />
                            <FormHelperText style={{ color: "red" }}></FormHelperText>
                            </Stack>
                        </Stack>

                        {/* Specialist */}
                        <Stack direction="row" spacing={2}>
                            <Stack spacing={2} sx={{ width: '100%' }}>
                            <Typography variant='subtitle1'>Spesialis </Typography>
                                {/* <Autocomplete
                                id='specialities'
                                options={specialisOptions}
                                getOptionLabel={(option) => option.label || ''}
                                value={specialisOptions.find((opt) => opt.value === idSpecialities) || null}
                                onChange={(event, newValue) => {
                                    setIdSpecialities(newValue?.value || 0);
                                }}
                                renderInput={(params) => (
                                    <TextField {...params} label="Spesialis" fullWidth />
                                )}
                                /> */}
                                <Autocomplete
                                options={specialisOptions}
                                value={selectedSpecialis}
                                getOptionLabel={(o) => o.label}
                                isOptionEqualToValue={(o, v) => o.value === v.value}
                                onChange={(_, v) => setIdSpecialities(v?.value ?? null)}
                                renderInput={(params) => (
                                    <TextField {...params} label="Spesialis" fullWidth />
                                )}
                                />
                                <FormHelperText style={{ color: 'red' }}></FormHelperText>
                            </Stack>
                        </Stack>

                        <Stack direction="row" spacing={2}>
                            <Stack spacing={2} sx={{ width: '100%' }}>
                                <Typography variant='subtitle1'>DPJP </Typography>
                                <TextField
                                id='dppj'
                                variant='outlined'
                                value={inputDppj}
                                placeholder="DPJP"
                                onChange={(event) => {
                                    setInputDppj(event.target.value);
                                }}
                                fullWidth
                                />
                            </Stack>
                        </Stack>
                        <LoadingButton
                            variant="contained"
                            sx={{ marginTop: 2, p: 2, backgroundColor: '#19BBBB' }}
                            onClick={() => {
                            submitRequestFinalLog();
                            }}
                            loading={submitLoading}
                        >
                            Simpan
                        </LoadingButton>
                    </Card>
                </Grid>

                {/* Surat persetujuan Tindakan */}
                <Grid item xs={12}>
                    <Card sx={{ p: 3 }}>
                        <Stack direction="row" justifyContent="space-between" alignItems="flex-start" sx={{ mb: 3 }}>
                        <Typography variant="subtitle1" sx={{ color: '#19BBBB', fontWeight: 'bold' }}>
                            Tindakan Persetujuan
                        </Typography>
                        </Stack>

                        {!isReversal && (
                            <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
                                <Stack spacing={2}>
                                <Stack spacing={2} sx={{ mb: 3 }}>
                                    <Typography variant="body1" fontWeight="bold">
                                    Upload Tindakan Persetujuan
                                    </Typography>

                                    {fileApprovals?.map((file: any, index: number) => (
                                    <Stack
                                        key={index}
                                        direction="row"
                                        justifyContent="space-between"
                                        alignItems="center"
                                    >
                                        <Typography variant="body2" color="text.secondary">
                                        {file.name}
                                        </Typography>
                                        <Iconify
                                        icon="eva:trash-2-outline"
                                        color="darkred"
                                        sx={{ cursor: "pointer" }}
                                        onClick={() => removeApprovalFiles(fileApprovals, index)}
                                        />
                                    </Stack>
                                    ))}

                                    <ButtonBase
                                    sx={{
                                        p: 2,
                                        border: "2px dashed #F9FAFB",
                                        bgcolor: "#F4F6F8",
                                        borderRadius: 2,
                                        width: "100%",
                                        height: 60,
                                    }}
                                    onClick={() => fileDiagnosaInput.current?.click()}
                                    >
                                    <Box
                                        display="flex"
                                        alignItems="center"
                                        justifyContent="center"
                                        gap={1}
                                    >
                                        <Iconify icon="icon-park-outline:upload-one" fontSize="2rem" />
                                        <Typography variant="body2" fontWeight="bold">
                                        Upload Tindakan Persetujuan
                                        </Typography>
                                    </Box>
                                    <input
                                        type="file"
                                        ref={fileDiagnosaInput}
                                        style={{ display: "none" }}
                                        multiple
                                        onChange={handleDiagnosaInputChange}
                                        accept="application/pdf,image/*"
                                    />
                                    </ButtonBase>
                                </Stack>
                               <RHFTextFieldMoney
                                    id="nominal"
                                    name="nominal"
                                    label="Nominal"
                                    required
                                    placeholder="Nominal"
                                    value={requestLog?.nominal || 0}
                                    disabled={!!approval}
                                />

                                {/* <LoadingButton
                                    type="submit" // ✅ supaya ikut submit
                                    variant="contained"
                                    sx={{ marginTop: 2, p: 2, backgroundColor: "#19BBBB" }}
                                    loading={false}
                                >
                                    Simpan
                                </LoadingButton> */}
                                <Stack direction="row" spacing={2} sx={{ mt: 6 }}>
                                {approval ? (
                                    <>
                                        <Box sx={{ flexGrow: 1 }} />
                                        {/* GRUP TOMBOL DI KANAN */}
                                        {requestLog?.status_approval !== 'approved' && (
                                        <Stack direction="row" spacing={1.5} mt={2}>
                                            <Button
                                            color="error"
                                            variant="outlined"
                                            size="small"
                                            onClick={updateDecline}
                                            >
                                            Decline
                                            </Button>

                                            <Button
                                            variant="contained"
                                            size="small"
                                            color="primary"
                                            onClick={updateApproval}
                                            >
                                            Approve
                                            </Button>
                                        </Stack>
                                        )}
                                    </>
                                    ) : (
                                    <>
                                        {/* TOMBOL SIMPAN DI KIRI */}
                                        <LoadingButton
                                        type="submit"
                                        variant="contained"
                                        sx={{ p: 2, backgroundColor: "#19BBBB" }}
                                        loading={false}
                                        size="small"
                                        >
                                        Simpan
                                        </LoadingButton>

                                        {/* Ini adalah spacer untuk mendorong tombol berikutnya ke kanan */}
                                        <Box sx={{ flexGrow: 1 }} />

                                        {/* GRUP TOMBOL DI KANAN */}
                                        <Stack direction="row" spacing={1.5} mt={2}>
                                        <Button
                                            variant="contained"
                                            size="small"
                                            sx={{ p: 2, backgroundColor: "#19BBBB" }}
                                            onClick={() => {
                                            setDialogSendWa(true);
                                            setShareLink(false);
                                            }}
                                        >
                                            Kirim (WA Chatbot)
                                        </Button>

                                        <Button
                                            variant="contained"
                                            size="small"
                                            sx={{ p: 2, backgroundColor: "#19BBBB" }}
                                            onClick={() => {
                                            setDialogSendWa(true);
                                            setShareLink(true);
                                            }}
                                        >
                                            Share Link
                                        </Button>
                                        </Stack>
                                    </>
                                    )}
                                </Stack>

                            </Stack>
                        </FormProvider>

                        )}

                        {/* FILE YANG SUDAH TERUPLOAD */}
                        {requestLog?.files
                        ?.filter((document) => document.type === 'approval')
                        ?.map((documentType, index) => (
                        <Stack
                            key={index}
                            direction="row"
                            justifyContent="space-between"
                            alignItems="center"
                            sx={{ mt: 2 }}
                        >
                            <a
                            href={documentType.url}
                            target="_blank"
                            rel="noopener noreferrer"
                            style={{ textDecoration: 'none', color: '#19BBBB' }}
                            >
                            <Typography variant="body2">
                                {documentType.original_name || '-'}
                            </Typography>
                            </a>

                            {!isReversal && (
                            <IconButton
                                onClick={() => {
                                setDialogDeleteFileLog(true);
                                setPathFile(documentType.path);
                                }}
                                size="small"
                            >
                                <Delete color="error" fontSize="small" />
                            </IconButton>
                            )}
                        </Stack>
                        ))}

                        {/* DIALOG */}
                        <DialogDeleteFileLog
                        id={requestLog?.id}
                        path={pathFile}
                        setOpenDialog={setDialogDeleteFileLog}
                        openDialog={dialogDeleteFIleLog}
                        />

                        <DialogUploadFileFinalLog
                        id={requestLog?.id}
                        setOpenDialog={setDialogUploadFileLog}
                        openDialog={dialogUploadFileLog}
                        />
                    </Card>
                </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>
                                {
                                    !isReversal ? (
                                        <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}}  onClick={() => {
                                            setDialogBenefit(true);
                                        }} >
                                            <Typography variant="button" display="block">Benefit</Typography>
                                        </Button>
                                    ) : null
                                }
                        </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>
                                        {
                                            !isReversal ? (
                                                <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>
                                            ) : null
                                        }
                                    </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}
                        total={total}
                    />

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

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

                    <DialogSendWa
                        requestLog={requestLog}
                        openDialog={openDialogSendWa}
                        setOpenDialog={setDialogSendWa}
                        shareLink={shareLink}

                    />


                </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}>
                    <Card sx={{padding:2}}  >
                        <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{marginBottom: 4}}>
                            <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                                <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Files </Typography>
                            </Stack>
                            { !isReversal ? (
                                <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                                    <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => {
                                        setDialogUploadFileLog(true)
                                    }} >
                                        <Typography variant="button" display="block">Files</Typography>
                                    </Button>
                                </Stack>
                            ) : null }

                        </Stack>
                        {requestLog?.files
                        ?.filter((document) => document.type !== 'approval')
                        ?.map((documentType, index) => (
                            <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{marginBottom: 2}} key={index}>
                                <Stack direction="column" spacing={2} >
                                <a
                                href={documentType.url}
                                    style={{ cursor: 'pointer', textDecoration: 'none', color: '#19BBBB' }}
                                    target="_blank"
                                >
                                    <Typography variant="body2" gutterBottom>{documentType.original_name ? documentType.original_name : '-'}</Typography>
                                </a>
                                </Stack>
                                { !isReversal ? (
                                    <Stack direction="column" spacing={2}>
                                        <IconButton onClick={() => {
                                            setDialogDeleteFileLog(true)
                                            setPathFile(documentType.path)
                                        }} aria-label="delete" size="small" sx={{ marginLeft: 'auto' }}>
                                        <Delete color='error' fontSize="small" />
                                        </IconButton>
                                    </Stack>
                                ) : null }

                            </Stack>
                        ))}

                        <DialogDeleteFileLog
                            id={requestLog?.id}
                            path={pathFile}
                            setOpenDialog={setDialogDeleteFileLog}
                            openDialog={dialogDeleteFIleLog}
                        />

                        <DialogUploadFileFinalLog
                            id={requestLog?.id}
                            setOpenDialog={setDialogUploadFileLog}
                            openDialog={dialogUploadFileLog}
                        />
                    </Card>
                </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={() => {

                            }}
                            >
                            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>
    );
}
