// @mui
import { styled } from '@mui/material/styles';
import {
  Typography,
  LinearProgress,
  linearProgressClasses,
  Stack,
  Card,
  Button,
  Link,
  Switch,
  SwitchProps,
  ButtonGroup,
} from '@mui/material';
import { Add as AddIcon, Cancel as CancelIcon } from '@mui/icons-material';
// components
import MuiDialog from '../../components/MuiDialog';
import Iconify from '../../components/Iconify';
import { FormProvider } from '../../components/hook-form';
// React
import { ReactElement, useEffect, useState } from 'react';
// yup
import * as Yup from 'yup';
// form
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { LoadingButton } from '@mui/lab';
import { fSplit } from '../../utils/formatNumber';

/* ---------------------------------- 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;
};

type BorderLinearProgressProps = {
  percentage: number;
};

type FormValuesProps = {
  invoice: '';
};
/* -------------------------------------------------------------------------- */

/* --------------------------------- styles --------------------------------- */
const BorderLinearProgress = styled(LinearProgress)<BorderLinearProgressProps>(
  ({ theme, percentage }) => ({
    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%)',
      '&::before': {
        content: '""',
        position: 'absolute',
        right: 0,
        top: 0,
        width: `${100 - percentage}%`,
        zIndex: 1,
        bottom: 0,
        background: '#DFE3E8',
      },
    },
  })
);
/* -------------------------------------------------------------------------- */

const DialogClaimSubmitMemberSubmission = ({
  title,
  openDialog,
  setOpenDialog,
  data,
}: MuiDialogProps) => {
  /* ---------------------------- Get Current Date ---------------------------- */
  const current = new Date();
  const date = `${current.getDate()} / ${current.getMonth() + 1} / ${current.getFullYear()}`;
  /* -------------------------------------------------------------------------- */

  /* ------------------------------- file input ------------------------------- */
  // const [multipleImages, setMultipleImages] = useState([]);

  // Functions to preview multiple images
  // const changeMultipleFiles = (e) => {
  //   if (e.target.files) {
  //     const imageArray = Array.from(e.target.files).map((file) => URL.createObjectURL(file));
  //     setMultipleImages((prevImages) => prevImages.concat(imageArray));
  //   }
  // };

  // const render = (data) => {
  //   data.map((image) => {
  //     <Typography key={image}>{image}</Typography>;
  //   });
  // };

  // const FileForm = (props: any) => (
  //   <input
  //     type="file"
  //     multiple
  //     {...register('invoice', { required: true })}
  //     onChange={changeMultipleFiles}
  //   />
  // );
  /* -------------------------------------------------------------------------- */

  /* ------------------------------- Form Submit ------------------------------ */
  const ClaimSubmitSchema = Yup.object().shape({
    invoice: Yup.mixed()
      .required('You need to provide a file')
      // @ts-ignore
      .test('fileSize', 'The file is too large', (value) => {
        for (let index = 0; index < value.length; index++) {
          return value ? value[index].size <= 2000000 : false;
        }
      }),
  });

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(ClaimSubmitSchema),
  });

  const {
    register,
    reset,
    handleSubmit,
    formState: { isSubmitting, errors },
  } = methods;

  // const {
  //   register,
  //   reset,
  //   handleSubmit,
  //   formState: { isSubmitting },
  // } = useForm({ resolver: yupResolver(ClaimSubmitSchema) });

  const onSubmit = ({ invoice }: FormValuesProps) => {
    // console.log(invoice);
  };
  /* -------------------------------------------------------------------------- */

  /* ---------------------------- Ios Switch Style ---------------------------- */
  const IosSwitch = styled((props: SwitchProps) => (
    <Switch focusVisibleClassName=".Mui-focusVisible" disableRipple {...props} />
  ))(({ theme }) => ({
    width: 28,
    height: 16,
    padding: 0,
    marginRight: '10px',
    '& .MuiSwitch-switchBase': {
      padding: 0,
      margin: 2,
      transitionDuration: '300ms',
      '&.Mui-checked': {
        transform: 'translateX(12px)',
        color: '#fff',
        '& + .MuiSwitch-track': {
          opacity: 1,
          border: 0,
        },
        '&.Mui-disabled + .MuiSwitch-track': {
          opacity: 0.5,
        },
      },
      '&.Mui-focusVisible .MuiSwitch-thumb': {
        color: '#33cf4d',
        border: '6px solid #fff',
      },
      '&.Mui-disabled .MuiSwitch-thumb': {
        color: theme.palette.mode === 'light' ? theme.palette.grey[100] : theme.palette.grey[600],
      },
      '&.Mui-disabled + .MuiSwitch-track': {
        opacity: theme.palette.mode === 'light' ? 0.7 : 0.3,
      },
    },
    '& .MuiSwitch-thumb': {
      boxSizing: 'border-box',
      width: 12,
      height: 12,
    },
    '& .MuiSwitch-track': {
      borderRadius: 26 / 2,
      opacity: 1,
      transition: theme.transitions.create(['background-color'], {
        duration: 500,
      }),
    },
  }));
  /* -------------------------------------------------------------------------- */

  useEffect(() => {
    if (openDialog === false) {
      reset();
    }
  }, [openDialog, reset]);

  const getContent = () => (
    <Stack>
      <Stack direction="row" justifyContent="space-between" alignItems="center" paddingY={1}>
        <Typography variant="subtitle1">Claim Submission</Typography>
        <Stack sx={{ color: '#757575' }}>
          <Typography variant="caption">Submission date</Typography>
          <Typography variant="caption">{date}</Typography>
        </Stack>
      </Stack>
      <Card sx={{ paddingY: 1, paddingX: 2, marginTop: 2, backgroundColor: '#F4F6F8' }}>
        <Stack direction="row" alignItems="center" spacing={2}>
          <img
            width={40}
            height={40}
            src="/images/member.png"
            alt="user-profile"
            style={{ borderRadius: '50%' }}
          />
          <Stack sx={{ flex: '45%' }}>
            <Typography variant="subtitle1">{data && data.fullName}</Typography>
            <Typography color="#637381" variant="body2" sx={{ fontWeight: 500 }}>
              Member ID : {data && data.memberId}
            </Typography>
          </Stack>
        </Stack>
      </Card>
      <Card sx={{ paddingY: 1, paddingX: 2, marginTop: 2 }}>
        <Stack spacing={1} paddingY={1}>
          <Stack direction="row" justifyContent="space-between">
            <Typography color="#0A0A0A" variant="caption">
              Total Limit
            </Typography>
            <Link variant="caption" textAlign="center" href="#">
              Details Benefits <Iconify icon="ic:round-chevron-right" />
            </Link>
          </Stack>
          <BorderLinearProgress
            variant="determinate"
            value={100}
            percentage={data && data.limit ? data.limit.percentage : 100}
          />
          <Typography variant="subtitle2" sx={{ fontWeight: 500 }}>
            {fSplit(data && data.limit ? data.limit.current : 0)} /{' '}
            <Typography variant="body2" color="#757575" component="span">
              {fSplit(data && data.limit ? data.limit.total : 0)}
            </Typography>
          </Typography>
        </Stack>
      </Card>
      <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
        {/* Invoice */}
        <Stack marginTop={2} spacing={1}>
          <Stack>
            <Typography variant="subtitle2">Real Invoice</Typography>
            <Typography color="#9E9E9E" variant="caption">
              Real invoice required
            </Typography>
          </Stack>
          <input {...register('invoice')} type="file" />
          {errors.invoice && errors.invoice.message ? <p>{errors.invoice.message}</p> : ''}
        </Stack>
        {/* Prescription */}
        {/* <Stack marginTop={2} spacing={1}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Stack>
              <Typography variant="subtitle2">
                Doctor's Prescription and Another Documents
              </Typography>
              <Typography color="#9E9E9E" variant="caption">
                Doctor's Prescription required
              </Typography>
            </Stack>
            <Stack
              direction="row"
              padding={1}
              alignItems="center"
              sx={{
                backgroundColor: 'white',
                border: '1px solid #E0E0E0',
                borderRadius: '6px',
                height: 32,
              }}
            >
              <IosSwitch defaultChecked />
              <Typography color="#404040" variant="body2">
                Yes
              </Typography>
            </Stack>
          </Stack>
          <ImportForm label="Add Prescription" />
        </Stack> */}
        {/* Laboratory */}
        {/* <Stack marginTop={2} spacing={1}>
          <Stack direction="row" justifyContent="space-between" alignItems="center">
            <Stack>
              <Typography variant="subtitle2">
                Doctor's Prescription and Another Documents
              </Typography>
              <Typography color="#9E9E9E" variant="caption">
                Doctor's Prescription required
              </Typography>
            </Stack>
            <Stack
              direction="row"
              padding={1}
              alignItems="center"
              sx={{
                backgroundColor: 'white',
                border: '1px solid #E0E0E0',
                borderRadius: '6px',
                height: 32,
              }}
            >
              <IosSwitch defaultChecked />
              <Typography color="#404040" variant="body2">
                Yes
              </Typography>
            </Stack>
          </Stack>
          <ImportForm label="Add Result" />
        </Stack> */}
        {/* Submit */}
        <Stack marginTop={1}>
          <LoadingButton
            fullWidth
            size="large"
            type="submit"
            variant="contained"
            loading={isSubmitting}
            sx={{ marginTop: 2 }}
          >
            Ajukan Permintaan
          </LoadingButton>
        </Stack>
      </FormProvider>
    </Stack>
  );

  return (
    <>
      <MuiDialog
        title={title}
        openDialog={openDialog}
        setOpenDialog={setOpenDialog}
        content={getContent()}
        maxWidth="sm"
      />
    </>
  );
};

export default DialogClaimSubmitMemberSubmission;
