import * as Yup from 'yup';
import { LoadingButton } from "@mui/lab";
import {Box, Card, FormControlLabel, Grid, Stack, Typography } from "@mui/material";
import Autocomplete from '@mui/material/Autocomplete';
import TextField from '@mui/material/TextField';
import { Role } from '../../../@types/user';
import { Permisions } from '../../../@types/user';
import { FormProvider, RHFSelect, RHFSwitch, RHFTextField } from "../../../components/hook-form";
import { useEffect, useMemo, useState } from 'react';
import { useForm, Controller } 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';
import { Checkbox } from '@mui/material';
import Label from '@/components/Label';

type Props = {
  isEdit: boolean;
  currentUserRole?: Role;
  permissions?: Permisions;
};

export default function UserRoleForm({ isEdit, currentUserRole, permissions }: Props) {

  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate();
  const { corporate_id } = useParams();
  const [guardName, setGuardName] = useState(currentUserRole?.guard_name || '');
  const [filteredPermissions, setFilteredPermissions] = useState(permissions);

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

  const defaultValues = useMemo(
    () => ({
      name: currentUserRole?.name || '',
      guard_name: currentUserRole?.guard_name || '',
      permission_check: currentUserRole?.permissions?.map(permission => permission.id) || []

    }),
    [currentUserRole, permissions]
  );

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

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

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


  const onSubmit = async (data: any) => {
    console.log(data, 'test1')
    if (!isEdit) {
      await axios
      .post('/user/role', data)
      .then((res) => {
        enqueueSnackbar('User Role created successfully', { variant: 'success' });
      })
      .then((res) => {
        navigate('/user-role',  { 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/role/' + currentUserRole?.id, data)
        .then((res) => {
          enqueueSnackbar('User Role updated successfully', { variant: 'success' });
        })
        .then((res) => {
          navigate('/user-role' ,  { replace: true });
        })
        .catch(({ response }) => {
          enqueueSnackbar('Update Failed : '+ response.data.message, { variant: 'error' });
        });
    }
  };

  const guard_name_options = [
    { value: '', label: '' },
    { value: 'web', label: 'Primecenter' },
    { value: 'client-portal', label: 'Client Portal' },
    { value: 'hospital-portal', label: 'Hospital Portal' }
  ];

  // Buat fungsi handleCheckboxClick di luar komponen utama (UserRoleForm)
  const handleCheckboxClick = (permissionId, checked) => {
    const currentPermissions = getValues('permission_check') || [];
    if (checked) {
      setValue('permission_check', [...currentPermissions, permissionId]);
    } else {
      setValue('permission_check', currentPermissions.filter(id => id !== permissionId));
    }
  };

  useEffect(() => {
    // Fetch permissions based on guard_name
    if (guardName) {
      axios.get(`/permission_list?guard_name=${guardName}`)
        .then((res) => {
          setFilteredPermissions(res.data);
        })
        .catch((err) => {
          console.error('Error fetching permissions:', err);
        });
    } else {
      setFilteredPermissions(permissions);
    }
  }, [guardName,permissions]);

  const handleGuardNameChange = (event) => {
    console.log("ivan")
    setGuardName(event.target.value);
    setValue('guard_name', event.target.value);
  };

  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 Role</Typography>
                <RHFTextField name="name" label="Name" />
                <RHFSelect name="guard_name" label="Guard Name" onChange={handleGuardNameChange}>
                  {guard_name_options.map((option, index) => (
                    <option key={index} value={option.value}>
                      {option.label}
                    </option>
                  ))}
                </RHFSelect>
                <Typography variant="h6" color={palette.light.primary.main}>Permission</Typography>
                <Grid container spacing={2}>
                  {filteredPermissions?.map((permission, index) => (
                    <Grid item xs={4} key={permission.id}>
                      <FormControlLabel
                        control={
                          <Checkbox
                            name={`permission_check`}
                            value={permission.id}
                            checked={watch('permission_check')?.includes(permission.id) || false}
                            onChange={(e) => handleCheckboxClick(permission.id, e.target.checked)}
                          />
                        }
                        label={permission.name}
                      />
                    </Grid>
                  ))}
                </Grid>
                <LoadingButton type="submit" variant="contained" size="large" fullWidth={true} loading={isSubmitting}>
                  { isEdit? 'Update' : 'Create' }
                </LoadingButton>
              </Stack>
            </Card>
          </Grid>
        </Grid>
      </Box>
    </FormProvider>

  );
}
