import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Button, Divider, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import { FormProvider, RHFTextField } from "components/hook-form";
import { useForm } from "react-hook-form";
import * as Yup from "yup";

type AreaBoxProps = {
  title: string;
} & HasChildren;
function AreaBox({ title, children }: AreaBoxProps) {
  return (
    <Box sx={{ maxWidth: 500 }}>
      <Typography variant="subtitle1">{title}</Typography>
      {children}
    </Box>
  );
}

type FormProps = {
  email: string;
};

type Props = {
  onNext?: VoidFunction;
  onPrev?: VoidFunction;
};
export default function useInputEmailStep({ onNext, onPrev }: Props) {
  const form = useForm<FormProps>({
    defaultValues: {
      email: "",
    },
    resolver: yupResolver(
      Yup.object().shape({
        email: Yup.string().required("必須項目です"),
      })
    ),
  });

  const handleSubmit = () => {
    if (onNext) {
      onNext();
    }
  };

  const handlePrev = () => {
    if (onPrev) {
      onPrev();
    }
  };

  const element = (
    <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
      <Stack spacing={2} sx={{ p: 1, m: 1 }} textAlign="left">
        <AreaBox title="Email">
          <RHFTextField name="email" />
        </AreaBox>
        <Divider />
        <Stack direction="row" spacing={2}>
          <Button variant="text" onClick={handlePrev}>
            戻る
          </Button>
          <Button variant="contained" type="submit">
            次へ
          </Button>
        </Stack>
      </Stack>
    </FormProvider>
  );

  return { element, values: form.getValues, setValue: form.setValue };
}
