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 } from '@mui/material';
import { CorporateService } from '../../@types/corporates';
// components
import { FormProvider, RHFTextField, RHFSwitch, RHFSelect } from '../../components/hook-form';
import axios from '../../utils/axios';
import { LaravelPaginatedData } from '../../@types/paginated-data';

// import { Contact } from '../../../../@types/contact';
import { Link, useParams, useSearchParams } from 'react-router-dom';

// @mui
// components
import MuiDialog from '../../components/MuiDialog';
// React
import { ReactElement } from 'react';

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

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

type DataContent = {
  info: string;
  date: string;
  time: string;
};

type MuiDialogProps = {
  title?: {
    name?: string;
    icon?: string;
  };
  openDialog: boolean;
  setOpenDialog: Function;
  content?: ReactElement;
  id: number;
};

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

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

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

const DialogUpdateStatus = ({ title, openDialog, setOpenDialog, id }: MuiDialogProps) => {
  const NewCorporateSchema = Yup.object().shape({
    reason: Yup.string().required('Corporate Status is required'),
  });

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

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


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

  const handleActivate = (id: number, status: string) => {
    axios
        .put(`/corporates/${id}/activation`, {
          active: status == 'active',
        })
        .then((res) => {
         console.log(res)
        enqueueSnackbar(
          'Succes',
          { variant: 'success' }
        );
        })
        .catch((error) => {
          // console.log('asdasd', error.response.data.message)
          enqueueSnackbar(
            error.response.data.message ?? error.message ?? 'Failed Processing Request',
            { variant: 'error' }
          );
        });
  };

  const onSubmit = async (row : ReturnType<typeof createData>) => {
    try {
      handleActivate(1, 'active')
    } catch (error: any) {

    }

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

  function createData(corporateService: CorporateService): CorporateService {
    return {
      ...corporateService,
    };
  }
  
  const getContent = (props: { row: ReturnType<typeof createData> }) => (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
      <Stack spacing={3}>
        <Box sx={{ width: '100%', typography: 'body1', p: 2, mt: 1 }}>
          <Grid item xs={12}>
            <RHFSelect
                  name="reason"
                  label="Reason for update"
                >
              <option value=""></option>
              <option value="Agreement changed">Agreement changed</option>
              <option value="Endorsement">Endorsement</option>
              <option value="Renewal">Renewal</option>
              <option value="Worng Setting">Worng Setting</option>
            </RHFSelect>
          </Grid>

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

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

export default DialogUpdateStatus;