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;
  data?: DataContent[];
};

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

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

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

const DialogTopUpLimit = ({ title, openDialog, setOpenDialog, data }: MuiDialogProps) => {
  const navigate = useNavigate();
  const [dataTableData, setDataTableData] = useState<LaravelPaginatedData>({
    current_page: 1,
    data: [],
    path: '',
    first_page_url: '',
    last_page: 1,
    last_page_url: '',
    next_page_url: '',
    prev_page_url: '',
    per_page: 10,
    from: 0,
    to: 0,
    total: 0,
  });
  
  const { id, service_code, status } = data;

  const isEdit = id ? true : false;

  const NewCorporateSchema = Yup.object().shape({
    reason: Yup.string().required('Corporate Status is required'),
  });


  const methods = useForm<FormValuesProps>({
    resolver: yupResolver(NewCorporateSchema),
  });
  const {
    reset,
    watch,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

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

  // const { plan_id } = useParams();
  const handleActivate = (model: any, status: string) => {
    axios
      .put(`/benefits/${id}/activation`, {
        // service_code: service.service_code,
        active: status == 'active',
        reason: model.reason
      })
      .then((res) => {
        // Memuat ulang halaman saat ini
        setOpenDialog(false)
        window.location.reload();
        // setDataTableData({
        //   ...dataTableData,
        //   data: dataTableData.data.map((service) => {
        //     let updatedService = service;
        //     if (id == service.id) {
        //       updatedService.status = res.data.status;
        //     }
        //     return updatedService;
        //   }),
        // });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const onSubmit = async (row : ReturnType<typeof createData>) => {
    try {
      const data = {
        service_code : service_code,
        reason : row.reason,
        id : id,
      }
      handleActivate(data, status)  
    } catch (error: any) {
      console.log('data gagal', data);
    }

    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 DialogTopUpLimit;