import * as Yup from 'yup';
import { LoadingButton } from "@mui/lab";
import { Box, Card, Grid, Stack, Typography } from "@mui/material";
import { Role, UserAccess, Organization } from "../../../@types/user";
import { FormProvider, RHFSelect, RHFSwitch, RHFTextField } from "../../../components/hook-form";
import { useEffect, useMemo } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { useSnackbar } from 'notistack';
import { useNavigate, useParams } from 'react-router-dom';
import axios from '../../../utils/axios';
import palette from '@/theme/palette';

type Props = {
  isEdit: boolean;
  currentUserAccess?: UserAccess;
  roles: Role;
  organizations: Organization;
};

export default function AccsessForm({ isEdit, currentUserAccess, roles, organizations }: Props) {

  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { id } = useParams();

  const NewCorporatePlanSchema = Yup.object().shape({
    name: Yup.string().required('Name is required'),
  });

  console.log(currentUserAccess, 'test')
  const defaultValues = useMemo(
    () => ({
      name: currentUserAccess?.person?.name || '',
      username:  currentUserAccess?.username || '',
      email: currentUserAccess?.email || '',
      roles: currentUserAccess?.role?.id || [],
      organizations: currentUserAccess?.organization_id || [],
      password: '',
    }),
    [currentUserAccess]
  );

  useEffect(() => {
    if (isEdit && currentUserAccess) {
      reset(defaultValues);
    }
    if (!isEdit) {
      reset(defaultValues);
    }
  }, [isEdit, currentUserAccess]);

  const methods = useForm({
    resolver: yupResolver(NewCorporatePlanSchema),
    defaultValues,
  });

  const {
    reset,
    watch,
    control,
    setValue,
    getValues,
    setError,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;


  const onSubmit = async (data: any) => {

    console.log(data);
    if (!isEdit) {
      await axios
      .post('/user/access', data)
      .then((res) => {
        enqueueSnackbar('User created successfully', { variant: 'success' });
      })
      .then((res) => {
        navigate('/user-access',  { replace: true });
      })
      .catch(({ response }) => {
        if (response.status === 422) {
          for (const [key, value] of Object.entries(response.data.errors)) {
            setError(key, { message: value[0] });
            enqueueSnackbar(value[0] ?? 'Failed Processing Request', { variant: 'error' });
          }
        }
        else {
          enqueueSnackbar('Create Failed : '+ response.data.message, { variant: 'error' });
        }
      });
    } else {
      await axios
        .put('/user/access/' + currentUserAccess?.id, data)
        .then((res) => {
          enqueueSnackbar('User updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/user-access' ,  { replace: true });
        })
        .catch(({ response }) => {
          enqueueSnackbar('Update Failed : '+ response.data.message, { variant: 'error' });
        });
    }
  };

  const optionsRoles = roles?.data?.map(item => ({
    value: item.id,
    label: item.name
  })) ?? [];

  if (optionsRoles.length > 0) {
    optionsRoles.unshift({ value: '', label: '' });
  }

  const optionsOrganization = organizations?.data?.map(item => ({
    value: item.id,
    label: item.name
  })) ?? [];

  if (optionsOrganization.length > 0) {
    optionsOrganization.unshift({ value: '', label: '' });
  }

  return (
    <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
        <Box sx={{ px: 2 }}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={12}>
                    <Card sx={{ px: 3, py: 4 }}>
                        <Stack spacing={2}>
                          <Typography variant="h6" color={palette.light.primary.main}>User Access</Typography>
                          <RHFTextField name="name" label="Name" />
                          <RHFTextField name="username" label="Username"  />
                          <RHFTextField type="email" name="email" label="Email" />
                          <RHFTextField type="password" name="password" label="Password" />
                          <RHFSelect name="roles" label="Roles">
                            {optionsRoles.map((option, index) => (
                              <option key={index} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </RHFSelect>
                          <RHFSelect name="organizations" label="organizations">
                            {optionsOrganization.map((option, index) => (
                              <option key={index} value={option.value}>
                                {option.label}
                              </option>
                            ))}
                          </RHFSelect>


                          <LoadingButton type="submit" variant="contained" size="large" fullWidth={true} loading={isSubmitting}>
                              { isEdit? 'Update' : 'Create' }
                          </LoadingButton>

                        </Stack>
                    </Card>
                </Grid>
            </Grid>
        </Box>
      </FormProvider>
  );
}
