import MuiDialog from "@/components/MuiDialog";
import { Button, Card, Checkbox, DialogActions, Grid, TextField, TextareaAutosize, Typography, Select } from "@mui/material";
import { Paper } from "@mui/material";
import { Stack } from '@mui/material';
import React, { useEffect, useState } from 'react';
import { DetailRequestLogType } from "../Model/Types";
import { fDateOnly, fDateTimesecond, toTitleCase } from "@/utils/formatTime";
import axios from "@/utils/axios";
import { enqueueSnackbar } from "notistack";
import { useNavigate } from "react-router";
import { RHFSelect, RHFTextField, RHFEditor } from "@/components/hook-form";
import { Autocomplete } from "@mui/material";
// import { RHFEditor } from "@/components/hook-form/v2";


type DialogConfirmationType = {
    openDialog: boolean;
    setOpenDialog: any;
    onSubmit?: void;
    requestLog: DetailRequestLogType|undefined; 
}

export default function DialogEditInformation({requestLog, setOpenDialog, openDialog, onSubmit} : DialogConfirmationType ) {
    const navigate = useNavigate();

    const [formData, setFormData] = useState({
        submission_date: requestLog?.submission_date,
        keterangan: requestLog?.keterangan,
        hak_kamar_pasien: requestLog?.hak_kamar_pasien,
        penempatan_kamar: requestLog?.penempatan_kamar,
        reason: requestLog?.reason
    });

    const [isReasonSelected, setIsReasonSelected] = useState(true);
    
    useEffect(() => {
        // Update formData setiap kali requestLog berubah
        setFormData({
          submission_date: requestLog?.submission_date || '',
          keterangan: requestLog?.keterangan || '',
          hak_kamar_pasien: requestLog?.hak_kamar_pasien || '',
          penempatan_kamar: requestLog?.penempatan_kamar || '',
          reason: requestLog?.reason || '',

        });
      }, [requestLog]);

    const handleChange = (field, value) => {
        setFormData((prevData) => ({
            ...prevData,
            [field]: value,
        }));
        if (field === 'reason') {
            setIsReasonSelected(!!value);
        }

    };

    const handleApprove = () => {
        setFormData((prevData) => ({
            ...prevData,
        }));
        handleSubmit();
    };
    

    const handleSubmit = () => {
        if (isReasonSelected && formData.reason !== '') {
            axios
                .put(`customer-service/request/${requestLog?.id}`, formData)
                .then((response) => {
                    enqueueSnackbar('Verification Request LOG Success', { variant: 'success' });
                    setOpenDialog(false);
                    navigate('/custormer-service/request/detail/' + requestLog?.id)
                    window.location.reload()
                })
                .catch(({ response }) => {
                    enqueueSnackbar(response.data.message ?? 'Something went wrong!', { variant: 'error' });
                });
        } else {
            setIsReasonSelected(false);
            alert('Silakan pilih alasan sebelum mengirimkan data.');
        }
    }

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

    const marginBottom2 = {
        marginBottom: 2,
    }

    const resetForm = () => {
        setFormData({
            submission_date: requestLog?.submission_date ?? '',
            keterangan: requestLog?.keterangan ?? '',
            hak_kamar_pasien: requestLog?.hak_kamar_pasien ?? '',
            penempatan_kamar: requestLog?.penempatan_kamar ?? '',
            reason: requestLog?.reason ?? '',
            
        });
    };

    const handleCloseDialog = () => {
        setOpenDialog(false);
        resetForm();
    }

    const handleNumericInput = (input: any) => {
        const numericInput = input.replace(/\D/g, '');
        return numericInput;
    };

    const handleKeyPress = (e:any) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            // Menghentikan default "Enter" (tidak membuat baris baru)
            e.preventDefault();

            // Menambahkan karakter baris baru
            handleChange('keterangan', `${formData.keterangan}\n`);
        }
    };

    const reasons = [
        { value: 'agreement', label: 'Agreement changed' },
        { value: 'endorsement', label: 'Endorsement' },
        { value: 'renewal', label: 'Renewal' },
        { value: 'wrong_setting', label: 'Wrong Setting' },
        // Add more options as needed
    ];

    const getContent = () => (
        <Stack spacing={1} marginTop={2}>
            <Typography variant="subtitle2">Are you sure to update this request ?</Typography>
            <Grid item xs={12} md={12} marginTop={4}>
                    <Card sx={{padding:2, marginTop:2}}  >
                        <Stack direction='row' spacing={2} sx={marginBottom2}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Addmision Date</Typography>
                            <TextField
                                label="Addmision Date"
                                variant="outlined"
                                fullWidth
                                type="date"
                                value={formData.submission_date ? fDateOnly(formData.submission_date) : ''}
                                onChange={(e) => handleChange('submission_date', e.target.value)}
                            />
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom2}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Keterangan</Typography>
                            <TextareaAutosize
                                aria-label="Keterangan"
                                minRows={3}
                                placeholder="Masukkan keterangan..."
                                value={formData.keterangan}
                                onChange={(e) => handleChange('keterangan', e.target.value)}
                                onKeyDown={handleKeyPress}
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    border: '1px solid #ced4da',
                                    borderRadius: '4px',
                                    fontSize: '14px',
                                }}
                            />
                            {/* <RHFEditor name="description" placeholder="Tuliskan Deskripsi" /> */}
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom2}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Hak Kamar Pasien</Typography>
                            <TextField
                                label="Hak Kamar Pasien"
                                variant="outlined"
                                fullWidth
                                value={formData.hak_kamar_pasien}
                                onChange={(e) => handleChange('hak_kamar_pasien', e.target.value)}
                            />
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom2}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Penempatan Kamar</Typography>
                            <TextField
                                label="Penempatan Kamar"
                                variant="outlined"
                                fullWidth
                                value={formData.penempatan_kamar}
                                onChange={(e) => handleChange('penempatan_kamar', e.target.value)}
                            />
                        </Stack>
                        <Stack direction='row' spacing={2} sx={marginBottom2}>
                            <Typography variant='subtitle2' sx={style1} gutterBottom>Reason*</Typography>
                            <Autocomplete
                                options={reasons}
                                getOptionLabel={(option) => option.label}
                                fullWidth
                                value={reasons.find((r) => r.value === formData.reason) || null} // Use find to match the default value
                                onChange={(e, newValue) => handleChange('reason', newValue?.value)}
                                renderInput={(params) => (
                                    <TextField
                                        {...params}
                                        label="Reason"
                                        variant="outlined"
                                        required
                                        error={!isReasonSelected} // Menandai input sebagai salah jika opsi tidak dipilih
                                        helperText={!isReasonSelected ? 'Alasan harus dipilih' : ''}

                                    />
                                )}
                            />
                        </Stack>
                    </Card>
                </Grid>
                <DialogActions>
                    <Button variant="outlined" sx={{color: '#212B36', borderColor: '#919EAB52'}} onClick={handleCloseDialog}>Cancel</Button>
                    <Button color="primary"  variant="contained" onClick={() => handleApprove()}>Update</Button>
                </DialogActions>
        </Stack>
      );


    return (
        <MuiDialog
          title={{name: "Edit Request LOG"}}
          openDialog={openDialog}
          setOpenDialog={setOpenDialog}
          content={getContent()}
          maxWidth="xl"
        />
      );
}