// @mui
import { styled } from '@mui/material/styles';
import {
  Typography,
  LinearProgress,
  linearProgressClasses,
  Stack,
  Card,
  Button,
  Divider,
  Avatar,
} from '@mui/material';
// components
import MuiDialog from '../../components/MuiDialog';
import Iconify from '../../components/Iconify';
// React
import { ReactElement, useRef, useState } from 'react';
// form
import { LoadingButton } from '@mui/lab';
import axios from '../../utils/axios';
import { enqueueSnackbar } from 'notistack';
import { fPostFormat } from '../../utils/formatTime';
import { fCurrency } from '../../utils/formatNumber';
import { makeFormData } from '../../utils/jsonToFormData';

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

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 DialogRequestLog = ({ openDialog, setOpenDialog, data }: MuiDialogProps) => {
  const [serviceCode, setServiceCode] = useState('IP');

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

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

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

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

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

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

  const [submitLoading, setSubmitLoading] = useState(false);
  function submitRequest() {
    setSubmitLoading(true);
    const formData = makeFormData({
      member_id: data.id,
      result_files: fileHasilPenunjangs,
      diagnosa_files: fileDiagnosas,
      kondisi_files: fileKondisis,
      service_code: serviceCode,
    });

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

  const getContent = () => (
    <Stack paddingY={1}>
      <Stack direction="row" justifyContent={'end'} sx={{ marginBottom: 2 }}>
        <Typography textAlign={'right'} variant="body2">
          Submission Date : <br /> {fPostFormat(new Date(), 'dd/MM/yyyy')}
        </Typography>
      </Stack>

      <Card sx={{ p: 1, background: '#f4f6f8', marginBottom: 2 }}>
        <Stack direction="row" spacing={2}>
          <Button
            sx={{ padding: 2, width: '100%' }}
            variant={serviceCode == 'IP' ? 'contained' : ''}
            onClick={() => {
              setServiceCode('IP');
            }}
          >
            Rawat Inap
          </Button>
          <Button
            sx={{ padding: 2, width: '100%' }}
            variant={serviceCode == 'OP' ? 'contained' : ''}
            onClick={() => {
              setServiceCode('OP');
            }}
          >
            Rawat Jalan
          </Button>
        </Stack>
      </Card>

      <Card sx={{ p: 1, background: '#f4f6f8', marginBottom: 2 }}>
        <Stack direction="row">
          <Avatar
            src="https://minimal-assets-api.vercel.app/assets/images/avatars/avatar_5.jpg"
            alt={data.fullName}
            sx={{ marginTop: 1, width: 48, height: 48 }}
          />
          <Stack sx={{ p: 1 }}>
            <Typography>{data.fullName}</Typography>
            <Typography>{data.memberId}</Typography>
          </Stack>
        </Stack>
      </Card>

      <Card sx={{ paddingY: 1, paddingX: 2 }}>
        <Typography variant="body1" sx={{ marginBottom: 1, fontWeight: 600 }}>
          Total Limit
        </Typography>
        <BorderLinearProgress variant="determinate" value={data.limit.percentage} />
        <Typography sx={{ textAlign: 'right', marginTop: 1 }}>
          {fCurrency(data.limit.current)} / {fCurrency(data.limit.total)}
        </Typography>
      </Card>

      <Stack
        divider={<Divider orientation="horizontal" flexItem />}
        spacing={4}
        sx={{ marginY: 2 }}
      >
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill" /> Dokumen Kondisi
          </Typography>
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileKondisis &&
              fileKondisis.map((file, index) => (
                <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);
                    }}
                  />
                </Stack>
              ))}
          </Stack>
          <input
            type="file"
            id="file"
            ref={fileKondisiInput}
            style={{ display: 'none' }}
            multiple
            onChange={handleKondisiInputChange}
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
          />
          <LoadingButton
            variant="outlined"
            onClick={() => {
              fileKondisiInput?.current?.click();
            }}
          >
            <Iconify icon="eva:plus-fill" />
            Add Result
          </LoadingButton>
        </Stack>

        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill" /> Dokumen Diagnosa
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </Typography> */}
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileDiagnosas &&
              fileDiagnosas.map((file, index) => (
                <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);
                    }}
                  />
                </Stack>
              ))}
          </Stack>
          <input
            type="file"
            id="file"
            ref={fileDiagnosaInput}
            style={{ display: 'none' }}
            multiple
            onChange={handleDiagnosaInputChange}
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
          />
          <LoadingButton
            variant="outlined"
            onClick={() => {
              fileDiagnosaInput?.current?.click();
            }}
          >
            <Iconify icon="eva:plus-fill" />
            Add Result
          </LoadingButton>
        </Stack>

        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill" /> Dokumen Hasil Penunjang
          </Typography>
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileHasilPenunjangs &&
              fileHasilPenunjangs.map((file, index) => (
                <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);
                    }}
                  />
                </Stack>
              ))}
          </Stack>
          <input
            type="file"
            id="file"
            ref={fileHasilPenunjangInput}
            style={{ display: 'none' }}
            multiple
            onChange={handleResultInputChange}
            accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/plain, application/pdf"
          />
          <LoadingButton
            variant="outlined"
            onClick={() => {
              fileHasilPenunjangInput?.current?.click();
            }}
          >
            <Iconify icon="eva:plus-fill" />
            Add File
          </LoadingButton>
        </Stack>
      </Stack>

      <LoadingButton
        variant="contained"
        sx={{ marginTop: 2, p: 2 }}
        onClick={() => {
          submitRequest();
        }}
        loading={submitLoading}
      >
        LOG Request
      </LoadingButton>
    </Stack>
  );

  return (
    // <>
    //   <MuiDialog
    //     title={{ name: data.fullName }}
    //     openDialog={openDialog}
    //     setOpenDialog={setOpenDialog}
    //     content={getContent()}
    //     maxWidth="sm"
    //   />
    // </>
    getContent()
  );
};

export default DialogRequestLog;
