import StyledForm from "@/core/components/StyledForm";
import {SEND_OTP_TOKEN} from "@/core/data/apiRoutes";
import FingerprintIcon from "@mui/icons-material/Fingerprint";
import {Button, Container, Grid, Paper, Stack, TextField, Typography,} from "@mui/material";
import {Field, Formik} from "formik";
import {useTranslations} from "next-intl";
import {useSearchParams} from "next/navigation";
import * as Yup from "yup";
import SvgLogin from "@/core/components/svgs/SvgLogin";
import {CenterLayout, FullPageLayout, LinkRouting, useRequest} from "@witel/webapp-builder";


const SendUserDataComponent = ({
                                   setOtpToken,
                                   setPhoneNumber,
                                   PhoneNumber,
                                   setTimer,
                                   initialTimerValue,
                               }) => {
    const t = useTranslations();
    const requestServer = useRequest();

    const searchParams = useSearchParams();
    const backUrlDecodedPath = searchParams.get("back_url");

    const initialValues = {
        phone_number: PhoneNumber,
    };
    const validationSchema = Yup.object().shape({
        phone_number: Yup.mixed()
            .test("max", `${t("LoginPage.phone_number_max")}`, (value) => {
                const stringValue = String(value);
                return stringValue.length === 11
            })
            .required(t("LoginPage.error_message_phone_number")),
    });

    const handleSubmit = (values, props) => {
        requestServer(SEND_OTP_TOKEN, "post", {
            auth: false, data: {
                phone_number: values.phone_number,
            }
        })
            .then(function (response) {
                setPhoneNumber(values.phone_number);
                setOtpToken(true);
                setTimer(initialTimerValue);
            }).catch(function (error) {
            props.setSubmitting(false);
        });
    };

    return (
        <FullPageLayout sx={{p: 1}}>
            <CenterLayout>
                <Container maxWidth="sm">
                    <Paper elevation={0}>
                        <Formik
                            initialValues={initialValues}
                            onSubmit={handleSubmit}
                            validationSchema={validationSchema}
                        >
                            {(props) => (
                                <Stack spacing={2} sx={{p: 2}}>
                                    <Stack
                                        sx={{width: "100%"}}
                                        alignItems='center'
                                    >
                                        <SvgLogin width={300} height={200}/>
                                    </Stack>
                                    <Typography margin={2} variant="h4" textAlign="center">
                                        {t("Titles.title_login_page")}
                                    </Typography>
                                    <StyledForm sx={{width: "100%"}}>
                                        <Stack spacing={3} sx={{p: 2}}>
                                            <Field
                                                as={TextField}
                                                name="phone_number"
                                                variant="outlined"
                                                label={t("LoginPage.text_field_phone_number")}
                                                placeholder={t(
                                                    "LoginPage.text_field_enter_your_phone_number"
                                                )}
                                                value={props.values.phone_number}
                                                type={"tel"}
                                                onChange={(event) => {
                                                    const inputValue = event.target.value;
                                                    if (isNaN(Number(inputValue))) {
                                                        return;
                                                    }
                                                    props.handleChange({
                                                        target: {
                                                            name: "phone_number",
                                                            value: inputValue,
                                                        },
                                                    });
                                                }}
                                                error={
                                                    !!(props.touched.phone_number && props.errors.phone_number)
                                                }
                                                fullWidth
                                                helperText={
                                                    props.touched.phone_number
                                                        ? props.errors.phone_number
                                                        : null
                                                }
                                            />
                                            <Grid
                                                container
                                                rowSpacing={{xs: 1, sm: 0}}
                                                sx={{
                                                    flexDirection: {xs: "column-reverse", sm: "row"},
                                                }}
                                            >
                                                <Button
                                                    fullWidth
                                                    type="submit"
                                                    variant="contained"
                                                    size="large"
                                                    endIcon={<FingerprintIcon/>}
                                                    disabled={props.isSubmitting}
                                                >
                                                    {t("LoginPage.button_request_verification")}
                                                </Button>
                                            </Grid>
                                        </Stack>
                                    </StyledForm>
                                </Stack>
                            )}
                        </Formik>
                    </Paper>
                </Container>
            </CenterLayout>
            <Stack direction="row" alignItems="center" justifyContent="center">
                <LinkRouting
                    sx={{margin: 2}}
                    href={
                        backUrlDecodedPath ? decodeURIComponent(backUrlDecodedPath) : "/"
                    }
                >
                    {t("LoginPage.link_routing_back_to")}{" "}
                    {backUrlDecodedPath
                        ? t("LoginPage.link_routing_previuos_page")
                        : t("LoginPage.link_routing_main_page")}
                </LinkRouting>
            </Stack>
        </FullPageLayout>
    );
};

export default SendUserDataComponent;
