import * as Yup from 'yup';
import { enqueueSnackbar, useSnackbar } from 'notistack';
import { useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
// @mui
import { styled } from '@mui/material/styles';
import { LoadingButton } from '@mui/lab';
import {
  Box,
  Button,
  Grid,
  Stack,
  Typography,
  Chip,
  Autocomplete,
  InputAdornment,
  IconButton,
} from '@mui/material';

// components
import { FormProvider, RHFTextField, RHFSwitch } from '../../components/hook-form';
import axios from '../../utils/axios';
import { JWTContextType } from '../../@types/auth';

// @mui
import { LinearProgress, linearProgressClasses, FormControlLabel } from '@mui/material';
import Checkbox from '@mui/material/Checkbox';
// components
import MuiDialog from '../../components/MuiDialog';
// React
import { ReactElement } from 'react';
import { Users } from '../../@types/user';
import Iconify from '../../components/Iconify';

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

const HeaderStyle = styled('header')(({ theme }) => ({
  display: 'flex',
  alignItems: 'center',
  padding: theme.spacing(2),
  justifyContent: 'space-between',
}));

const LabelStyle = styled(Typography)(({ theme }) => ({
  ...theme.typography.h6,
  marginBottom: theme.spacing(2),
  marginTop: theme.spacing(2),
}));
type DataContent = {
  info: string;
  date: string;
  time: string;
};

type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  data?: DataContent[];
};

type FormValuesProps = {
  value: string;
  active: boolean;
};

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

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

const DialogFormPassword = ({ title, openDialog, setOpenDialog, data }: MuiDialogProps) => {
  const [isDisabledCheckbox, setIsDisabledCheckbox] = useState(false);
  const [isDisabledButton, setIsDisabledButton] = useState(true);
  const navigate = useNavigate();

  const id = data;

  const isEdit = id ? true : false;

  // eslint-disable-next-line @typescript-eslint/no-redeclare
  // const [currentUsers, setCurrentUsers] = useState<JWTContextType>();
  const [currentUsers, setCurrentUsers] = useState<Users>();
  console.log('usernya masuk', currentUsers);
  useEffect(() => {
    if (isEdit) {
      axios.get('/user/' + id).then((res) => {
        setCurrentUsers(res.data);
      });
    }
  }, [id]);

  const Title = styled(Typography)(({ theme }) => ({
    ...theme.typography.h4,
    boxShadow: 'none',
    fontWeight: 700,
    color: '#005B7F',
  }));

  console.log('currentUsers', currentUsers);

  console.log('data Id masuk', data);

  // const NewCorporateSchema = Yup.object().shape({
  //   active: Yup.boolean().required('Corporate Status is required'),
  //   // file: Yup.boolean().required('Corporate Status is required'),
  // });

  // const defaultValues = useMemo(
  //   () => ({
  //     id: currentUsers?.id || '',
  //     name: currentUsers?.name || '',
  //     value: currentUsers?.value || '',
  //     active: currentUsers?.active === 1 ? true : false,
  //   }),
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  //   [currentUsers]
  // );

  interface FormValuesProps extends Partial<Banner> {
    taxes: boolean;
    inStock: boolean;
  }

  type Props = {
    isEdit: boolean;
    currentBanners?: Banner;
  };

  // const profileSchema = Yup.object().shape({
  //   // password: Yup.string().required('katasandilama is required'),
  //   // katasandibaru: Yup.string().required('katasandibaru is required'),
  //   // konfirmasikatasandi: Yup.string().required('konfirmasikatasandi is required'),
  // });

  // const defaultValues = useMemo(
  //   () => ({
  //     new_password: currentUsers?.new_password,
  //     password2: currentUsers?.password2,
  //   }),
  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  //   [currentUsers]
  // );

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

  // console.log('defaultValues', defaultValues);
  const {
    reset,
    watch,
    control,
    setValue,
    setError,
    getValues,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  const values = watch();

  // useEffect(() => {
  //   if (isEdit && currentUsers) {
  //     reset(defaultValues);
  //   }
  //   if (!isEdit) {
  //     reset(defaultValues);
  //   }

  //   // eslint-disable-next-line react-hooks/exhaustive-deps
  // }, [isEdit, currentUsers]);

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

  const onSubmit = async (data: FormValuesProps) => {
    console.log('data', data);
    // const formData = new FormData();
    // formData.append('password', password);
    // formData.append('passworrd')

    try {
      if (!isEdit) {
        const response = await axios.post('/reset-password', data);
      } else {
        const response = await axios.put('/reset-password/', data);
      }

      reset();
      enqueueSnackbar(
        !isEdit ? 'Password Created Successfully!' : 'Password Updated Successfully!',
        {
          variant: 'success',
        }
      );

      setOpenDialog(false);
      // navigate(0);

      // window.location.reload();
      // navigate('/general/bantuan/contact', { replace: true });
    } catch (error: any) {
      if (error && error.response.status === 422) {
        for (const [key, value] of Object.entries(error.response.data.errors)) {
          setError(key, { message: value[0] });
          enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
        }
      } else {
        enqueueSnackbar(error.message ?? 'Failed Processing Request', { variant: 'error' });
      }
    }

    const ascent = document?.querySelector('ascent');
    if (ascent != null) {
      ascent.innerHTML = '';
    }
  };

  const [showPasswordOld, setShowPasswordOld] = useState(false);
  const [showPasswordNew, setShowPasswordNew] = useState(false);
  const [showPasswordConfirmNew, setShowPasswordConfirmNew] = useState(false);

  const getContent = () => (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <HeaderStyle>
        <Title>Ubah Kata Sandi</Title>
      </HeaderStyle>
      <Stack spacing={3}>
        <Box sx={{ width: '100%', typography: 'body1', p: 2 }}>
          <Grid item xs={12}>
            <LabelStyle>Kata Sandi Lama </LabelStyle>
            <RHFTextField
              name="old_password"
              label="Kata Sandi Lama"
              type={showPasswordOld ? 'text' : 'password'}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => setShowPasswordOld(!showPasswordOld)} edge="end">
                      <Iconify icon={showPasswordOld ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </Grid>

          <Grid item xs={12}>
            <LabelStyle>Kata Sandi Baru </LabelStyle>
            <RHFTextField
              name="new_password"
              label="Kata Sandi Baru"
              type={showPasswordNew ? 'text' : 'password'}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton onClick={() => setShowPasswordNew(!showPasswordNew)} edge="end">
                      <Iconify icon={showPasswordNew ? 'eva:eye-fill' : 'eva:eye-off-fill'} />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </Grid>

          <Grid item xs={12}>
            <LabelStyle>Konfirmasi Kata Sandi </LabelStyle>
            <RHFTextField
              name="confirm_new_password"
              label="Konfirmasi Kata Sandi"
              type={showPasswordConfirmNew ? 'text' : 'password'}
              InputProps={{
                endAdornment: (
                  <InputAdornment position="end">
                    <IconButton
                      onClick={() => setShowPasswordConfirmNew(!showPasswordConfirmNew)}
                      edge="end"
                    >
                      <Iconify
                        icon={showPasswordConfirmNew ? 'eva:eye-fill' : 'eva:eye-off-fill'}
                      />
                    </IconButton>
                  </InputAdornment>
                ),
              }}
            />
          </Grid>

          <Box sx={{ width: '100%', pt: 5 }}>
            <Stack
              alignItems="center"
              justifyContent="end"
              direction={{ xs: 'column', md: 'row' }}
              // sx={{ textAlign: { xs: 'center', md: 'left' } }}
            >
              <Stack direction="row" spacing={1}>
                <Button
                  sx={{
                    boxShadow: 'none',
                  }}
                  variant="outlined"
                  size="medium"
                  fullWidth={true}
                  onClick={() => setOpenDialog(false)}
                >
                  Batal
                </Button>
                <LoadingButton
                  sx={{ boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)' }}
                  type="submit"
                  variant="contained"
                  size="medium"
                  fullWidth={true}
                  loading={isSubmitting}
                >
                  {!isEdit ? 'Simpan' : 'Simpan'}
                </LoadingButton>
              </Stack>
            </Stack>
          </Box>
        </Box>
      </Stack>
    </FormProvider>
  );

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

export default DialogFormPassword;
