import * as React from 'react';
import Timeline from '@mui/lab/Timeline';
import TimelineItem, { timelineItemClasses } from '@mui/lab/TimelineItem';
import TimelineSeparator from '@mui/lab/TimelineSeparator';
import TimelineConnector from '@mui/lab/TimelineConnector';
import TimelineContent from '@mui/lab/TimelineContent';
import TimelineDot from '@mui/lab/TimelineDot';
import {Typography, Card, Stack, ButtonBase, Box, Divider} from '@mui/material';
import { styled } from '@mui/material/styles';
import Paper from '@mui/material/Paper';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import Iconify from '../../components/Iconify';
import { useEffect, useState, useRef } from 'react';
import { format } from 'date-fns';
import { LoadingButton } from '@mui/lab';
import axios from '../../utils/axios';
import { makeFormData } from '@/utils/jsonToFormData';
import { enqueueSnackbar } from 'notistack';
import { useParams} from 'react-router-dom';
import InsertDriveFileIcon from '@mui/icons-material/InsertDriveFile';

const Item1 = styled(Paper)(({ theme }) => ({
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  backgroundColor: '#919EAB29',
  color: '#637381',
  width: 'fit-content',
  marginRight: 'auto',
}));

const Item2 = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  color: theme.palette.text.secondary,
  width: 'fit-content',
  marginLeft: 'auto',
}));

export default function NoOppositeContent({data}) {
  const [timeline, setTimeline] = useState(null);
  const [requestFile, setRequestFile] = useState(null);
  useEffect(() => {
    if (data && data.data) {
      setTimeline(data.data.timeline);
      setRequestFile(data.data.request_files);
    }

  }, [data]);

  // Diagnosis
  const fileRequestDocumentInputDiagnosis = useRef<HTMLInputElement>(null);
  const [fileDiagnosis, setFileDiagnosis] = useState([]);
  const handleRequestDocumentInputChangeDiagnosis = (event) => {
    if (event.target.files[0]) {
      setFileDiagnosis([...fileDiagnosis, ...event.target.files]);
    }
  };
  const removeFileDiagnois = (filesState, index) => {
    setFileDiagnosis(
      filesState.filter((file, fileIndex) => {
          return fileIndex != index;
      })
    );
  };
  // Kondisi
  const fileRequestDocumentInputKondisi = useRef<HTMLInputElement>(null);
  const [fileKondisi, setFileKondisi] = useState([]);
  const handleRequestDocumentInputChangeKondisi = (event) => {
    if (event.target.files[0]) {
      setFileKondisi([...fileKondisi, ...event.target.files]);
    }
  };
  const removeFileKondisi = (filesState, index) => {
    setFileKondisi(
      filesState.filter((file, fileIndex) => {
          return fileIndex != index;
      })
    );
  };
  // Result
  const fileRequestDocumentInputResult = useRef<HTMLInputElement>(null);
  const [fileResult, setFileResult] = useState([]);
  const handleRequestDocumentInputChangeResult = (event) => {
    if (event.target.files[0]) {
      setFileResult([...fileResult, ...event.target.files]);
    }
  };
  const removeFileResult = (filesState, index) => {
    setFileResult(
      filesState.filter((file, fileIndex) => {
          return fileIndex != index;
      })
    );
  };
  const { id } = useParams();
  const [submitLoading, setSubmitLoading] = useState(false);
  const submitRequestFiles = () => {
    setSubmitLoading(true);
    const formData = makeFormData({
        fileDiagnosis: fileDiagnosis,
        fileKondisis: fileKondisi,
        fileResults: fileResult
    });
    axios
    .post('claim-requests/'+id+'/request-files', formData)
    .then((response) => {
        window.location.reload();
    })
    .catch(({ response }) => {
        enqueueSnackbar(response.data.message ?? 'Something Went Wrong', { variant: 'error' });
    });
  }
  const submitButton = requestFile?.find((dataRequestFile) => dataRequestFile.check_files === null);
  return (
    <>
      {timeline?.map((dataTimeline, index) => (
      <Timeline
        sx={{
          [`& .${timelineItemClasses.root}:before`]: {
            flex: 0,
            padding: 0,
          },
        }}
        key={index}
      >
        <Typography variant="body2" gutterBottom fontWeight="bold">{dataTimeline.date ? format(new Date(dataTimeline.date), "d MMM yyyy") : ''}</Typography>
        <TimelineItem>
          <TimelineSeparator>
            <TimelineDot />
            <TimelineConnector />
          </TimelineSeparator>
          <TimelineContent spacing={3}>
          	<Card sx={{ borderRadius: '6px', paddingY: 2 }}>
          		<Stack sx={{marginLeft: 2, marginRight: 2, marginTop: 2 }}>
            		<Stack direction="row" spacing={2} sx={{marginBottom: 2, paddingBottom: 2, borderBottom: '1px solid #919EAB52' }}>
        				  <Item1>{dataTimeline.date ? format(new Date(dataTimeline.date), "HH : mm") : ''}</Item1>
        				  <Item2 sx={{backgroundColor: dataTimeline.txt_status_backgroundColor, color: dataTimeline.txt_status_color}}>{dataTimeline.txt_status}</Item2>
        				</Stack>
        				<Stack direction="row" spacing={2} sx={{marginBottom: 2}}>
        					<Typography variant="body2" gutterBottom>Detail:</Typography>
        					<Typography variant="body2" gutterBottom>{dataTimeline.description}</Typography>
        				</Stack>
                {dataTimeline.status === 'reviewed' && requestFile ? (
                  <>
                  {submitButton ? (
                      <Typography variant="body2" gutterBottom>Request Document</Typography>
                    ) : (
                      <Typography sx={{color: '#19BBBB'}} variant="body2" gutterBottom>Request Document Success Uploaded</Typography>
                    )}
                    {/* Diagnosis */}
                    {requestFile?.map((dataRequestFile, index) => {
                      if(dataRequestFile.type !== 'claim-diagnosis' || dataRequestFile.check_files !== null){
                        return null;
                      }
                      return (
                        <Stack spacing={2} sx={{marginBottom: 2}} key={index}>
                          <Typography variant="body2" gutterBottom fontWeight="bold">
                            Diagnosis
                          </Typography>
                          <Stack
                              divider={<Divider orientation="horizontal" flexItem />}
                              spacing={1}
                              sx={{ marginY: 2 }}
                          >
                            {fileDiagnosis &&
                            fileDiagnosis.map((file, index) => (
                                <Stack direction="row" justifyContent={'space-between'} key={index}>
                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                        <InsertDriveFileIcon />
                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                    </Stack>
                                    <Iconify
                                        icon="eva:trash-2-outline"
                                        color={'darkred'}
                                        onClick={() => {
                                          removeFileDiagnois(fileDiagnosis, index);
                                        }}
                                        sx={{cursor: 'pointer'}}
                                    ></Iconify>
                                </Stack>
                            ))}
                          </Stack>
                          <ButtonBase
                            sx={{
                              p: 4,
                              border: '2px dashed #F9FAFB',
                              bgcolor: '#919EAB52',
                              borderRadius: '8px',
                              width: '100%',
                              height: '60px',
                            }}
                            onClick={() => fileRequestDocumentInputDiagnosis.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">
                                Add Result
                              </Typography>
                            </Box>
                            <input
                              type="file"
                              id={`file-${index}`}
                              ref={fileRequestDocumentInputDiagnosis}
                              style={{ display: 'none' }}
                              multiple
                              onChange={(event) => handleRequestDocumentInputChangeDiagnosis(event)}
                              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
                            />
                          </ButtonBase>
                        </Stack>
                      );
                    })}
                    {/* Kondisi */}
                    {requestFile?.map((dataRequestFile, index) => {
                      if(dataRequestFile.type !== 'claim-kondisi' || dataRequestFile.check_files !== null){
                        return null;
                      }
                      return (
                        <Stack spacing={2} sx={{marginBottom: 2}} key={index}>
                          <Typography variant="body2" gutterBottom fontWeight="bold">
                            Condition
                          </Typography>
                          <Stack
                              divider={<Divider orientation="horizontal" flexItem />}
                              spacing={1}
                              sx={{ marginY: 2 }}
                          >
                            {fileKondisi &&
                            fileKondisi.map((file, index) => (
                                <Stack direction="row" justifyContent={'space-between'} key={index}>
                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                        <InsertDriveFileIcon />
                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                    </Stack>
                                    <Iconify
                                        icon="eva:trash-2-outline"
                                        color={'darkred'}
                                        onClick={() => {
                                          removeFileKondisi(fileKondisi, index);
                                        }}
                                        sx={{cursor: 'pointer'}}
                                    ></Iconify>
                                </Stack>
                            ))}
                          </Stack>
                          <ButtonBase
                            sx={{
                              p: 4,
                              border: '2px dashed #F9FAFB',
                              bgcolor: '#919EAB52',
                              borderRadius: '8px',
                              width: '100%',
                              height: '60px',
                            }}
                            onClick={() => fileRequestDocumentInputKondisi.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">
                                Add Result
                              </Typography>
                            </Box>
                            <input
                              type="file"
                              id={`file-${index}`}
                              ref={fileRequestDocumentInputKondisi}
                              style={{ display: 'none' }}
                              multiple
                              onChange={(event) => handleRequestDocumentInputChangeKondisi(event)}
                              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
                            />
                          </ButtonBase>
                        </Stack>
                      );
                    })}
                    {/* Supporting Result */}
                    {requestFile?.map((dataRequestFile, index) => {
                      if(dataRequestFile.type !== 'claim-result' || dataRequestFile.check_files !== null){
                        return null;
                      }
                      return (
                        <Stack spacing={2} sx={{marginBottom: 2}} key={index}>
                          <Typography variant="body2" gutterBottom fontWeight="bold">
                            Supporting Result
                          </Typography>
                          <Stack
                              divider={<Divider orientation="horizontal" flexItem />}
                              spacing={1}
                              sx={{ marginY: 2 }}
                          >
                            {fileResult &&
                            fileResult.map((file, index) => (
                                <Stack direction="row" justifyContent={'space-between'} key={index}>
                                    <Stack direction="row" spacing={1} sx={{color: '#19BBBB'}}>
                                        <InsertDriveFileIcon />
                                        <Typography variant="body2" gutterBottom>{file.name ? file.name : '-'}</Typography>
                                    </Stack>
                                    <Iconify
                                        icon="eva:trash-2-outline"
                                        color={'darkred'}
                                        onClick={() => {
                                          removeFileResult(fileResult, index);
                                        }}
                                        sx={{cursor: 'pointer'}}
                                    ></Iconify>
                                </Stack>
                            ))}
                          </Stack>
                          <ButtonBase
                            sx={{
                              p: 4,
                              border: '2px dashed #F9FAFB',
                              bgcolor: '#919EAB52',
                              borderRadius: '8px',
                              width: '100%',
                              height: '60px',
                            }}
                            onClick={() => fileRequestDocumentInputResult.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">
                                Add Result
                              </Typography>
                            </Box>
                            <input
                              type="file"
                              id={`file-${index}`}
                              ref={fileRequestDocumentInputResult}
                              style={{ display: 'none' }}
                              multiple
                              onChange={(event) => handleRequestDocumentInputChangeResult(event)}
                              accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
                            />
                          </ButtonBase>
                        </Stack>
                      );
                    })}
                    {submitButton ? (
                      <LoadingButton
                        variant="contained"
                        sx={{ marginTop: 2, p: 2, backgroundColor: '#19BBBB' }}
                        onClick={() => {
                          submitRequestFiles();
                        }}
                        loading={submitLoading}
                      >
                        Submit
                      </LoadingButton>
                    ) : ''}
                  </>
                ) : ''}
    			   </Stack>
          	</Card>
          </TimelineContent>
        </TimelineItem>
      </Timeline>
      ))}
    </>
  );
}
