import * as Yup from 'yup';
// mui
import {
    Container,
    Grid,
    Stack,
    Typography,
    Card,
    TextField,
    Divider,
    ButtonBase,
    Box,
    IconButton,
    Autocomplete,
    FormControl,
    InputLabel,
    Select,
    FormHelperText,
    MenuItem } 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 { format } from 'date-fns';
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';
import { Dialog, DialogTitle, DialogContent, DialogActions } from '@mui/material';
import CloseIcon from '@mui/icons-material/Close';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import { DatePicker, LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import { fPostFormat } from '@/utils/formatTime';
import { fDate, fDateTime } from '../../utils/formatTime';
import ListItemText from '@mui/material/ListItemText';
import EditOutlinedIcon from '@mui/icons-material/EditOutlined';
import TableMoreMenu from '@/components/table/TableMoreMenu';

import { enqueueSnackbar } from 'notistack';
import BenefitConfigurationList from './components/BenefitConfigurationList';
import { map } from 'lodash';


import { FormProvider, RHFDatepicker, RHFSelect, RHFTextField } from '@/components/hook-form';
import { useFieldArray, useForm } from 'react-hook-form';
import { ClaimHistoryCare } from '@/@types/claims';
import { yupResolver } from '@hookform/resolvers/yup';
import { LoadingButton } from '@mui/lab';
import { Delete, Edit, EditOffOutlined, EditTwoTone, LoopOutlined, RefreshOutlined } from '@mui/icons-material';
import { fDateOnly, fDateTimeSuffix } from '@/utils/formatTime';
import Label from '@/components/Label';
import RHFAutocomplete from '../../components/hook-form/RHFAutocompleteV2';

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

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

    const navigate = useNavigate();
    const { themeStretch } = useSettings();
    const [customerData, setCustomerData] = useState(null);
    const [documentData, setDocumentData] = useState(null);
    const [requestDocumentData, setRequestDocumentData] = useState(null);
    const [serviceData, setServiceData] = useState(null);
    const [serviceBenefitData, setServiceBenefitData] = useState(null);
    const [dataDialog, setDataDialog] = useState(null);

    const { id } = useParams();

    useEffect(() => {
        axios
        .get('/claims/detail/'+id)
        .then((response) => {
            setCustomerData(response.data.data.customer_data);
            setDocumentData(response.data.data.documents);
            setRequestDocumentData(response.data.data.request_documents);
            setServiceData(response.data.data.claim_services);
            setServiceBenefitData(response.data.data.claim_service_benefits);
            setDataDialog(response.data.data.dialog_submits);
        })
        .catch((error) => {
            console.error(error);
        });
        getService();

    }, []);

    function toTitleCase(str: string | null) {
        return str.replace(/\w\S*/g, function(txt) {
            return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
        });
    }

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

    //Request
    const [openDialogRequest, setOpenDialogRequest] = useState(false);
    const handleCloseDialogRequest = () => {
        setOpenDialogRequest(false);
    }

    const [conditionChecked, setConditionChecked] = useState(true);
    const [diagnosisChecked, setDiagnosisChecked] = useState(false);
    const [supportingResultChecked, setSupportingResultChecked] = useState(false);

    const handleConditionChange = (event) => {
        setConditionChecked(event.target.checked);
    };

    const handleDiagnosisChange = (event) => {
        setDiagnosisChecked(event.target.checked);
    };

    const handleSupportingResultChange = (event) => {
        setSupportingResultChecked(event.target.checked);
    };

    const [noteField, setNoteField] = useState('');
    const [noteFieldError, setNoteFieldError] = useState('');
    const isRequiredFieldsFilled = () => {
        return noteField.trim() !== '';
    };

    const handelRequestDocument = () => {
        const dataForm = {
            claim_id: id,
            condition: conditionChecked,
            diagnosis: diagnosisChecked,
            result: supportingResultChecked,
            note: noteField,
        }
        axios
        .post('/claims/request-documents', dataForm)
        .then((response) => {
            enqueueSnackbar('Success Request Document', { variant: 'success' });
            setOpenDialogRequest(false);
            window.location.reload();
        })
        .catch((error) => {
            enqueueSnackbar('Something Went Wrong', { variant: 'error' });
        })
    }

    /*---------------------- Handle History Hospital Care ----------------------------*/

    interface FormValuesProps extends Partial<ClaimHistoryCare> {
        taxes: boolean;
        inStock: boolean;
    }


    /**------------- Handle History Hospital Care ---------------------*/
    const [currentClaimHistoryCare, setCurrentClaimHistoryCare] = useState(null);
    const [organization, setOrganization] = useState([]); // Untuk Hospital
    const [doctor, setDoctor] = useState([]); // Untuk Docter
    const [corporate_id, setCorporateId] = useState(null); // Untuk Corporate
    const [main_diagnosis, setMainDiagnosis] = useState([]); // Untuk Main diagnosis
    const [claimHistoryId,setClaimHistoryId] = useState<number|null>(null); // Untuk edit Claim History

    const [carehistory, setCarehistory] = useState<ClaimHistoryCare|null>(null);
    const [isEdit,setEdit] = useState(false);
    const [service_code, setServiceType] = useState<ClaimHistoryCare|null>();
    const handleCloseDialogUpdate = () => {
        setOpenDialogRequest(false);
        reset()
    }

    useEffect( () => {
        axios
        .get('claims/'+id)
        .then((response) => {
            setCorporateId(response.data.data.corporate_id)
            setCurrentClaimHistoryCare(response.data.data.history_hospital_care)
            setServiceType(response.data.data.service_code)
            
        })
    }, [id])

    useEffect( () => {
        // setMainDiagnosis
        axios
        .get(`corporates/${corporate_id}/diagnosis`)
        .then((response) => {
           setMainDiagnosis(response.data.data)
        })

        // setOrganization atau hospital atau location
        axios
        .get(`corporates/${corporate_id}/hospitals`)
        .then((response) => {
            setOrganization(response.data.data)
        })

    }, [corporate_id])

   useEffect( () => {
       // setCarehistory
       if (claimHistoryId != null) {
           axios
           .get('/claims/carehistory/'+claimHistoryId)
           .then((response) => {
               reset({
                   service_code: response.data.data.service_code,
                   admission_date: response.data.data.admission_date,
                   discharge_date: response.data.data.discharge_date,
                   organization_id: response.data.data.organization_id,
                   practitioner_id: response.data.data.practitioner_id,
                   medical_record_number: response.data.data.medical_record_number,
                   symptoms: response.data.data.symptoms,
                   sign: response.data.data.sign,
                   main_diagnosis_id: response.data.data.main_diagnosis_id,
                   secondary_diagnosis_id: response.data.data.secondary_diagnosis.map((row: any) => ({
                        value: {
                            id: row.id,
                            name: row.icd.name
                        }
                   }))
               });

               setCarehistory(response.data.data);
           })
           .catch((error) => {
               console.error(error);
           });
            // setDoctor atau practioner
            axios
            .get('/doctors?search=&organization_id='+values.organization_id)
            .then((response) => {
                setDoctor(response.data.data);
                
            })
            .catch((error) => {
                console.error(error);
            });

            // setMainDiagnosis
            axios
            .get(`corporates/${corporate_id}/diagnosis`)
            .then((response) => {
            setMainDiagnosis(response.data.data)
            })

            // setOrganization atau hospital atau location
            axios
            .get(`corporates/${corporate_id}/hospitals`)
            .then((response) => {
                setOrganization(response.data.data)
            })
       }

   }, [claimHistoryId])

   useEffect( () => {
        reset(defaultValues);
   }, [isEdit])


    const [openDialogHospitalCare, setOpenHospitalCare] = useState(false);

    const handleCloseDialogHospitalCare = () => {
        setEdit(false)
        setOpenHospitalCare(false);
        setClaimHistoryId(null)
        reset();
    }

    const [openDialogApproval, setOpenDialogApproval] = useState(false);

    const handleCloseDialogApprove = () => {
        setOpenDialogApproval(false);
        setEdit(false)
        setClaimHistoryId(null);
        reset();
    }

    /* Handle For Approve Claim */
    const handleApproveClaim = (id: number|null, claim_id: number|null) =>{
        // let data = {
        //     status: 1
        // }
        // axios.post(`/claims/carehistory/${id}/approval`, data);
        //     setOpenDialogApproval(false)
        //     enqueueSnackbar(
        //         'Claim Approve Successfully!',
        //         { variant: 'success' }
        //     );
        //     window.location.reload();

        const dataForm = {
            status: 1,
            claim_id: id 
        }
        axios
        .post(`/claims/carehistory/approval`, dataForm)
        .then((response) => {
            enqueueSnackbar('Claim Approve Successfully!', { variant: 'success' });
            setOpenDialogApproval(false);
            window.location.reload();
        })
        .catch((error) => {
            enqueueSnackbar('Something Went Wrong', { variant: 'error' });
        })

    }

    // Handle Location Change
    const handleLocationChange = (organization_id:number) => {
        // if (newValue) {
            const selectedValue = organization_id;
            setValue('organization_id', selectedValue);
            // let data = {
            //     ...values,
            //     practitioner_id: 0
            // }
            // reset(data)

            axios
                .get('/doctors?search=&organization_id=' + selectedValue)
                .then((response) => {
                    setDoctor(response.data.data);
                })
                .catch((error) => {
                    console.error(error);
                });
        // }
    }

    const handleDoctorChange = (event, newValue) => {
        if (newValue) {
            const selectedValue = newValue.id;
            setValue('practitioner_id', selectedValue);
        }
    }

    const handleMainDiagnosisChange = (event, newValue) => {
        if (newValue) {
            const selectedValue = newValue.id;
            setValue('main_diagnosis_id', selectedValue);
        }
    }

    const defaultValues = useMemo(
        () => ({
            service_code: service_code,
            secondary_diagnosis_id: [{
                value: {
                    name: "",
                    value: 0
                }
             }],
             admission_date: isEdit ? carehistory?.admission_date : '',
             discharge_date: isEdit ? carehistory?.discharge_date : '',
             organization_id: isEdit ? carehistory?.organization_id : '',
             practitioner_id: isEdit ? carehistory?.practitioner_id : '',
             medical_record_number: isEdit ? carehistory?.medical_record_number : '',
             symptoms: isEdit ? carehistory?.symptoms : '',
             sign: isEdit ? carehistory?.sign : '',
             main_diagnosis_id: isEdit ? carehistory?.main_diagnosis_id : 0,
        }),
        [service_code]
    )

    let NewClaimHistoryCareSchema = Yup.object().shape({
        service_code: Yup.string().required('Name is required'),
        // admission_date: Yup.date().required('Admisision Date is required'),
        // discharge_date: Yup.date().required('Discharge Date is required'),
        // organization_id: Yup.number().required('Location is required'),
        // practitioner_id: Yup.number().required('Doctor is required'),
        // medical_record_number: Yup.string().required('Medical Record is required'),
        // symptoms: Yup.string().required('Symptoms is required'),
        // sign: Yup.string().required('Sign is required'),
        // main_diagnosis_id: Yup.number().required('Main Diagnosis is required'),
    });

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

    const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    resetField,
    formState: { isSubmitting },
    } = methods;

    const values = watch();
    const valueOfLocation = organization.find((row) => row.organization_id === values.organization_id)

    const {fields, append, remove} = useFieldArray<FormValuesProps>({name: "secondary_diagnosis_id", control})

    const onSubmit = async (data: FormValuesProps) => {
        if (isEdit){
            let newData = {
                service_code: data.service_code,
                admission_date: data.admission_date ? fDateOnly(data.admission_date) : null,
                discharge_date: data.discharge_date ? fDateOnly(data.discharge_date) : null,
                organization_id: data.organization_id,
                practitioner_id: data.practitioner_id,
                medical_record_number: data.medical_record_number,
                symptoms: data.symptoms,
                sign: data.sign,
                secondary_diagnosis_id: data.secondary_diagnosis_id ? data.secondary_diagnosis_id.map((row) => row.value.id) : null,
                main_diagnosis_id: data.main_diagnosis_id,
            }

            const response:any = await axios.post(`/claims/carehistory/${claimHistoryId}/update`, newData);
            // if (response.status == 'success'){
                setOpenHospitalCare(false)
                enqueueSnackbar(
                    'Claim Update Successfully!',
                   { variant: 'success' }
                 );
                 navigate('/claims/detail/'+id);
                 window.location.reload();

            // }
        } else {
            let newData = {
                service_code: data.service_code,
                admission_date: data.admission_date ? fDateOnly(data.admission_date) : null,
                discharge_date: data.discharge_date ? fDateOnly(data.discharge_date) : null,
                organization_id: data.organization_id,
                practitioner_id: data.practitioner_id,
                medical_record_number: data.medical_record_number,
                symptoms: data.symptoms,
                sign: data.sign,
                secondary_diagnosis_id: data.secondary_diagnosis_id ? data.secondary_diagnosis_id.map((row) => row.value.id) : null,
                main_diagnosis_id: data.main_diagnosis_id,

            }


            const response:any = await axios.post(`/claims/${id}/carehistory`, newData);
            // if (response.status == 'success'){
                setOpenHospitalCare(false)
                enqueueSnackbar(
                    'Claim Insert Successfully!',
                   { variant: 'success' }
                 );
                 navigate('/claims/detail/'+id);
                 window.location.reload();
            // }

        }

        reset();
    }

    function secondaryDiagnosisOption() {
        return fields.map((item, index) => {
            return (
            <Card key={item.id} sx={{ paddingX: 2, paddingY: 2, marginBottom: 2 }}>
               <Typography variant='subtitle1' marginBottom={2}>{`#${index+1}`}</Typography>
               <Box sx={{display: "flex", placeContent: 'space-between', placeItems: "center", gap: 2}}>
               <Box sx={{width: "100%"}}>
               <RHFAutocomplete
                name={`secondary_diagnosis_id.${index}.value`}
                options={main_diagnosis}
                disableClearable
                freeSolo
                getOptionLabel={(opt) => opt.name}
                isOptionEqualToValue={(opt, val) => opt.name === val.name}
                label='Comparative Diagnosis (ICD-X)'
               />
               </Box>
               <IconButton color='error' onClick={() => remove(index)}>
                <Delete />
               </IconButton>
               </Box>
             </Card>
            )
        })
    }

    function handleNewHospitalCare() {
        setEdit(false);
        setOpenHospitalCare(true);
        reset(defaultValues);
    }

    function handleEditHospitalCare(id: number) {
        setClaimHistoryId(id);
        setEdit(true);
        setOpenHospitalCare(true);
        reset(defaultValues);
    }

    function handleUpdateHospitalCare(id: number) {
        setOpenHospitalCare(false);
        setClaimHistoryId(id);
        setEdit(false);
        setOpenDialogApproval(true);
    }

    //Service
    const [openDialogService, setOpenDialogService] = useState(false);
    const handleCloseDialogService = () => {
        setOpenDialogService(false);
    }
    const handleConditionChangeService = (event) => {
        const selectedItem = event.target.value;

        if (valBenefitNames.includes(selectedItem)) {
            // Item is already selected, remove it
            setValBenefitNames(valBenefitNames.filter(item => item !== selectedItem));
        } else {
            // Item is not selected, add it
            setValBenefitNames([...valBenefitNames, selectedItem]);
        }
    };

    //Data
    const [serviceTypeData, setServiceTypeData] = useState(null);
    const [benefitNameData, setBenefitNameData] = useState(null);
    const [hospitalData, setHospitalData] = useState(null);
    //Field
    const currentDate = new Date();
    const formattedCurrentDate = format(currentDate, 'dd MMM yyyy');
    //Date Addmissions
    const [dateAd, setDateAd] = useState(currentDate);
    //Date Discharge
    const [dateDis, setDateDis] = useState(currentDate);
    //Service Type
    const [valServiceType, setValServiceType] = useState('');
    const [valServiceTypeError, setValServiceTypeError] = useState('');
    //Benefit Name
    const [valBenefitNames, setValBenefitNames] = useState([]);
    const [valBenefitNameError, setValBenefitNameError] = useState('');
    //Hospital
    const [valHospital, setValHospital] = useState('');
    const [valHospitalError, setValHospitalError] = useState('');
    //txt name
    const [txtName, setTxtName] =  useState('Add Service');
    //flag add or edit service
    const [flagAddService, setFlagAddService] = useState('add');
    //id claim_services
    const [idService, setIdService] = useState(null);


    const isRequiredFieldsServiceType = () => {
        return dateAd !== '' && dateDis !== '' && valServiceType !== '' && valBenefitNames.length > 0 && valHospital !== '';
    };

    const getService = async () => {
        try {
            const response = await axios.get('/claims/get-services/' + id);
            setServiceTypeData(response.data.data.service_type);
            setValServiceType(response.data.data.service_type[0].id);
            setBenefitNameData(response.data.data.benefit_name);
            setHospitalData(response.data.data.hospital);
            await Promise.all([
                setServiceTypeData(response.data.data.service_type),
                setBenefitNameData(response.data.data.benefit_name),
                setHospitalData(response.data.data.hospital),
            ]);

        } catch (error) {
        }
    }


    const handleAddService = async () => {
        setTxtName('Add Service');
        setFlagAddService('add');
        setOpenDialogService(true);
    }

    const handleEditService = async () => {
        setDateAd(serviceData.addmission_date);
        setDateDis(serviceData.discharge_date);
        setIdService(serviceData.id);

        setOpenDialogService(true);
        setTxtName('Edit Service');
        setFlagAddService('edit');

        if (serviceTypeData) {
            setValServiceType(serviceData.service_id);
            setValHospital(serviceData.hospital_id);
            setValBenefitNames(serviceBenefitData.benefit_id);
        }
    }

    const handelSaveServiceType = () => {
        const dateAdd = dateAd ? fPostFormat(dateAd, 'yyyy-MM-dd') : null;
        const dateDisc = dateDis ? fPostFormat(dateDis, 'yyyy-MM-dd') : null;
        const data = {
            flagAddService : flagAddService,
            idService: idService,
            claim_request_id: id,
            dateAdd : dateAdd,
            dateDisc : dateDisc,
            serviceType : valServiceType,
            benefitName : valBenefitNames,
            hospital : valHospital
        };
        axios
        .post('/claims/save-services', data)
        .then((response) => {
            enqueueSnackbar('Success '+(flagAddService == 'add' ? 'Add' : 'Edit')+' Service', { variant: 'success' });
            handleCloseDialogService();
            window.location.reload();
        })
        .catch((error) => {
            enqueueSnackbar('Something Went Wrong', { variant: 'error' });
        })
    }

    const [openDialogSubmit, setOpenDialogSubmit] = useState(false);
    const handleCloseDialogSubmit = () => {
        setOpenDialogSubmit(false);
    }

    const [decline, setDeclaine] = useState('');

    const handleSubmitData = () => {
        //approve or decline
        axios
        .post('claims/'+id+'/'+decline)
        .then((response) => {
            enqueueSnackbar('Success '+toTitleCase(decline)+' Claim Request', { variant: 'success' });
            setOpenDialogSubmit(false);
            window.location.reload();
            
        })
        .catch(({ response }) => {
            enqueueSnackbar(response.data.message ?? 'Something went wrong!', { variant: 'error' });
        });

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

    };

    const handelDownloadLog = () => {
        axios
        .get(`final-log/${id}`, {
            responseType: 'blob',
        })
        .then((response) => {
            window.open(URL.createObjectURL(response.data));
        })
        .catch((response) => {
            enqueueSnackbar(response.message, { variant: 'error' });
        });
    }

    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}}>{(customerData && customerData.code ? customerData.code : '')}</Typography>
            {customerData ? (
                <Stack direction="column" spacing={1} alignItems="center" sx={{marginLeft:'auto'}}>
                    <Stack direction="row" spacing={2}>
                        <Typography variant="body2" sx={{color: '#757575'}}>Status</Typography>
                        <Typography variant="body2" fontWeight="bold">{(customerData && customerData.status) ? toTitleCase(customerData.status) : ''}</Typography>
                    </Stack>
                    <Stack direction="row" spacing={2}>
                        <Typography variant="body2" sx={{color: '#757575'}}>Submission Date</Typography>
                        <Typography variant="body2" fontWeight="bold">{(customerData && customerData.submission_date) ? format(new Date(customerData.submission_date), "d MMM yyyy") : ''}</Typography>
                    </Stack>
                </Stack>
            ) : ''}
            </Stack>
            <Grid container spacing={2}>
            {customerData ? (
                <Grid item xs={12} md={12}>
                <Card sx={{padding:2}}  >
                    <Typography variant='subtitle1' sx={{color: '#19BBBB', marginBottom: 4}} gutterBottom>Summary of Customer Data</Typography>
                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                        <Typography variant='subtitle2' sx={style1} gutterBottom>Full Name</Typography>
                        <Typography variant='subtitle2' sx={style2} gutterBottom>{customerData.name}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                        <Typography variant='subtitle2' sx={style1} gutterBottom>Policy Number</Typography>
                        <Typography variant='subtitle2' sx={style2} gutterBottom>{customerData.payor_id}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                        <Typography variant='subtitle2' sx={style1} gutterBottom>Member ID</Typography>
                        <Typography variant='subtitle2' sx={style2} gutterBottom>{customerData.member_id}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                        <Typography variant='subtitle2' sx={style1} gutterBottom>Claim Type</Typography>
                        <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(customerData.payment_type)}</Typography>
                    </Stack>
                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                        <Typography variant='subtitle2' sx={style1} gutterBottom>Corporate Name</Typography>
                        <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(customerData.coporate_name)}</Typography>
                    </Stack>
                </Card>
                </Grid>
            ) : ''}
            {documentData ? (
                <Grid item xs={12}>
                    <Card sx={{padding: 2}}>
                        {customerData?.status === 'received' ? (
                            <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                                <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Additional Documents</Typography>
                                <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => setOpenDialogRequest(true)}>
                                    <Typography variant="button" display="block">Request Document</Typography>
                                </Button>
                            </Stack>
                        ) : ''}
                        <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                            {documentData?.map((documentType, index) => (
                                <Stack direction="column" spacing={2} key={index}>
                                    <Typography variant="Subtitle2" gutterBottom>
                                    {documentType.type === 'claim-diagnosis' ?
                                        'Diagnosis'
                                    : documentType.type === 'claim-kondisi' ?
                                        'Condition'
                                    : documentType.type === 'claim-result' ?
                                        'Supporting Result'
                                    : documentType.type === 'claim-invoice' ?
                                        'Invoice'
                                    : ''}
                                    </Typography>
                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                    <InsertDriveFileIcon />
                                    <a
                                        href={documentType.path}
                                        style={{ cursor: 'pointer', textDecoration: 'underline', color: '#19BBBB' }}
                                        target="_blank"
                                    >
                                        <Typography variant="body2" gutterBottom>{documentType.original_name ? documentType.original_name : '-'}</Typography>
                                    </a>
                                    </Stack>
                                </Stack>
                            ))}
                        </Stack>
                        {requestDocumentData && requestDocumentData.length > 0 ? (
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Request Documents</Typography>
                        ) : ''}
                        <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                            {requestDocumentData?.map((documentType, index) => (
                                <Stack direction="column" spacing={2} key={index}>

                                    <Stack direction="row" spacing={1} sx={{color: '#637381'}}>
                                    <InsertDriveFileIcon />
                                    <Typography variant="body2" gutterBottom>
                                    {documentType.type === 'claim-diagnosis' ?
                                        'Diagnosis'
                                    : documentType.type === 'claim-kondisi' ?
                                        'Condition'
                                    : documentType.type === 'claim-result' ?
                                        'Supporting Result'
                                    : documentType.type === 'claim-invoice' ?
                                        'Invoice'
                                    : ''}
                                    </Typography>
                                    </Stack>
                                </Stack>
                            ))}
                        </Stack>
                        {/* Dialog Request Documents */}
                        <Dialog open={openDialogRequest} onClose={handleCloseDialogRequest} fullWidth={true} >
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">Request Document</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogRequest}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                            <Stack spacing={2} sx={{marginTop: 2, padding: 2}}>
                                <FormGroup>
                                    <FormControlLabel
                                        control={<Checkbox checked={conditionChecked} onChange={handleConditionChange} />}
                                        label="Condition Document"
                                    />
                                    <FormControlLabel
                                        control={<Checkbox checked={diagnosisChecked} onChange={handleDiagnosisChange} />}
                                        label="Diagnosis Document"
                                    />
                                    <FormControlLabel
                                        control={<Checkbox checked={supportingResultChecked} onChange={handleSupportingResultChange} />}
                                        label="Supporting Result Document"
                                    />
                                </FormGroup>
                                <Typography variant="Subtitle1" sx={{fontWeight: 'bold'}}>
                                    Notes*
                                </Typography>
                                <TextField
                                    label="Detail Notes"
                                    value={noteField ? noteField : ''}
                                    onChange={(e) =>{
                                    setNoteField(e.target.value);
                                    setNoteFieldError(e.target.value.trim() === '' ? 'This field is required' : '');
                                    }}
                                    fullWidth
                                    inputProps={{ maxLength: 50 }}
                                    error={!!noteFieldError}
                                    helperText={noteFieldError}
                                />
                            </Stack>
                            </DialogContent>
                            <DialogActions>
                            <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialogRequest}>Cancel</Button>
                            <Button sx={{backgroundColor: '#19BBBB'}} variant="contained" disabled={!isRequiredFieldsFilled()} onClick={() => handelRequestDocument()}>Request</Button>
                            </DialogActions>
                        </Dialog>
                    </Card>
                </Grid>
            ): ''}
                <Grid item xs={12}>
                    <Card sx={{padding: 3}}>
                      
                            <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                                <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>History of Hospital Care</Typography>
                                    {customerData?.status === 'received' ? (
                                        <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={handleNewHospitalCare}>
                                            <Typography variant="button" display="block">History</Typography>
                                        </Button>
                                    ) : ''}
                            </Stack>
                       
                        <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                            {currentClaimHistoryCare?.map((claimHistoryCare, index) =>
                                claimHistoryCare.status === 0 ? (
                                    <Grid item xs={12} md={12} key={index}> {/* Tambahkan key untuk setiap elemen dalam loop */}
                                    <Card sx={{padding: 2}}>
                                        {customerData?.status === 'received' ? (
                                            <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{marginBottom: 4}}>
                                                <Label variant="outlined" color='primary'  >
                                                    <Typography variant="button" display="block">{claimHistoryCare.service_code = 'OP' ? 'Outpatient' : 'Inpatient'}</Typography>
                                                </Label>
                                                <TableMoreMenu actions={
                                                    <>
                                                    <MenuItem onClick={() => handleEditHospitalCare(claimHistoryCare.id)}>
                                                    <EditTwoTone />Edit
                                                    </MenuItem>
                                                    <MenuItem onClick={() => handleUpdateHospitalCare(claimHistoryCare.id)}>
                                                    <LoopOutlined />Update Status
                                                    </MenuItem>
                                                    </>
                                                }/>
                                            </Stack>
                                        ) : ''}
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Admission Date :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ fDate(claimHistoryCare.admission_date)}</Typography> {/* Perbaikan typo di 'admission_date' */}
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Discharge Date :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ fDate(claimHistoryCare.discharge_date)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Location :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(claimHistoryCare.organization?.name)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Doctor :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(claimHistoryCare.practitioner?.code)} - {claimHistoryCare.person?.name}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Status :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{claimHistoryCare.status == 0 ? 'Pending' : 'Approv'}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Diagnosis :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>#{index+1} {claimHistoryCare.icd?.code} - {claimHistoryCare.icd?.name}</Typography>
                                        </Stack>
                                    </Card>
                                    </Grid>
                                ) : null
                            )}
                        </Stack>

                        {/* Dialog for input and update */}
                        <Dialog open={openDialogHospitalCare} onClose={handleCloseDialogHospitalCare} fullWidth={true} maxWidth={'xl'}>
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">{isEdit ? 'Update' : 'Add'} History of Hospital Care</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogHospitalCare}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                            <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
                                <Stack spacing={2} sx={{marginTop: 2, padding: 2}}>
                                    <Grid container spacing={2}>
                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' marginBottom={1}>Service Code</Typography>
                                            <RHFSelect
                                                name="service_code"
                                                label="Service Code"
                                                placeholder="Service Code"
                                                disabled
                                            >
                                                <option value="" />
                                                <option value="IP">Inpatient</option>
                                                <option value="OP">Outpatient</option>
                                            </RHFSelect>
                                        </Grid>
                                        <Grid item xs={6} md={6}>
                                            <Typography variant="subtitle1" sx={{marginBottom: '10px'}}>Admission Date*</Typography>
                                            <RHFDatepicker name="admission_date" label="Admission Date" required/>
                                        </Grid>
                                        <Grid item xs={6} md={6}>
                                            <Typography variant="subtitle1" sx={{marginBottom: '10px'}}>Discharge Date*</Typography>
                                            <RHFDatepicker name="discharge_date" label="Discharge Date" required/>
                                        </Grid>
                                        {/* Location */}
                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' marginBottom={1}>Location*</Typography>
                                            <Autocomplete

                                                id="combo-box-demo"
                                                options={organization}
                                                fullWidth
                                                getOptionLabel={(option) => {
                                                    return option.name ?? false
                                                }}
                                                isOptionEqualToValue={(option, value) =>{
                                                    return option.organization_id == value.organization_id
                                                }}

                                                onChange={(e, selectedOption) => {
                                                    if (selectedOption) {
                                                        const selectedOrganizationId = selectedOption.organization_id;
                                                        handleLocationChange(selectedOrganizationId);
                                                    }
                                                  }}
                                                // value={organization.find(row => row.organization_id == values.organization_id)}
                                                value={valueOfLocation ?? null}

                                                renderInput={(params) => (
                                                    <RHFTextField
                                                      name="organization_id_test"
                                                      {...params}
                                                      label="Location"
                                                      variant="outlined"
                                                      fullWidth
                                                      required
                                                    />
                                                  )}
                                            />
                                        </Grid>

                                        {/* Dokter */}
                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' marginBottom={1}>Doctor*</Typography>
                                            <Autocomplete
                                                id="combo-box-demo"
                                                options={doctor}
                                                limitTags={1}
                                                fullWidth
                                                getOptionLabel={(option) => {
                                                    return option.name ?? false
                                                }}
                                                isOptionEqualToValue={(option, value) =>{
                                                    return option.id === value.id
                                                }}

                                                value={doctor.find(row => row.id == values.practitioner_id) ?? null}

                                                onChange={handleDoctorChange}
                                                renderInput={(params) => (
                                                <RHFTextField
                                                    name='practitioner_id'
                                                    {...params}
                                                    label="Doctor"
                                                    variant="outlined"
                                                    fullWidth
                                                    required
                                                />
                                                )}
                                            />
                                        </Grid>


                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' color="#637381" marginBottom={1}>Medical Record Number*</Typography>
                                            <RHFTextField name="medical_record_number" label="Medical Record Number" required placeholder='Medical Record Number' />
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' color="#637381" marginBottom={1}>Symptoms*</Typography>
                                            <RHFTextField name="symptoms" label="Symptoms" placeholder='Symptoms' required/>
                                        </Grid>
                                        <Grid item xs={12}>
                                            <Typography variant='subtitle1' color="#637381" marginBottom={1}>Sign*</Typography>
                                            <RHFTextField name="sign" label="Sign" placeholder='Sign' required />
                                        </Grid>
                                        <Grid item xs={10.8}>
                                            <Typography variant='subtitle1' color="#637381">Diagnosis*</Typography>
                                        </Grid>
                                        <Grid item xs={1} justifyContent={'flex-end'}>
                                            {/* <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => handleAddSecondaryDiagnosis()}> */}
                                            <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => append({value: {name: "", value: 0}})}>
                                                <Typography variant="button" display="block">Diagnosis</Typography>
                                            </Button>
                                        </Grid>
                                        {/* Main Diagnosis */}
                                        <Grid item xs={12}>
                                        <Autocomplete
                                            id="combo-box-demo"
                                            options={main_diagnosis}
                                            limitTags={1}
                                            fullWidth
                                            getOptionLabel={(option) => {
                                                return option.name ?? false
                                            }}
                                            isOptionEqualToValue={(option, value) =>{
                                                return option.id == value.main_diagnosis_id
                                            }}
                                            value={main_diagnosis.find(row => row.id == values.main_diagnosis_id) ?? null}
                                            onChange={handleMainDiagnosisChange}
                                            renderInput={(params) => (
                                            <RHFTextField required {...params} label="Main Diagnosis (ICD-X)" variant="outlined" name='main_diagnosis_id' />
                                            )}
                                        />
                                        </Grid>

                                        <Grid item xs={12}>
                                            {secondaryDiagnosisOption()}
                                        </Grid>
                                    </Grid>
                                </Stack>

                                <Stack direction="row" spacing={2}>
                                    <Grid container item xs={12} md={12} justifyContent="flex-end">
                                    <Button variant="outlined" color='primary' onClick={handleCloseDialogHospitalCare}>Cancel</Button>
                                    <LoadingButton
                                        type="submit"
                                        variant="contained"
                                        size="medium"
                                        loading={isSubmitting}
                                        sx={{marginLeft:2}}
                                    >
                                        <Typography variant="subtitle2">{isEdit ? 'Update' : 'Save'}</Typography>
                                    </LoadingButton>
                                    </Grid>
                                </Stack>
                            </FormProvider>
                            </DialogContent>
                            <DialogActions>


                            </DialogActions>
                        </Dialog>

                        {/* Dialog for approval */}
                        <Dialog open={openDialogApproval} onClose={handleCloseDialogApprove} fullWidth={true} maxWidth={'sm'}>
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">Add History of Hospital Care</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogApprove}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                            <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
                                <Stack spacing={2} sx={{marginTop: 2, padding: 2}}>
                                   <Typography variant='subtitle1'> Are you sure to approve this hospital care ?</Typography>
                                </Stack>

                                <Card sx={{padding: 2}}>
                                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                                        <Typography variant='subtitle2' sx={style1} gutterBottom>Admission Date</Typography>
                                        <Typography variant='subtitle1' gutterBottom>{ carehistory ? fDate(carehistory?.admission_date) : '-'}</Typography>
                                    </Stack>
                                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                                        <Typography variant='subtitle2' sx={style1} gutterBottom>Discharge Date</Typography>
                                        <Typography variant='subtitle1' gutterBottom>{carehistory ? fDate(carehistory.discharge_date) : '-'}</Typography>
                                    </Stack>
                                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                                        <Typography variant='subtitle2' sx={style1} gutterBottom>Location</Typography>
                                        <Typography variant='subtitle1' gutterBottom>{ carehistory ? carehistory.organization_name : '-'}</Typography>
                                    </Stack>
                                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                                        <Typography variant='subtitle2' sx={style1} gutterBottom>Doctor</Typography>
                                        <Typography variant='subtitle2' gutterBottom>{carehistory ? carehistory.practitioner_name : '-'}</Typography>
                                    </Stack>
                                    <Stack direction='row' spacing={2} sx={marginBottom1}>
                                        <Typography variant='subtitle2' sx={style1} gutterBottom>Diagnosis</Typography>
                                        <Typography variant='subtitle2' gutterBottom>{carehistory ? carehistory?.main_diagnosis_name : '-'}</Typography>
                                    </Stack>
                                </Card>

                                <Stack direction="row" spacing={1} marginTop={3}>
                                    <Grid container item xs={12} md={12} justifyContent="flex-end">
                                        <Button variant="outlined" color='inherit' onClick={handleCloseDialogApprove}>Cancel</Button>
                                        <Button variant="contained" sx={{marginLeft:1}} onClick={()=> handleApproveClaim(carehistory?.id, carehistory?.claim_id)} >
                                            <Typography variant="subtitle2">Approve</Typography>
                                        </Button>
                                    </Grid>
                                </Stack>
                            </FormProvider>
                            </DialogContent>
                            <DialogActions>


                            </DialogActions>
                        </Dialog>


                    </Card>
                </Grid>
                <Grid item xs={12}>
                    <Card sx={{padding: 3}}>
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Diagnostic History</Typography>
                        </Stack>
                        <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                            {currentClaimHistoryCare?.map((claimHistoryCare, index) =>
                                claimHistoryCare.status === 1 ? (
                                    <Grid item xs={12} md={12} key={index}> {/* Tambahkan key untuk setiap elemen dalam loop */}
                                    <Card sx={{padding: 2}}>
                                        <Stack direction="row" alignItems="center" justifyContent="space-between" sx={{marginBottom: 4}}>
                                            <Label variant="outlined" color='primary'  >
                                                <Typography variant="button" display="block">{claimHistoryCare.service_code = 'OP' ? 'Outpatient' : 'Inpatient'}</Typography>
                                            </Label>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Admission Date :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ fDate(claimHistoryCare.admission_date)}</Typography> {/* Perbaikan typo di 'admission_date' */}
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Discharge Date :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ fDate(claimHistoryCare.discharge_date)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Location :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(claimHistoryCare.organization?.name)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Doctor :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{toTitleCase(claimHistoryCare.practitioner?.code)} - {claimHistoryCare.person?.name}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Status :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{claimHistoryCare.status == 0 ? 'Pending' : 'Approv'}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Diagnosis :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>#{index+1} {claimHistoryCare.icd?.code} - {claimHistoryCare.icd?.name}</Typography>
                                        </Stack>
                                    </Card>
                                    </Grid>
                                ) : null
                            )}
                        </Stack>
                    </Card>
                </Grid>
                <Grid item xs={12}>
                    <Card sx={{padding: 3}}>
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Diagnosis Summary</Typography>
                        </Stack>
                        <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
                        {currentClaimHistoryCare?.map((claimHistoryCare, index) =>
                                claimHistoryCare.status === 1 ? (
                                    <Grid item xs={12} md={12} key={index}> {/* Tambahkan key untuk setiap elemen dalam loop */}
                                    <Card sx={{padding: 2}}>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Symtomps :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ claimHistoryCare.symptoms}</Typography> {/* Perbaikan typo di 'admission_date' */}
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Sign :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{ claimHistoryCare.sign}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2} sx={marginBottom1}>
                                            <Typography variant='subtitle2' sx={style1} gutterBottom>Main Diagnosis :</Typography>
                                            <Typography variant='subtitle2' sx={style2} gutterBottom>{claimHistoryCare.icd?.name}  <Label>{claimHistoryCare.icd?.code}</Label></Typography>
                                        </Stack>

                                        {/* {claimHistoryCare.comparative_diagnosis?.map((comparativeDiagnosis, i) =>
                                            (
                                                <Stack direction='row' spacing={2} sx={marginBottom1}>
                                                    <Typography variant='subtitle2' sx={style1} gutterBottom>{i == 0 ? 'Comparative Diagnosis :' : ''}</Typography>
                                                    <Typography variant='subtitle2' sx={style2} gutterBottom>{comparativeDiagnosis.icd?.name}  <Label>{comparativeDiagnosis.icd?.code}</Label></Typography>
                                                </Stack>
                                            )
                                        )} */}

                                        {claimHistoryCare.comparative_diagnosis && claimHistoryCare.comparative_diagnosis.length > 0 && (
                                            claimHistoryCare.comparative_diagnosis.map((comparativeDiagnosis, i) => (
                                                <Stack direction='row' spacing={2} sx={marginBottom1} key={i}>
                                                <Typography variant='subtitle2' sx={style1} gutterBottom>
                                                    {i === 0 ? 'Comparative Diagnosis :' : ''}
                                                </Typography>
                                                <Typography variant='subtitle2' sx={style2} gutterBottom>
                                                    {comparativeDiagnosis.icd?.name} <Label>{comparativeDiagnosis.icd?.code}</Label>
                                                </Typography>
                                                </Stack>
                                            ))
                                        )}


                                    </Card>
                                    </Grid>
                                ) : null
                            )}
                        </Stack>
                    </Card>
                </Grid>
                <Grid item xs={12}>
                    <Card sx={{padding: 2}}>
                        <Stack direction="row" alignItems="center" sx={{marginBottom: 4}}>
                            <Typography variant='subtitle1' sx={{color: '#19BBBB'}} gutterBottom>Service</Typography>
                            {!serviceData && customerData?.status === 'received' ? (
                            <Button variant="outlined" startIcon={<AddIcon/>} sx={{marginLeft: 'auto'}} onClick={() => handleAddService()}>
                                <Typography variant="button" display="block">Service</Typography>
                            </Button>
                            ) : (
                                <Stack sx={{marginLeft: 'auto'}}>
                                    {customerData?.status === 'received' ? (
                                    <TableMoreMenu  actions={
                                        <>
                                            <MenuItem onClick={() => handleEditService()}>
                                                <EditOutlinedIcon />
                                                Edit
                                            </MenuItem>
                                        </>
                                        }
                                    />
                                    ) : ''}
                                </Stack>
                            )}
                        </Stack>
                        {serviceData ? (
                        <>
                            <Stack direction='row' spacing={2} sx={marginBottom1}>
                                <Typography variant='subtitle2' sx={style1} gutterBottom>Admission Date</Typography>
                                <Typography variant='subtitle2' sx={style2} gutterBottom>{serviceData && serviceData.addmission_date ? fDateTime(serviceData.addmission_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>{serviceData && serviceData.discharge_date ? fDateTime(serviceData.discharge_date) : ''}</Typography>
                            </Stack>
                            <Stack direction='row' spacing={2} sx={marginBottom1}>
                                <Typography variant='subtitle2' sx={style1} gutterBottom>Serice Type</Typography>
                                <Typography variant='subtitle2' sx={style2} gutterBottom>{serviceData && serviceData.name_services ? serviceData.name_services : ''}</Typography>
                            </Stack>
                            <Stack direction='row' spacing={2} sx={marginBottom1}>
                                <Typography variant='subtitle2' sx={style1} gutterBottom>Benefit Name</Typography>
                                <Typography variant='subtitle2' sx={style2} gutterBottom>{serviceBenefitData && serviceBenefitData.name_benefits ? serviceBenefitData.name_benefits : ''}</Typography>
                            </Stack>
                            <Stack direction='row' spacing={2} sx={marginBottom1}>
                                <Typography variant='subtitle2' sx={style1} gutterBottom>Hospital</Typography>
                                <Typography variant='subtitle2' sx={style2} gutterBottom>{serviceData && serviceData.name_hospitals ? serviceData.name_hospitals : ''}</Typography>
                            </Stack>
                        </>
                        ): ''}

                        {/* Dialog Service */}
                        <Dialog open={openDialogService} onClose={handleCloseDialogService} fullWidth={true}>
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">{txtName}</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogService}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                            <Stack spacing={2} sx={{marginTop: 2, padding: 2}} direction="column">
                                <Stack direction="row" spacing={2}>
                                    <Stack direction="column" spacing={2}>
                                        <Typography variant="Subtitle1" sx={{fontWeight: 'bold'}}>
                                            Admission Date*
                                        </Typography>
                                        <LocalizationProvider dateAdapter={AdapterDateFns}>
                                            <DatePicker
                                                label="Admission Date"
                                                value={dateAd}
                                                onChange={(newValue) => {
                                                    setDateAd(newValue);
                                                }}
                                                inputFormat="dd MMM yyyy"
                                                renderInput={(params) => <TextField sx={{width:'100%'}} {...params} defaultValue={formattedCurrentDate}/>}
                                            />
                                        </LocalizationProvider>
                                    </Stack>
                                    <Stack direction="column" spacing={2}>
                                        <Typography variant="Subtitle1" sx={{fontWeight: 'bold'}}>
                                            Discharge Date*
                                        </Typography>
                                        <LocalizationProvider dateAdapter={AdapterDateFns}>
                                            <DatePicker
                                                label="Discharge Date"
                                                value={dateDis}
                                                onChange={(newValue) => {
                                                    setDateDis(newValue);
                                                }}
                                                inputFormat="dd MMM yyyy"
                                                renderInput={(params) => <TextField sx={{width:'100%'}} {...params} defaultValue={formattedCurrentDate}/>}
                                            />
                                        </LocalizationProvider>
                                    </Stack>
                                </Stack>
                                <Stack direction="row" spacing={2}>
                                    <Stack spacing={2} sx={{width:'100%'}}>
                                        <Typography variant='subtitle1'>Service Type*</Typography>
                                        <FormControl>
                                        <InputLabel htmlFor="service_type">
                                            Service Type
                                        </InputLabel>
                                        <Select
                                            id="service_type"
                                            value={valServiceType}
                                            fullWidth
                                            label="Service Type"
                                            error={!!valServiceTypeError}
                                            onChange={(e) => {
                                                setValServiceType(e.target.value);
                                                setValServiceTypeError(e.target.value === '' ? 'This field is required' : '');
                                            }}
                                            disabled

                                        >
                                        {serviceTypeData?.map((item, index) => (
                                            <MenuItem key={index} value={item.id}>{item.name}</MenuItem>
                                        ))}
                                        </Select>
                                        <FormHelperText style={{ color: 'red' }}>{valServiceTypeError}</FormHelperText>
                                        </FormControl>
                                    </Stack>
                                </Stack>
                                <Stack direction="row" spacing={2}>
                                    <Stack spacing={2} sx={{width:'100%'}}>
                                        <Typography variant='subtitle1'>Benefit Name*</Typography>
                                        <FormControl>
                                        <InputLabel htmlFor="benefit_name">
                                            Benefit Name
                                        </InputLabel>
                                        <Select
                                            id="benefit_name"
                                            value={valBenefitNames}
                                            fullWidth
                                            label="Benefit Name"
                                            error={!!valBenefitNameError}
                                            onChange={(e) => {
                                                setValBenefitNameError(!valBenefitNames ? 'At least one item must be selected' : '');
                                            }}
                                            renderValue={(selected) => selected.map(value => {
                                                const selectedOption = benefitNameData.find(option => String(option.id) === value);
                                                return selectedOption ? selectedOption.description : '';
                                            }).join(', ')}
                                        >
                                            {benefitNameData?.map((item, index) => (
                                                <FormGroup key={index} sx={{ marginLeft: 2 }}>
                                                    <FormControlLabel
                                                        control={
                                                            <Checkbox
                                                                checked={valBenefitNames.includes(String(item.id))}
                                                                onChange={handleConditionChangeService}
                                                                value={String(item.id)}
                                                            />
                                                        }
                                                        label={item.description}
                                                    />
                                                </FormGroup>
                                            ))}
                                        </Select>
                                        <FormHelperText style={{ color: 'red' }}>{valBenefitNameError}</FormHelperText>
                                        </FormControl>
                                    </Stack>
                                </Stack>
                                <Stack direction="row" spacing={2}>
                                    <Stack spacing={2} sx={{width:'100%'}}>
                                        <Typography variant='subtitle1'>Hospital*</Typography>
                                        <FormControl>
                                        <InputLabel htmlFor="hospital">
                                            Hospital
                                        </InputLabel>
                                        <Select
                                            id="hospital"
                                            value={valHospital}
                                            fullWidth
                                            label="Hospital"
                                            error={!!valHospitalError}
                                            onChange={(e) => {
                                                setValHospital(e.target.value);
                                                setValHospitalError(e.target.value === '' ? 'This field is required' : '');
                                            }}

                                        >
                                        {hospitalData?.map((item, index) => (
                                            <MenuItem key={index} value={item.id}>{item.name}</MenuItem>
                                        ))}
                                        </Select>
                                        <FormHelperText style={{ color: 'red' }}>{valHospitalError}</FormHelperText>
                                        </FormControl>
                                    </Stack>
                                </Stack>
                            </Stack>
                            </DialogContent>
                            <DialogActions>
                            <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialogService}>Cancel</Button>
                            <Button sx={{backgroundColor: '#19BBBB'}} variant="contained" disabled={!isRequiredFieldsServiceType()} onClick={() => handelSaveServiceType()}>Save</Button>
                            </DialogActions>
                        </Dialog>
                    </Card>
                </Grid>
                <Grid item xs={12}>
                    <Card sx={{padding: 3}}>
                        <Grid container spacing={4}>
                            {/* title */}
                            <Grid item xs={12}>
                                <Typography variant='subtitle1' sx={{color: '#19BBBB'}}>Client Benefit Configuration</Typography>
                            </Grid>

                            {/* no benefit selected */}
                            {
                                false
                                ?
                                (
                                    <Grid item xs={12}>
                                        <Typography variant='body2' sx={{color: '#919EAB', paddingBottom: '14px', textAlign: 'center'}}>Tidak ada benefit yang dipilih</Typography>
                                    </Grid>
                                )
                                :
                                (
                                    <Grid item xs={12}>
                                        <BenefitConfigurationList />
                                    </Grid>
                                )
                            }
                        </Grid>
                    </Card>
                </Grid>
                <Grid item xs={12} md={12}>
                    <Stack direction="row" padding={4}>
                        <>
                            {(customerData && customerData.status === 'received') ? (
                                <>
                                    <Button
                                        variant="outlined"
                                        sx={{color: '#FF4842', borderColor: '#FF4842', marginLeft: 'auto'}}
                                        onClick={() => {
                                            setOpenDialogSubmit(true);
                                            setDeclaine('decline');
                                        }}
                                    >
                                        Decline
                                    </Button>
                                    <Button
                                        sx={{backgroundColor: '#19BBBB', marginLeft: 1}}
                                        variant="contained"
                                        onClick={()=> {
                                            setOpenDialogSubmit(true);
                                            setDeclaine('approve');
                                        }}
                                    >
                                        Approve
                                    </Button>
                                </>
                            ) : (
                                <>
                                    <Stack direction="row" sx={{marginLeft: 'auto'}} spacing={2}>
                                        <Button
                                            variant="outlined"
                                            sx={{color: '#212B36', borderColor: '#919EAB52', display: customerData?.status === 'declined' ? 'none' : '' }}
                                            onClick={handelDownloadLog}
                                        >
                                            Download Final LOG
                                        </Button>
                                        <Button
                                            sx={{backgroundColor: '#19BBBB', marginLeft: 1}}
                                            variant="contained"
                                            onClick={()=> {
                                                setOpenDialogSubmit(true);
                                                setDeclaine('re-open');
                                            }}
                                        >
                                            Re-Open
                                        </Button>
                                    </Stack>
                                </>
                            ) }

                        </>
                        {/* Dialog Submits */}
                        <Dialog open={openDialogSubmit} onClose={handleCloseDialogSubmit} fullWidth={true}>
                            <DialogTitle sx={{ backgroundColor: '#19BBBB', color: '#FFF', padding: 2 }}>
                            <Stack direction="row" alignItems="center" justifyContent="space-between">
                                <Stack direction="row" alignItems='center' spacing={1}>
                                    <Typography variant="h6">Confirmation</Typography>
                                </Stack>
                                <IconButton sx={{ color: '#FFF' }} onClick={handleCloseDialogSubmit}>
                                    <CloseIcon />
                                </IconButton>
                            </Stack>
                            </DialogTitle>
                            <DialogContent>
                                {dataDialog ? (
                                <Stack spacing={2} padding={2}>
                                    <Typography variant='body1'>Are you sure to {toTitleCase(decline)} this claim ?</Typography>
                                    <Card sx={{padding:2}}  >
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Code</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{dataDialog.code}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Name</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{dataDialog.name}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Date Submission</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>{fDateTime(dataDialog.submission_date)}</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Claim Method</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>Service Type</Typography>
                                        </Stack>
                                        <Stack direction='row' spacing={2}>
                                            <Typography variant='subtitle2' sx={{color: '#919EAB', width: '30%'}}>Service Type</Typography>
                                            <Typography variant='subtitle2' sx={{width: '70%'}}>
                                                {dataDialog.service_code === 'IP' ? 'Inpatient' : 'Outpatient'}
                                            </Typography>
                                        </Stack>
                                    </Card>
                                </Stack>
                                ) : ''}
                            </DialogContent>
                            <DialogActions>
                            <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialogSubmit}>Cancel</Button>
                            <Button sx={{backgroundColor: (decline === 'decline' ? '' : '#19BBBB'), color: (decline === 'decline' ? '#FF4842' : ''), borderColor: '#FF4842'}} onClick={handleSubmitData} variant={(decline === 'decline' ? 'outlined' : 'contained')}>{(decline === "decline" ? 'Decline' : (decline === "approve" ? 'Approve' : 'Re-Open'))}</Button>
                            </DialogActions>
                        </Dialog>
                    </Stack>
                </Grid>
            </Grid>
        </Container>
        </Page>
    );
}
