import React, { ChangeEvent, MouseEvent } from "react";
import { Card, Button, TextField } from "@mui/material";
import "@scss/reset.scss";
import { useNavigate } from "react-router-dom";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useForm } from "react-hook-form";
import Typography from "@theme/modules/components/Typography";

type Inputs = {
    password: string;
    confirm_password: string;
};

const schema = yup
    .object()
    .shape({
        password: yup.string().required("No password was provided"),
        confirm_password: yup
            .string()
            .oneOf([yup.ref("password"), null], "Passwords must match"),
    })
    .required();

export default function Reset() {
    const navigate = useNavigate();

    const {
        register,
        formState: { errors },
        handleSubmit,
    } = useForm<Inputs>({
        resolver: yupResolver(schema),
    });

    function hash(s: string) {
        return `hash of '${s}' to be definied`;
    }

    const { ref: passRef, ...passRegisterProps } = register("password");

    const passProps = {
        ...passRegisterProps,
        inputRef: passRef,
        className: "textField",
        name: "password",
        type: "password",
        id: "password",
        label: "Password",
        error: !!errors.password,
        helperText: errors?.password?.message,
    };

    const { ref: confirmPassRef, ...confirmPassRegisterProps } =
        register("confirm_password");

    const confirmPassProps = {
        ...confirmPassRegisterProps,
        inputRef: confirmPassRef,
        className: "textField",
        name: "confirm_password",
        id: "confirm_password",
        type: "password",
        label: "Confirm Password",
        error: !!errors.confirm_password,
        helperText: errors?.confirm_password?.message,
    };

    function onSubmit(data: Inputs) {
        console.warn("There will be an API call now with the following data");
        data = {
            password: hash(data.password),
            confirm_password: hash(data.confirm_password),
        };
        console.table(data);
    }

    return (
        <main className="cardContainer">
            <form onSubmit={handleSubmit(onSubmit)}>
                <Card className="card">
                    <Typography className="title" variant="h5">Reset Password</Typography>
                    <TextField {...passProps} />
                    <TextField {...confirmPassProps} />
                    <Button type="submit" id="submit" variant="contained">
                        Reset Password
                    </Button>
                </Card>
            </form>
        </main>
    );
}
