import { useCallback } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
// @mui
import LoadingButton from '@mui/lab/LoadingButton';
import Card from '@mui/material/Card';
import Stack from '@mui/material/Stack';
import Grid from '@mui/material/Unstable_Grid2';
// routes
import { paths } from 'src/routes/paths';
import { useRouter } from 'src/routes/hooks';
// types
import { NewEmployee, newEmployeeSchema } from 'src/schemas';
// components
import { useSnackbar } from 'src/components/snackbar';
import FormProvider, { RHFTextField, RHFUploadAvatar } from 'src/components/hook-form';
import { createEmployee } from 'src/api/employee';

export default function EmployeeNewEditForm() {
  const router = useRouter();
  const { enqueueSnackbar } = useSnackbar();

  const methods = useForm<NewEmployee>({
    resolver: zodResolver(newEmployeeSchema),
    defaultValues: {
      name: '',
      email: '',
      status: 'active' as const,
      project: '',
      iban: '',
      photo: '',
      cv: '',
    },
  });

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

  const onSubmit = handleSubmit(async (data) => {
    try {
      await createEmployee(data);
      enqueueSnackbar('Create success!');
      router.push(paths.dashboard.employee.list);
    } catch (error) {
      console.error(error);
    }
  });

  return (
    <FormProvider methods={methods} onSubmit={onSubmit}>
      <Grid container spacing={3}>
        <Grid xs={12} md={8}>
          <Card sx={{ p: 3 }}>
            <Stack spacing={3}>
              <RHFTextField name="name" label="Full Name" />
              <RHFTextField name="email" label="Email Address" />
              <RHFTextField name="project" label="Project" />
              <RHFTextField name="iban" label="IBAN" />
              <RHFTextField name="cv" label="CV Link" />
            </Stack>

            <Stack alignItems="flex-end" sx={{ mt: 3 }}>
              <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
                Create Employee
              </LoadingButton>
            </Stack>
          </Card>
        </Grid>
      </Grid>
    </FormProvider>
  );
}
