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

// 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('');

  // ----------------------------------------------------------------------
  // 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() {
    if(serviceCode == '')
    {
      enqueueSnackbar('Please select services', { variant: 'error' });
      return false;
    }
    setSubmitLoading(true);
    const formData = makeFormData({
      member_id: member.members.id,
      result_files: fileHasilPenunjangs,
      diagnosa_files: fileDiagnosas,
      kondisi_files: fileKondisis,
      service_code: serviceCode
    });
    axios
      .post('/claim-requests', formData)
      .then((response) => {
        enqueueSnackbar(response.data.data.message ?? 'Berhasil membuat data', { variant: 'success' });
        handleSubmitSuccess();
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.data.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .then(() => {
        setSubmitLoading(false);
      });
  }

  return (
    <Stack>
      <Stack direction="row" justifyContent={'end'} sx={{ marginBottom: 2 }} spacing={2}>
        <Typography variant='body2' sx={{color: '#757575'}}>
          Submission Date
        </Typography>
        <Typography variant='body2' sx={{fontWeight:'bold'}}>{format(new Date(), "d MMM yyyy")}</Typography>
      </Stack>
      
      <Stack direction="column" spacing={2} sx={{marginBottom: 2}}>
        <Typography variant="body1" sx={{fontWeight:'bold'}}>
            Services
        </Typography>
        <Card sx={{ p: 1, background: '#f4f6f8', marginBottom: 2 }}>
            <Stack direction="row" spacing={2}>
              {member && member?.services?.map((dataServices, index) => (
                  <Button
                      key={index}
                      sx={{padding: 2, width: '100%'}}
                      color="primary"
                      variant={serviceCode === dataServices.service_code ? 'outlined' : ''}
                      onClick={() => { setServiceCode(dataServices.service_code) }}
                  >
                      {dataServices.name}
                  </Button>
              ))}
          </Stack>
        </Card>

      </Stack>


      <Card sx={{ p: 1, background: '#f4f6f8'}}>
        <Stack direction="row">
          <Avatar
            src="https://minimal-assets-api.vercel.app/assets/images/avatars/avatar_5.jpg"
            alt={member?.members.name ?? ''}
            sx={{ marginTop: 1, width: 48, height: 48 }}
          />
          <Stack sx={{ p: 1 }}>
            <Typography variant="body2">{member?.members.name ?? ''}</Typography>
            <Typography variant="body2" sx={{color:'#637381'}}>{member?.members.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, marginBottom: 6 }}
      >
        {/* -------------------------------Upload Dokumen Kondisi------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
             Condition Document
          </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>
           <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">
                Add Result
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileKondisiInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleKondisiInputChange}
              accept="application/pdf"
            />
          </ButtonBase>
        </Stack>

        {/* -------------------------------Upload Dokumen Diagnosa------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
            Diagnosis Dokument
          </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) } */}
          <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">
                Add Result
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileDiagnosaInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleDiagnosaInputChange}
              accept="application/pdf"
            />
          </ButtonBase>
        </Stack>

        {/* -------------------------------Upload Dokumen Hasil Penunjang------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
            Supporting Result Document
          </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) } */}
          <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">
                Add Result
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileHasilPenunjangInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleResultInputChange}
              accept="application/pdf"
            />
          </ButtonBase>
        </Stack>
      </Stack>

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