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 } 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 } from 'react';
import { makeFormData } from '@/utils/jsonToFormData';

// TODO Fix any
export default function FormRequestClaim({ member, handleSubmitSuccess }) {
  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 [serviceCode, setServiceCode] = useState('IP');

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

  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) => {
        return fileIndex != index;
      })
    );
  };

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

  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) => {
        return fileIndex != index;
      })
    );
  };

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

  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) => {
        return fileIndex != index;
      })
    );
  };

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

  const [submitLoading, setSubmitLoading] = useState(false);
  function submitRequest() {
    setSubmitLoading(true);
    const formData = makeFormData({
      member_id: member.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' });
        handleSubmitSuccess();
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .then(() => {
        setSubmitLoading(false);
      });
  }

  return (
    <Stack>
      <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={member?.full_name ?? ''}
            sx={{ marginTop: 1, width: 48, height: 48 }}
          />
          <Stack sx={{ p: 1 }}>
            <Typography>{member?.full_name ?? ''}</Typography>
            <Typography>{member?.member_id ?? ''}</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={
            100 -
            (member?.current_plan?.limit_rules
              ? (member?.current_plan?.usage ?? 0) / member?.current_plan?.limit_rules
              : 0)
          }
        />
        <Typography sx={{ textAlign: 'right', marginTop: 1 }}>
          {fCurrency(member?.current_plan?.usage ?? 0)} /{' '}
          {member?.current_plan?.limit_rules < 9999999999 ? fCurrency(member?.current_plan?.limit_rules ?? 0) : 'As Charge' }
        </Typography>
      </Card>

      <Stack
        divider={<Divider orientation="horizontal" flexItem />}
        spacing={4}
        sx={{ marginY: 2 }}
      >
        {/* -------------------------------Upload Dokumen Kondisi------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill"></Iconify> Dokumen Kondisi
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </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);
                    }}
                  ></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) } */}
          <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"
          />
          <LoadingButton
            variant="outlined"
            onClick={() => {
              fileKondisiInput.current.click();
            }}
          >
            <Iconify icon="eva:plus-fill" />
            Add Result
          </LoadingButton>
        </Stack>

        {/* -------------------------------Upload Dokumen Diagnosa------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill"></Iconify> 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);
                    }}
                  ></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) } */}
          <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"
          />
          <LoadingButton
            variant="outlined"
            onClick={() => {
              fileDiagnosaInput.current.click();
            }}
          >
            <Iconify icon="eva:plus-fill" />
            Add Result
          </LoadingButton>
        </Stack>

        {/* -------------------------------Upload Dokumen Hasil Penunjang------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" fontWeight={600}>
            <Iconify icon="eva:file-text-fill"></Iconify> Dokumen Hasil Penunjang
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </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);
                    }}
                  ></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) } */}
          <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"
          />
          <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>
  );
}
