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

export default function DialogClaimSubmit({ member, getData, onClose, handleSubmitSuccess }: any) {
    const { localeData }: any =  useContext(LanguageContext);

  // ----------------------------------------------------------------------
  // Files Result Tambahan

  const fileAdditionalInput = useRef<HTMLInputElement>(null);
  const [fileAdditionals, setFileAdditionals] = useState<any>([]);

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

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

  const [submitLoading, setSubmitLoading] = useState(false);
  function submitRequestClaim() {
    setSubmitLoading(true);
    const formData = makeFormData({
      request_logs_id: member.id,
      service_code: member.service_code,
      member_id: member.member_id,
      additional_files: fileAdditionals
    });
    axios
      .post('/claim-requests', formData)
      .then((response) => {
        enqueueSnackbar(response.data.meta.message ?? 'Berhasil membuat data', { variant: 'success' });
        handleSubmitSuccess();
        onClose({ someData: 'example data' }, getData);
      })
      .catch(({ response }) => {
        enqueueSnackbar(response.data.meta.message ?? 'Something Went Wrong', { variant: 'error' });
      })
      .then(() => {
        setSubmitLoading(false);
      });
  }

  return (
    <Stack>
      <Stack direction="row" justifyContent={'end'} sx={{ marginBottom: 2, marginTop: 2 }} spacing={2}>
        <Typography variant='body2' sx={{color: '#757575'}}>
          {localeData.txtDialogMember5}
        </Typography>
        <Typography variant='body2' sx={{fontWeight:'bold'}}>{format(member?.submission_date ? new Date(member.submission_date) : new Date(), "d MMM yyyy")}</Typography>
      </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?.full_name ?? ''}
            sx={{ marginTop: 1, width: 48, height: 48 }}
          />
          <Stack sx={{ p: 1 }}>
            <Typography variant="body2">{member?.full_name ?? ''}</Typography>
            <Typography variant="body2" sx={{color:'#637381'}}>{member?.no_polis ?? ''}</Typography>
          </Stack>
        </Stack>
      </Card>

      <Stack
        divider={<Divider orientation="horizontal" flexItem />}
        spacing={4}
        sx={{ marginY: 2, marginBottom: 6 }}
      >
        {/* -------------------------------Upload Dokumen Tambahan------------------------------- */}
        <Stack sx={{ marginTop: 2 }}>
          <Typography variant="body1" sx={{fontWeight:'bold'}}>
             {localeData.txtAdditionalDocuments}
          </Typography>
          {/* <Typography variant="body2">Hasil Lab, </Typography> */}
          <Stack
            divider={<Divider orientation="horizontal" flexItem />}
            spacing={1}
            sx={{ marginY: 2 }}
          >
            {fileAdditionals &&
              fileAdditionals.map((file:any, index:any) => (
                <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(fileAdditionals, index);
                    }}
                  ></Iconify>
                </Stack>
              ))}
          </Stack>
           <ButtonBase sx={{ p: 4, border: '2px dashed #F9FAFB',
                bgcolor: '#919EAB52',
                borderRadius: '8px',
                width: '100%', height: '60px'}} onClick={() => fileAdditionalInput.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">
                {localeData.txtAddResult}
              </Typography>
            </Box>
            <input
              type="file"
              id="file"
              ref={fileAdditionalInput}
              style={{ display: 'none' }}
              multiple
              onChange={handleKondisiInputChange}
              accept="application/pdf"
            />
          </ButtonBase>
        </Stack>
      </Stack>

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