import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Button, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import { startPasswordSetting } from "api/auth";
import RequireChip from "components/chip/RequireChip";
import { FormProvider, RHFTextField } from "components/hook-form";
import StackRow from "components/stack/StackRow";
import useAPICall from "hooks/useAPICall";
import useNavigateCustom from "hooks/useNavigateCustom";
import { PageID } from "pages";
import { useState } from "react";
import { useForm } from "react-hook-form";
import { getPath } from "routes/path";
import { object as YupObject, string as YupString } from "yup";

type AreaBoxProps = {
  label: string;
  require?: boolean;
} & HasChildren;
function AreaBox({ label, children, require }: AreaBoxProps) {
  return (
    <Box>
      <StackRow>
        <Typography variant="subtitle1">〇{label}</Typography>
        <RequireChip require={require ?? false} />
      </StackRow>
      {children}
    </Box>
  );
}

type FormProps = {
  email: string;
  retype_email: string;
};

export default function PasswordSettingStart() {
  const { navigateWhenChanged } = useNavigateCustom();

  const [done, setDone] = useState<boolean | null>(null);

  const form = useForm<FormProps>({
    defaultValues: {
      email: "",
      retype_email: "",
    },
    resolver: yupResolver(
      YupObject().shape({
        email: YupString().required("必須項目です"),
        retype_email: YupString()
          .required("必須項目です")
          .test("retype", "一致しません", function (value) {
            return value === this.parent.email;
          }),
      })
    ),
  });

  const { callAPI: callStartPasswordSetting } = useAPICall({
    apiMethod: startPasswordSetting,
    backDrop: true,
    form,
    onSuccess: () => {
      setDone(true);
    },
    onFailed: () => {},
  });

  const handleSubmit = (data: FormProps) => {
    callStartPasswordSetting({ ...data });
  };

  const toLogin = () => {
    navigateWhenChanged(getPath(PageID.LOGIN));
  };

  if (done === true) {
    return (
      <Box sx={{ p: 3, pt: 5, mx: "auto", maxWidth: 500 }} textAlign="center">
        <Stack spacing={2}>
          <Box>
            <Typography>
              メールアドレスに設定手続きのご案内を送信しました。
            </Typography>
            <Typography>ご確認ください。</Typography>
          </Box>
          <Box>
            <Button onClick={toLogin}>ログインへ</Button>
          </Box>
        </Stack>
      </Box>
    );
  }

  return (
    <Box sx={{ p: 3, pt: 5, mx: "auto", maxWidth: 500 }} textAlign="center">
      <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmit)}>
        <Stack spacing={2}>
          <Box>
            <Button onClick={toLogin}>戻る</Button>
          </Box>
          <Box>
            <Typography>
              登録済みのメールアドレスへ変更用のURLを送信します。
            </Typography>
          </Box>
          <AreaBox label="Email" require={true}>
            <Box textAlign="left">
              <Typography variant="body2">8-20文字で設定可能です。</Typography>
              <Typography variant="body2">
                半角英数字と記号(@.-)が使えます。
              </Typography>
            </Box>
            <RHFTextField name="email" />
          </AreaBox>
          <AreaBox label="Email (確認用)" require={true}>
            <Box textAlign="left">
              <Typography variant="body2">
                確認のため再度同じパスワードを入力してください。
              </Typography>
            </Box>
            <RHFTextField name="retype_email" />
          </AreaBox>
          <Box>
            <Button type="submit">送信</Button>
          </Box>
        </Stack>
      </FormProvider>
    </Box>
  );
}
