// @mui
import { styled } from '@mui/material/styles';
import {
  Button,
  Box,
  LinearProgress,
  linearProgressClasses,
  Stepper,
  Step,
  StepLabel,
  Card,
  Typography,
  Divider,
  Stack,
  Grid,
  Avatar,
  ButtonBase,
} from '@mui/material';
import { Add } from '@mui/icons-material';
// components
import MuiDialog from '../../components/MuiDialog';
/*------------------------------------ icon ----------------------------------- */
import ArrowBackIosIcon from '@mui/icons-material/ArrowBackIos';
// theme
import palette from '../../theme/palette';
// React
import { Fragment, ReactElement, useEffect, useRef, useState } from 'react';
import { useSearchParams, useNavigate, Link } from 'react-router-dom';
import { fPostFormat } from '../../utils/formatTime';
import { fCurrency } from '../../utils/formatNumber';
import { LoadingButton } from '@mui/lab';
import Iconify from '../../components/Iconify';
import { useSelector } from 'react-redux';
import { RootState } from '../../store';
import { makeFormData } from '../../utils/jsonToFormData';
import { useSnackbar } from 'notistack';
import axiosInstance from '../../utils/axios';

// -------------------------------- type --------------------------------------
type DataContentType = {
  id: number;
  fullName: string;
  memberId: string;
  limit: {
    current: number;
    total: number;
    percentage: number;
  };
  avatar?: {
    url?: string;
    title?: string;
  };
};

type ClaimSubmission = {
  id: number;
  personID: string;
  personName: string;
  typePatient: string;
  limit: {
    current: number;
    total: number;
    percentage: number;
  };
  avatar: {
    url: string;
  };
  fileRealInvoice: any[];
  anotherDocument: any[];
  laboratoryResult: any[];
};

type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  data: DataContentType;
};

/* --------------------------------- styles --------------------------------- */
const BorderLinearProgress = styled(LinearProgress)(({ theme }) => ({
  height: 10,
  borderRadius: 6,
  [`&.${linearProgressClasses.colorPrimary}`]: {
    backgroundColor: theme.palette.grey[theme.palette.mode === 'light' ? 300 : 800],
  },
  [`& .${linearProgressClasses.bar}`]: {
    borderRadius: 6,
    background: 'linear-gradient(270deg, #19BBBB 38.42%, #FF9565 76.21%, #FE7253 104.02%)',
  },
}));
/* -------------------------------------------------------------------------- */

const steps = ['Review', 'Approval', 'Disbursement'];

const DialogDetailClaim = ({ title, openDialog, setOpenDialog, data }: MuiDialogProps) => {
  const navigate = useNavigate();
  const { enqueueSnackbar } = useSnackbar();

  const [submitLoading, setSubmitLoading] = useState(false);
  const selectedData = useSelector((state: RootState) => state.claims.data);
  const [dataContent, setDataContent] = useState<ClaimSubmission[]>([]);

  useEffect(() => {
    if (selectedData.length > 0) {
      let temp: ClaimSubmission[] = selectedData.map((item) => ({
        id: item.id,
        avatar: {
          url: '',
        },
        limit: item.limit,
        personID: item.memberId,
        personName: item.fullName,
        typePatient: 'IP',
        service_type: item.service_type,
        anotherDocument: [],
        fileRealInvoice: [],
        laboratoryResult: [],
      }));

      setDataContent(temp);
    } else {
      navigate('/claim-submit', { replace: true });
    }
  }, [selectedData]);

  const handleServiceCode = (data: ClaimSubmission, index?: number) => {
    let temp = dataContent.map((item) => {
      if (item.personID === data.personID) {
        return {
          ...item,
          typePatient: item.typePatient === 'IP' ? 'OP' : 'IP',
        };
      } else {
        return item;
      }
    });

    setDataContent(temp);
  };

  const handleInputFile = (
    event: any,
    data: ClaimSubmission,
    typeFile: 'invoice' | 'another' | 'lab'
  ) => {
    if (event.target.files[0]) {
      let temp = dataContent.map((item) => {
        if (item.personID === data.personID) {
          if (typeFile === 'invoice') {
            return {
              ...item,
              fileRealInvoice: [...item.fileRealInvoice, event.target.files[0]],
            };
          } else if (typeFile === 'another') {
            return {
              ...item,
              anotherDocument: [...item.anotherDocument, event.target.files[0]],
            };
          } else {
            return {
              ...item,
              laboratoryResult: [...item.laboratoryResult, event.target.files[0]],
            };
          }
        } else {
          return item;
        }
      });

      setDataContent(temp);
    } else {
      console.log('NO FILE');
    }
  };

  const handleRemoveFile = (
    data: ClaimSubmission,
    typeFile: 'invoice' | 'another' | 'lab',
    index: number
  ) => {
    let temp = dataContent.map((item) => {
      if (item.personID === data.personID) {
        if (typeFile === 'invoice') {
          return {
            ...item,
            fileRealInvoice: item.fileRealInvoice.filter((file, fileIndex) => fileIndex != index),
          };
        } else if (typeFile === 'another') {
          return {
            ...item,
            anotherDocument: item.anotherDocument.filter((file, fileIndex) => fileIndex != index),
          };
        } else {
          return {
            ...item,
            laboratoryResult: item.laboratoryResult.filter((file, fileIndex) => fileIndex != index),
          };
        }
      } else {
        return item;
      }
    });

    setDataContent(temp);
  };

  const onSubmit = () => {
    setSubmitLoading(true);
    const mapArrayToFormData = (claims: ClaimSubmission[]): FormData => {
      const formData = new FormData();

      claims.forEach((claim, index) => {
        formData.append(`member_id[${index}]`, claim.id.toString());
        formData.append(`service_code[${index}]`, claim.typePatient);

        claim.laboratoryResult.forEach((file, fileIndex) => {
          formData.append(`laboratorium[member_${claim.id}][${fileIndex}]`, file);
        });

        claim.anotherDocument.forEach((file, fileIndex) => {
          formData.append(`prescription[member_${claim.id}][${fileIndex}]`, file);
        });

        claim.fileRealInvoice.forEach((file, fileIndex) => {
          formData.append(`invoice[member_${claim.id}][${fileIndex}]`, file);
        });
      });

      return formData;
    };

    const formData = mapArrayToFormData(dataContent);

    axiosInstance
      .post('/claim-requests', formData)
      .then((response) => {
        enqueueSnackbar(response.data.message ?? 'Berhasil membuat data', { variant: 'success' });
        navigate('/claim-submit', { replace: true });
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .finally(() => {
        setSubmitLoading(false);
      });
  };

  return (
    <>
      <Grid container spacing={8}>
        {/* Field 1 */}
        <Grid item xs={12} paddingX="24px" paddingY="20px">
          <Stack direction="row" alignItems="center">
            <ArrowBackIosIcon
              onClick={() => navigate(`/claim-submit`)}
              sx={{ cursor: 'pointer' }}
            />
            <Typography variant="h5" sx={{ flexGrow: 1 }}>
              Claim Submission{' '}
            </Typography>
            <Typography variant="inherit" sx={{ textAlign: 'center', flexBasis: '15%' }}>
              Submission Date{' '}
            </Typography>
            <Typography textAlign={'right'} variant="h6" sx={{ textAlign: 'right' }}>
              {fPostFormat(new Date(), 'dd MMM yyyy')}
            </Typography>
          </Stack>
        </Grid>
        {dataContent.map((row, index) => {
          return (
            <Grid item xs={12} key={index}>
              <Card sx={{ p: 3 }}>
                <Grid container spacing={4} key={index}>
                 
                  <Grid item xs={12} paddingX="24px" paddingY="20px">
                    <Stack direction="row" spacing={4}>
                        {row.service_type.map((r, i) => {
                          return(
                                <Button
                                  sx={{
                                    padding: 2,
                                    width: '50%',
                                    border:
                                      row.typePatient === r.service_code ? '1px solid #919EAB52' : '1px solid #19BBBB',
                                  }}
                                  variant="outlined"
                                  color={row.typePatient ===  r.service_code  ? 'primary' : 'inherit'}
                                  onClick={() => {
                                    handleServiceCode(row);
                                  }}
                                >
                                  {r.service_code == 'IP' ? 'Inpatient' : 'Outpatient'}
                                </Button>
                                
                          )
                      })}
                          {/* <Button
                            sx={{
                              padding: 2,
                              width: '50%',
                              border:
                                row.typePatient === 'IP' ? '1px solid #919EAB52' : '1px solid #19BBBB',
                            }}
                            variant="outlined"
                            color={row.typePatient === 'OP' ? 'primary' : 'inherit'}
                            onClick={() => {
                              handleServiceCode(row);
                            }}
                          >
                            Outpatient
                          </Button> */}
                        </Stack>
                    </Grid>
                  {/* REAL INVOICE */}
                  <Grid item xs={12}>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <Typography variant="h6">Real Invoice</Typography>
                      </Grid>
                      {row.fileRealInvoice &&
                        row.fileRealInvoice.map((file, fileIndex) => (
                          <Grid item xs={12} key={fileIndex}>
                            <Stack direction="row" justifyContent={'space-between'}>
                              <Typography sx={{ color: 'text.secondary' }}>{file.name}</Typography>
                              <Iconify
                                icon="eva:trash-2-outline"
                                color={'darkred'}
                                onClick={() => {
                                  handleRemoveFile(row, 'invoice', fileIndex);
                                }}
                              />
                            </Stack>
                          </Grid>
                        ))}
                      <Grid item xs={12}>
                        <Box
                          sx={{
                            display: 'flex',
                            placeContent: 'center',
                            placeItems: 'center',
                            border: '2px dashed #F9FAFB',
                            bgcolor: '#919EAB52',
                            borderRadius: '8px',
                            p: 0,
                          }}
                        >
                          <Buttons handle={handleInputFile} row={row} type="invoice" />
                        </Box>
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* DOCTOR'S PRESCRIPTION AND ANOTHER DOCUMENTS  */}
                  <Grid item xs={12}>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <Typography variant="h6">
                          Doctor's Prescription and Another Documents
                        </Typography>
                      </Grid>
                      {row.anotherDocument &&
                        row.anotherDocument.map((file, fileIndex) => (
                          <Grid item xs={12} key={fileIndex}>
                            <Stack direction="row" justifyContent={'space-between'}>
                              <Typography sx={{ color: 'text.secondary' }}>{file.name}</Typography>
                              <Iconify
                                icon="eva:trash-2-outline"
                                color={'darkred'}
                                onClick={() => {
                                  handleRemoveFile(row, 'another', fileIndex);
                                }}
                              />
                            </Stack>
                          </Grid>
                        ))}
                      <Grid item xs={12}>
                        <Box
                          sx={{
                            display: 'flex',
                            placeContent: 'center',
                            placeItems: 'center',
                            border: '2px dashed #F9FAFB',
                            bgcolor: '#919EAB52',
                            borderRadius: '8px',
                            p: 0,
                          }}
                        >
                          <Buttons handle={handleInputFile} row={row} type="another" />
                        </Box>
                      </Grid>
                    </Grid>
                  </Grid>

                  {/* LABORATORY RESULTS   */}
                  <Grid item xs={12}>
                    <Grid container spacing={2}>
                      <Grid item xs={12}>
                        <Typography variant="h6">Laboraroty Results</Typography>
                      </Grid>
                      {row.laboratoryResult &&
                        row.laboratoryResult.map((file, fileIndex) => (
                          <Grid item xs={12} key={fileIndex}>
                            <Stack direction="row" justifyContent={'space-between'}>
                              <Typography sx={{ color: 'text.secondary' }}>{file.name}</Typography>
                              <Iconify
                                icon="eva:trash-2-outline"
                                color={'darkred'}
                                onClick={() => {
                                  handleRemoveFile(row, 'lab', fileIndex);
                                }}
                              />
                            </Stack>
                          </Grid>
                        ))}
                    </Grid>
                    <Grid item xs={12}>
                      <Box
                        sx={{
                          display: 'flex',
                          placeContent: 'center',
                          placeItems: 'center',
                          border: '2px dashed #F9FAFB',
                          bgcolor: '#919EAB52',
                          borderRadius: '8px',
                          p: 0,
                        }}
                      >
                        <Buttons handle={handleInputFile} row={row} type="lab" />
                      </Box>
                    </Grid>
                  </Grid>
                </Grid>
              </Card>
            </Grid>
          );
        })}
        <Grid item xs={12}>
          <LoadingButton
            variant="contained"
            sx={{ marginTop: 2, p: 2, margin: '10px' }}
            fullWidth
            onClick={onSubmit}
            loading={submitLoading}
          >
            Claim Submit
          </LoadingButton>
        </Grid>
      </Grid>
    </>
  );
};

// let temp = [
//   {
//     member: "",
//     result_file: [
//       "file.pdf",
//       "file2.pdf"
//     ]
//   }
// ]

export default DialogDetailClaim;

type ButtonIProp = {
  row: ClaimSubmission;
  type: 'invoice' | 'another' | 'lab';
  handle: (event: any, row: any, type: any) => void;
};

const Buttons = ({ handle, row, type }: ButtonIProp) => {
  const ref = useRef<HTMLInputElement>(null);

  return (
    <ButtonBase sx={{ p: 4 }} onClick={() => ref.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 {type}
        </Typography>
      </Box>
      <input
        ref={ref}
        hidden
        accept="application/pdf"
        type="file"
        name="file"
        multiple
        onChange={(event) => handle(event, row, type)}
      />
    </ButtonBase>
  );
};
