// @mui
import { styled } from '@mui/material/styles';
import {
  Typography,
  LinearProgress,
  linearProgressClasses,
  Stack,
  FormControlLabel,
} from '@mui/material';
import { LoadingButton } from '@mui/lab';
import Checkbox from '@mui/material/Checkbox';
// components
import MuiDialog from '../../components/MuiDialog';
import { FormProvider, RHFTextField } from '../../components/hook-form';
// React
import { useContext, ReactElement, useEffect, useState } from 'react';
import { fCurrency } from '../../utils/formatNumber';
import { UserCurrentCorporateContext } from '../../contexts/UserCurrentCorporate';

// yup
import * as Yup from 'yup';
// form
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import axios from '../../utils/axios';
import { enqueueSnackbar } from 'notistack';

/* ---------------------------------- types --------------------------------- */
type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  data?: DataProps;
};

type DataProps = {
  companyName: string;
  policyNumber: number;
  totalMembers: number;
  totalCases: number;
  totalPersen: number;
  myLimit: {
    balance: number;
    total: number;
    percentage: number;
  };
  maxTopUp: number;
};

type FormValuesProps = {
  topup: string;
};
/* -------------------------------------------------------------------------- */

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%)',
  },
}));

// ----------------------------------------------------------------------

export default function DialogTopUpLimit({
  title,
  openDialog,
  setOpenDialog,
  data,
}: MuiDialogProps) {
  const [isDisabledInput, setIsDisabledInput] = useState(false);
  const [isDisabledButton, setIsDisabledButton] = useState(true);
  const [isCheckboxChecked, setIsCheckboxChecked] = useState(false);
  const [ message, setMessage ] = useState ('');
  const { corporateValue } = useContext(UserCurrentCorporateContext);

  const TopUpSchema = Yup.object().shape({
    topup: Yup.number().max(
      data?.maxTopUp,
      `Maximum top-up amount is ${fCurrency(data?.maxTopUp)}`
    ),
  });

  const defaultValues = {
    topup: 0,
  };

  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(TopUpSchema),
    // @ts-ignore
    defaultValues,
  });

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

  useEffect(() => {
    if (openDialog === false) {
      setIsDisabledInput(false);
      setIsDisabledButton(true);
      setIsCheckboxChecked(false);

      reset();
    }
  }, [openDialog, reset]);

  const onSubmit = async (data: FormValuesProps) => {
    
    
    await new Promise((resolve) => setTimeout(resolve, 500));

    setIsDisabledInput(false);
    setIsDisabledButton(true);
    setIsCheckboxChecked(false);

    try {
      // Send the HTTP POST request to the backend
      await axios.post(corporateValue + '/topup', {
        topup: data.topup,
      });
  
      // Show a success notification
      enqueueSnackbar('The request has been sent', { variant: 'success' });
      setOpenDialog(false);
  
      reset();
    } catch (error) {
      // Show an error notification
      enqueueSnackbar('An error occurred', { variant: 'error' });
      setOpenDialog(false);
    }
    
    
  };

  const onCheckHandler = (value: string) => {
    setIsDisabledInput(!isDisabledInput);
    value === '0' || value === '' ? setIsDisabledButton(true) : setIsDisabledButton(false);
    setIsCheckboxChecked(!isCheckboxChecked);
    // @ts-ignore
    setValue('topup', data.maxTopUp.toString());
  };

  const onTopupHandler = (value: string) => {
    console.log(!!errors);

    let newValue;

    if (value.startsWith('0')) {
      newValue = '0';
    } else {
      newValue = value;
    }

    newValue === '0' || newValue === '' ? setIsDisabledButton(true) : setIsDisabledButton(false);
    setValue('topup', newValue);
  };

  const getContent = () => (
    <Stack spacing={1} marginTop={2}>
      <Stack>
        <Typography variant="caption" color="#637381">
          Company Name
        </Typography>
        <Typography variant="body2">{data ? data.companyName : ''}</Typography>
      </Stack>
      <Stack>
        <Typography variant="caption" color="#637381">
          Policy Number
        </Typography>
        <Typography variant="body2">{data ? data.policyNumber : 0}</Typography>
      </Stack>
      <Stack direction="row" spacing={22}>
        <Stack>
          <Typography variant="caption" color="#637381">
            Total Member
          </Typography>
          <Typography variant="body2">{data ? data.totalMembers : 0} Person</Typography>
        </Stack>
        <Stack>
          <Typography variant="caption" color="#637381">
            Total Cases
          </Typography>
          <Typography variant="body2">{data ? data.totalCases : 0} Cases</Typography>
        </Stack>
      </Stack>
      <Stack spacing={1} sx={{ backgroundColor: '#F4F6F8', borderRadius: 1.5, padding: 2 }}>
        <Stack direction="row" justifyContent="space-between" alignItems="center">
          <Stack>
            <Typography variant="body2">Company Pooled Fund</Typography>
            <Typography variant="body2">{fCurrency(data ? data.myLimit.balance : 0)}</Typography>
            <Typography variant="caption" color="#919EAB">
              / {data ? data.myLimit.total : 0}
            </Typography>
          </Stack>
          <Stack>
            <Typography variant="h5">{data ? data.myLimit.percentage : 0}%</Typography>
          </Stack>
        </Stack>
        <BorderLinearProgress variant="determinate" value={data ? data.myLimit.percentage : 0} />
      </Stack>
      <Stack spacing={2}>
        <Typography variant="subtitle1" marginTop={3}>
          Top Up Limit
        </Typography>
        <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
          <RHFTextField
            name="topup"
            label="Top Up"
            type="number"
            disabled={isDisabledInput}
            onChange={(e) => onTopupHandler(e.target.value)}
            error={!!errors.topup}
            helperText={errors.topup?.message}
          />
          <FormControlLabel
            name="checkboxTopUp"
            sx={{ typography: 'caption' }}
            control={
              <Checkbox
                checked={isCheckboxChecked}
                onChange={(e) => onCheckHandler(e.target.value)}
              />
            }
            label={'Max ' + fCurrency(data ? data.maxTopUp : 0)}
          />

          <LoadingButton
            fullWidth
            size="large"
            type="submit"
            variant="contained"
            loading={isSubmitting}
            sx={{ marginTop: 2 }}
            disabled={isDisabledButton}
          >
            Ajukan Permintaan
          </LoadingButton>
        </FormProvider>
      </Stack>
    </Stack>
  );

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