import { yupResolver } from "@hookform/resolvers/yup";
import { Box, Button, Stack, Typography } from "@mui/material";
import { HasChildren } from "@types";
import { changeLoginPassword, getLoginUsers } from "api/login-user";
import { PageID, TabID } from "codes/page";
import { UserRole } from "codes/user";
import { FormProvider, RHFTextField } from "components/hook-form";
import useAPICall from "hooks/useAPICall";
import useAuth from "hooks/useAuth";
import useDashboard from "hooks/useDashBoard";
import useSnackbarCustom from "hooks/useSnackbarCustom";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import { useParams } from "react-router-dom";
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 = {
  password: string;
  password_retype: string;
};

export default function ChangePassword() {
  const { setHeaderTitle, setTabs } = useDashboard(
    PageID.DASHBOARD_LOGIN_USER_CHANGE_PASSWORD,
    TabID.NONE
  );

  const { initialized, userId, role } = useAuth();

  const { success, error } = useSnackbarCustom();

  const { id: paramUserId } = useParams();

  const [timestamp, setTimestamp] = useState("");

  const [mode, setMode] = useState<"input" | "done">("input");

  const form = useForm<FormProps>({
    defaultValues: {
      password: "",
      password_retype: "",
    },
    resolver: yupResolver(
      Yup.object().shape({
        password: Yup.string().required("必須項目です"),
        password_retype: Yup.string()
          .required("必須項目です")
          .test("retype", "入力が一致しません", function (value) {
            return this.parent.password === value;
          }),
      })
    ),
  });

  const { callAPI: callGetLoginUsers } = useAPICall({
    apiMethod: getLoginUsers,
    onSuccess: ({ data: { records } }) => {
      if (records.length === 1) {
        setTimestamp(records[0].updated_at);
      }
    },
  });

  const { callAPI: callChangeLoginPassword, makeSendData } = useAPICall({
    apiMethod: changeLoginPassword,
    backDrop: true,
    form,
    onSuccess: () => {
      success("登録しました");
      setMode("done");
    },
    onFailed: () => {
      error("失敗しました");
    },
  });

  const fetch = () => {
    callGetLoginUsers({
      id: paramUserId,
    });
  };

  const handleSubmt = (data: FormProps) => {
    const sendData = makeSendData({ ...data, timestamp });

    if (userId === paramUserId) {
      // 自身の場合はパラメータなしで送信する
    } else {
      sendData.id = paramUserId ?? "";
    }

    callChangeLoginPassword(sendData);
  };
  useEffect(() => {
    if (initialized) {
      fetch();
    }
  }, [initialized]);

  useEffect(() => {
    setHeaderTitle("パスワード変更");
    setTabs(null);
  }, []);

  return (
    <>
      {mode === "input" && (
        <FormProvider methods={form} onSubmit={form.handleSubmit(handleSubmt)}>
          <Box>
            <Stack spacing={2}>
              <AreaBox title="ログインパスワード">
                <RHFTextField name="password" type="password" />
              </AreaBox>
              <AreaBox title="ログインパスワード（再入力）">
                <RHFTextField name="password_retype" type="password" />
              </AreaBox>
              <Stack direction="row">
                <Button variant="contained" type="submit">
                  登録
                </Button>
              </Stack>
            </Stack>
          </Box>
        </FormProvider>
      )}
      {mode === "done" && <Box>変更完了しました</Box>}
    </>
  );
}
