import { styled } from '@mui/material/styles';
import Iconify from '@/components/Iconify';
import { fCurrency } from '@/utils/formatNumber';
import { LoadingButton } from '@mui/lab';
import { Avatar, Button, Divider, LinearProgress, linearProgressClasses, ButtonBase, Box } from '@mui/material';
import { Card } from '@mui/material';
import { Stack, Typography } from '@mui/material';
import { fPostFormat } from '@/utils/formatTime';
import axios from '@/utils/axios';
import { enqueueSnackbar } from 'notistack';
import { useRef, useState, useContext } from 'react';
import { makeFormData } from '@/utils/jsonToFormData';
import { format } from 'date-fns';
import { LanguageContext } from '@/contexts/LanguageContext';
import { DatePicker, LocalizationProvider, MobileDatePicker } from '@mui/x-date-pickers';
import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns';
import TextField from '@mui/material/TextField';

export default function DialogFinalLog({ member, getData, onClose, handleSubmitSuccess }: any) {
    const { localeData }: any =  useContext(LanguageContext);
    //Submission date
    const [dischargeDate, setDischargeDate] = useState<string>(format(new Date(), "yyyy MMM d HH:mm:ss"));

  // ----------------------------------------------------------------------
  // Files Diagnosa

  const fileDiagnosaInput = useRef<HTMLInputElement>(null);
  const [fileDiagnosas, setFileDiagnosas] = useState<any>([]);

  const handleDiagnosaInputChange = (event:any) => {
    if (event.target.files[0]) {
      setFileDiagnosas([...fileDiagnosas, ...event.target.files]);
    } else {
      console.log('NO FILE');
    }
  };
  const removeDiagnosaFiles = (filesState:any, index:any) => {
    setFileDiagnosas(
      filesState.filter((file:any, fileIndex:any) => {
        return fileIndex != index;
      })
    );
  };

  // ----------------------------------------------------------------------
  // Files Result Kondisi

  const fileKondisiInput = useRef<HTMLInputElement>(null);
  const [fileKondisis, setFileKondisis] = useState<any>([]);

  const handleKondisiInputChange = (event:any) => {
    if (event.target.files[0]) {
      setFileKondisis([...fileKondisis, ...event.target.files]);
    } else {
      console.log('NO FILE');
    }
  };
  const removeKondisiFiles = (filesState:any, index:any) => {
    setFileKondisis(
      filesState.filter((file:any, fileIndex:any) => {
        return fileIndex != index;
      })
    );
  };

  // ----------------------------------------------------------------------
  // Files Result Hasil Penunjang

  const fileHasilPenunjangInput = useRef<HTMLInputElement>(null);
  const [fileHasilPenunjangs, setFileHasilPenunjangs] = useState<any>([]);

  const handleResultInputChange = (event:any) => {
    if (event.target.files[0]) {
      setFileHasilPenunjangs([...fileHasilPenunjangs, ...event.target.files]);
    } else {
      console.log('NO FILE');
    }
  };
  const removeFiles = (filesState:any, index:any) => {
    setFileHasilPenunjangs(
      filesState.filter((file:any, fileIndex:any) => {
        return fileIndex != index;
      })
    );
  };

  // --------------------------------------------------------------
  // Submit Form

  const [submitLoading, setSubmitLoading] = useState(false);
  function submitRequestFinalLog() {
    if(dischargeDate == '')
    {
        enqueueSnackbar(localeData.txtWarningDischargeDate, { variant: 'warning' });
        return false;
    }
    setSubmitLoading(true);
    const formData = makeFormData({
      request_logs_id: member.id,
      result_files: fileHasilPenunjangs,
      diagnosa_files: fileDiagnosas,
      kondisi_files: fileKondisis,
      discharge_date: fPostFormat(dischargeDate, 'yyyy-MM-dd HH:mm:ss'),
    });
    axios
      .post('/request-final-log', formData)
      .then((response) => {
        enqueueSnackbar(response.data.meta.message ?? 'Berhasil membuat data', { variant: 'success' });
        handleSubmitSuccess();
        onClose({ someData: 'example data' }, getData);
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.meta.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .then(() => {
        setSubmitLoading(false);
      });
  }

  return (
    <Stack>
      <Stack direction="row" justifyContent={'end'} sx={{ marginBottom: 2, marginTop: 2 }} spacing={2}>
        <Typography variant='body2' sx={{color: '#757575'}}>
          {localeData.txtDialogMember5}
        </Typography>
        <Typography variant='body2' sx={{fontWeight:'bold'}}>{format(member?.submission_date ? new Date(member.submission_date) : new Date(), "d MMM yyyy")}</Typography>
      </Stack>

      <Card sx={{ p: 1, background: '#f4f6f8'}}>
        <Stack direction="row">
          <Avatar
            src=""
            alt={member?.full_name ?? ''}
            sx={{ marginTop: 1, width: 48, height: 48 }}
          />
          <Stack sx={{ p: 1 }}>
            <Typography variant="body2">{member?.full_name ?? ''}</Typography>
            <Typography variant="body2" sx={{color:'#637381'}}>{member?.no_polis ?? ''}</Typography>
          </Stack>
        </Stack>
      </Card>

      <Stack
        divider={<Divider orientation="horizontal" flexItem />}
        spacing={4}
        sx={{ marginY: 2, marginBottom: 6 }}
      >
        {/* -------------------------------Upload Dokumen Kondisi------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
             {localeData.txtBillingDocument}
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </Typography> */}
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileKondisis &&
              fileKondisis.map((file:any, index:any) => (
                <Stack direction="row" justifyContent={'space-between'} key={index}>
                  <Typography sx={{ color: "text.secondary" }}>{file.name}</Typography>
                  <Iconify
                    icon="eva:trash-2-outline"
                    color={'darkred'}
                    onClick={() => {
                      removeKondisiFiles(fileKondisis, index);
                    }}
                  ></Iconify>
                </Stack>
              ))}
          </Stack>
           <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                bgcolor: '#919EAB52',
                borderRadius: '8px',
                width: '100%', height: '60px'}} onClick={() => fileKondisiInput.current?.click()}>
            <Box
              sx={{
                display: 'flex',
                placeItems: 'center',
                gap: 1,
                placeContent: 'center',
                

              }}
            >
              <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
              <Typography variant="body1" fontWeight="bold">
                {localeData.txtAddResult}
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileKondisiInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleKondisiInputChange}
              accept="application/pdf,image/*"
            />
          </ButtonBase>
        </Stack>

        {/* -------------------------------Upload Dokumen Diagnosa------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
            {localeData.txtDiagnosisDokument}
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </Typography> */}
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileDiagnosas &&
              fileDiagnosas.map((file:any, index:any) => (
                <Stack direction="row" justifyContent={'space-between'} key={index}>
                  <Typography sx={{ color: "text.secondary" }}>{file.name}</Typography>
                  <Iconify
                    icon="eva:trash-2-outline"
                    color={'darkred'}
                    onClick={() => {
                      removeDiagnosaFiles(fileDiagnosas, index);
                    }}
                  ></Iconify>
                </Stack>
              ))}
            {/* <Stack direction="row" justifyContent={'space-between'}>
                                      <Typography>Nama File .pdf</Typography>
                                      <Iconify icon="eva:trash-2-outline" color={'darkred'}></Iconify>
                                  </Stack> */}
          </Stack>
          {/* { JSON.stringify(filesResult) } */}
          <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                bgcolor: '#919EAB52',
                borderRadius: '8px',
                width: '100%', height: '60px'}} onClick={() => fileDiagnosaInput.current?.click()}>
            <Box
              sx={{
                display: 'flex',
                placeItems: 'center',
                gap: 1,
                placeContent: 'center',
                

              }}
            >
              <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
              <Typography variant="body1" fontWeight="bold">
                {localeData.txtAddResult}
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileDiagnosaInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleDiagnosaInputChange}
              accept="application/pdf,image/*"
            />
          </ButtonBase>
        </Stack>

        {/* -------------------------------Upload Dokumen Hasil Penunjang------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
            {localeData.txtSupportingResultDocument}
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </Typography> */}
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileHasilPenunjangs &&
              fileHasilPenunjangs.map((file:any, index:any) => (
                <Stack direction="row" justifyContent={'space-between'} key={index}>
                  <Typography sx={{ color: "text.secondary" }}>{file.name}</Typography>
                  <Iconify
                    icon="eva:trash-2-outline"
                    color={'darkred'}
                    onClick={() => {
                      removeFiles(fileHasilPenunjangs, index);
                    }}
                  ></Iconify>
                </Stack>
              ))}
            {/* <Stack direction="row" justifyContent={'space-between'}>
                                      <Typography>Nama File .pdf</Typography>
                                      <Iconify icon="eva:trash-2-outline" color={'darkred'}></Iconify>
                                  </Stack> */}
          </Stack>
          {/* { JSON.stringify(filesResult) } */}
          <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                bgcolor: '#919EAB52',
                borderRadius: '8px',
                width: '100%', height: '60px'}} onClick={() => fileHasilPenunjangInput.current?.click()}>
            <Box
              sx={{
                display: 'flex',
                placeItems: 'center',
                gap: 1,
                placeContent: 'center',
                

              }}
            >
              <Iconify icon="icon-park-outline:upload-one" fontSize="3em" />
              <Typography variant="body1" fontWeight="bold">
                {localeData.txtAddResult}
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileHasilPenunjangInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleResultInputChange}
              accept="application/pdf,image/*"
            />
          </ButtonBase>
        </Stack>
      </Stack>

      <Stack direction="row" spacing={2}>
            <Stack spacing={2} sx={{ width: '100%' }}>
                <Typography variant='subtitle1'>{localeData.txtDischargeDate} *</Typography>
                <LocalizationProvider dateAdapter={AdapterDateFns}>
                    <DatePicker
                        label={localeData.txtDischargeDate}
                        value={dischargeDate}
                        onChange={(newValue:any) => {
                          setDischargeDate(  (newValue));
                        }}
                        inputFormat="dd-MM-yyyy HH:mm"
                        renderInput={(params) => <TextField sx={{width:'40%'}} {...params} required/>}
                    />
                </LocalizationProvider>
            </Stack>
        </Stack>

      <LoadingButton
        variant="contained"
        sx={{ marginTop: 2, p: 2, backgroundColor: '#19BBBB' }}
        onClick={() => {
          submitRequestFinalLog();
        }}
        loading={submitLoading}
      >
        Request Final LOG
      </LoadingButton>
    </Stack>
  );
}
