import StyledForm from "@/core/components/StyledForm";
import {Box, Button, Chip, Divider, Stack, TextField} from "@mui/material";
import {Field, Formik} from "formik";
import {useTranslations} from "next-intl";
import EditIcon from '@mui/icons-material/Edit';
import * as Yup from "yup";
import SelectBox from "@/core/components/SelectBox";
import PlateNumber from "@/core/components/PlateNumber";
import MuiDatePicker from "@/core/components/MuiDatePicker";
import moment from "jalali-moment";
import useProvince from "@/lib/app/hooks/useProvince";
import useCities from "@/lib/app/hooks/useCities";
import UseEducations from "@/lib/app/hooks/useEducations";
import useOccupations from "@/lib/app/hooks/useOccupations";
import {UPDATE_LOAN} from "@/core/data/apiRoutes";
import {useRequest} from "@witel/webapp-builder";
import {useRouter} from "next/router";
import {useEffect} from "react";

const UpdateForm = ({LoanDetails, LoanId}) => {
    const t = useTranslations();
    const provinceStates = useProvince();
    const router = useRouter()
    const citiesStates = useCities();
    const educationStates = UseEducations();
    const occupationStates = useOccupations();
    const requestServer = useRequest();

    // initial values
    const initialValues = {
        national_id: LoanDetails.national_id,
        postal_code: LoanDetails.postal_code,
        national_serial_number: LoanDetails.national_serial_number,
        address: LoanDetails.address,
        birthday: moment(LoanDetails.birthday),
        navgan_id: LoanDetails.navgan_id,
        province_id: LoanDetails.province_id,
        city_id: LoanDetails.city_id,
        name: LoanDetails.name,
        navgan_type: LoanDetails.navgan_type,
        vehicle_type: LoanDetails.vehicle_type,
        telephone_number: LoanDetails.telephone_number,
        plate_part1: LoanDetails.plate_number.split("-")[0],
        plate_part2: LoanDetails.plate_number.split("-")[1],
        plate_part3: LoanDetails.plate_number.split("-")[2],
        plate_part4: LoanDetails.plate_number.split("-")[3],
        education_id: LoanDetails.education_id,
        occupation_id: LoanDetails.occupation_id,
    };
    // end initial values

    useEffect(() => {
        citiesStates.setProvinceID(LoanDetails.province_id)
    }, [LoanDetails.province_id]);

    // validation
    const validationSchema = Yup.object().shape({
        postal_code: Yup.mixed()
            .test("max", `${t("ShowLoan.postal_code_max")}`, (value) => value.toString().length === 10)
            .required(
                t("ShowLoan.error_message_postal_code")
            ),
        address: Yup.string().required(t("ShowLoan.error_message_address")),
        province_id: Yup.string().required(t("ShowLoan.error_message_province_id")),
        city_id: Yup.string().required(t("ShowLoan.error_message_city_id")),
        telephone_number: Yup.mixed()
            .test("max", `${t("ShowLoan.tel_number_max")}`, (value) => {
                const stringValue = String(value);
                return stringValue.length === 11
            })
            .required(t("ShowLoan.error_message_tel_number")),
        occupation_id: Yup.string().required(t("ShowLoan.error_message_occupation_id")),
        education_id: Yup.string().required(t("ShowLoan.error_message_education_id")),
        birthday: Yup.string().required(t("ShowLoan.error_message_date_of_birth")),
        national_serial_number: Yup.string().required(t("ShowLoan.error_message_national_serial_number")),

    });
    // end validation

    // submit
    const handleSubmit = async (values, props) => {
        props.setSubmitting(true)
        const formData = new FormData();
        formData.append("postal_code", values.postal_code);
        formData.append("address", values.address);
        formData.append("province_id", values.province_id);
        formData.append("city_id", values.city_id);
        formData.append("telephone_number", values.telephone_number);
        formData.append("occupation_id", values.occupation_id);
        formData.append("education_id", values.education_id);
        formData.append("national_serial_number", values.national_serial_number);
        formData.append("birthday", values.birthday.locale('en').format("YYYY-MM-DD"));
        await requestServer(UPDATE_LOAN + LoanId, "post", {
            auth: true, notification: true, data: formData
        }).then(() => {
            router.push("/dashboard/navgan/followUp-loan")
        }).catch(() => {
        }).finally(() => {
            props.setSubmitting(false)
        })

    };
    // end submit

    return (
        <>
            <Box sx={{width: "80%", my: 2}}>
                <Divider>
                    <Chip
                        label={t("ShowLoan.show_loan_page")}
                    />
                </Divider>
            </Box>
            <Formik
                initialValues={initialValues}
                onSubmit={handleSubmit}
                validationSchema={validationSchema}
            >
                {(props) => (
                    <Stack
                        spacing={2}
                        sx={{
                            p: 1,
                            width: "100%",
                        }}
                    >
                        <StyledForm sx={{width: "100%"}}>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >

                                    <Field
                                        as={TextField}
                                        sx={{width: "100%"}}
                                        name="national_id"
                                        disabled
                                        variant="standard"
                                        size="small"
                                        label={t("ShowLoan.text_field_national_id")}
                                        placeholder={t("ShowLoan.text_field_enter_your_national_id")}
                                        type={'tel'}
                                        error={!!(props.touched.national_id && props.errors.national_id)}
                                        fullWidth
                                        helperText={props.touched.national_id ? props.errors.national_id : null}
                                    />
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <Field
                                        as={TextField}
                                        sx={{width: "100%"}}
                                        name="name"
                                        disabled
                                        variant="standard"
                                        size="small"
                                        label={t("ShowLoan.text_field_name")}
                                        placeholder={t(
                                            "ShowLoan.text_field_enter_your_name"
                                        )}
                                        type={"text"}
                                        error={!!(props.touched.name && props.errors.name)}
                                        fullWidth
                                        helperText={
                                            props.touched.name
                                                ? props.errors.name
                                                : null
                                        }
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <Field
                                        as={TextField}
                                        sx={{width: "100%"}}
                                        name="navgan_id"
                                        disabled
                                        variant="standard"
                                        size="small"
                                        label={t("ShowLoan.text_field_navgan_id")}
                                        placeholder={t(
                                            "ShowLoan.text_field_enter_your_navgan_id"
                                        )}
                                        type={'tel'}
                                        error={!!(props.touched.navgan_id && props.errors.navgan_id)}
                                        fullWidth
                                        helperText={
                                            props.touched.navgan_id
                                                ? props.errors.navgan_id
                                                : null
                                        }
                                    />
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <SelectBox
                                        name="navgan_type"
                                        label={t("ShowLoan.text_field_navgan_type")}
                                        size="small"
                                        disabled
                                        variant="standard"
                                        selectType="navgan_type"
                                        schema={{value: "value", name: "name"}}
                                        selectors={[
                                            {
                                                id: 1,
                                                value: "روستایی",
                                                name: "روستایی"
                                            },
                                            {
                                                id: 2,
                                                value: "عمومی",
                                                name: "عمومی"
                                            },
                                            {
                                                id: 3,
                                                value: "منطقه آزاد",
                                                name: "منطقه آزاد"
                                            }
                                        ]}

                                        select={props.values.navgan_type}
                                        handleChange={(event) => {
                                            props.setFieldValue('navgan_type', event.target.value)
                                        }}
                                        setFieldTouched={props.setFieldTouched}
                                        error={props.touched.navgan_type && Boolean(props.errors.navgan_type)}
                                        helperText={props.touched.navgan_type && props.errors.navgan_type}
                                        onBlur={props.handleBlur("navgan_type")}
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <PlateNumber formik={props} disabled={true}/>
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <SelectBox
                                        name="vehicle_type"
                                        label={t("ShowLoan.text_field_vehicle_type")}
                                        size="small"
                                        disabled
                                        variant="standard"
                                        selectType="vehicle_type"
                                        schema={{value: "value", name: "name"}}
                                        selectors={[
                                            {
                                                id: 0,
                                                value: "اتوبوس",
                                                name: "اتوبوس"
                                            },
                                            {
                                                id: 1,
                                                value: "مینی بوس",
                                                name: "مینی بوس"
                                            },
                                            {
                                                id: 2,
                                                value: "سواری",
                                                name: "سواری"
                                            }
                                        ]}

                                        select={props.values.vehicle_type}
                                        handleChange={(event) => props.setFieldValue('vehicle_type', event.target.value)}
                                        error={props.touched.vehicle_type && Boolean(props.errors.vehicle_type)}
                                        helperText={props.touched.vehicle_type && props.errors.vehicle_type}
                                        onBlur={props.handleBlur("vehicle_type")}
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <Field
                                        as={TextField}
                                        sx={{width: "100%"}}
                                        name="national_serial_number"
                                        size="small"
                                        label={t("ShowLoan.text_field_national_serial_number")}
                                        placeholder={t(
                                            "ShowLoan.text_field_enter_your_national_serial_number"
                                        )}
                                        type={"text"}
                                        error={!!(props.touched.national_serial_number && props.errors.national_serial_number)}
                                        fullWidth
                                        helperText={
                                            props.touched.national_serial_number
                                                ? props.errors.national_serial_number
                                                : null
                                        }
                                    />
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <MuiDatePicker
                                        formik={props}
                                        disableFuture={true}
                                        error={props.touched.birthday && Boolean(props.errors.birthday)}
                                        helperText={props.touched.birthday && props.errors.birthday}
                                        onBlur={props.handleBlur("birthday")}
                                    />
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <Field
                                        as={TextField}
                                        sx={{width: "100%"}}
                                        name="postal_code"
                                        variant="outlined"
                                        size="small"
                                        label={t("ShowLoan.text_field_postal_code")}
                                        placeholder={t(
                                            "ShowLoan.text_field_enter_your_postal_code"
                                        )}
                                        value={props.values.postal_code}
                                        type={'tel'}
                                        onChange={(event) => {
                                            const inputValue = event.target.value;
                                            if (isNaN(Number(inputValue))) {
                                                return;
                                            }
                                            props.handleChange({
                                                target: {
                                                    name: "postal_code",
                                                    value: inputValue,
                                                },
                                            });
                                        }}
                                        error={!!(props.touched.postal_code && props.errors.postal_code)}
                                        fullWidth
                                        helperText={
                                            props.touched.postal_code
                                                ? props.errors.postal_code
                                                : null
                                        }
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    {provinceStates.provinceList.length !== 0 ?
                                        <SelectBox
                                            name="province_id"
                                            label={t("ShowLoan.text_field_province_id")}
                                            size="small"
                                            selectType="province_id"
                                            schema={{value: "value", name: "name"}}
                                            isLoading={provinceStates.isLoadingProvinceList}
                                            errorEcured={provinceStates.errorProvinceList}
                                            selectors={provinceStates.provinceList}
                                            select={props.values.province_id}
                                            handleChange={(event) => {
                                                props.setFieldValue('province_id', event.target.value);
                                                citiesStates.setProvinceID(event.target.value)
                                                props.setFieldTouched("city_id", false, false);
                                                props.setFieldValue("city_id", "")
                                            }}
                                            setFieldTouched={props.setFieldTouched}
                                            error={props.touched.province_id && Boolean(props.errors.province_id)}
                                            helperText={props.touched.province_id && props.errors.province_id}
                                            onBlur={props.handleBlur("province_id")}
                                        /> : <Field
                                            as={TextField}
                                            sx={{width: "100%"}}
                                            variant="outlined"
                                            disabled
                                            size="small"
                                            label={t("ShowLoan.text_field_province_id")}
                                            value={t("text_field_loading")}
                                            type={"text"}
                                        />}

                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    {citiesStates.cityList.length !== 0 ?
                                        <SelectBox
                                            name="city_id"
                                            label={citiesStates.cityList.length === 0 ? `${t("ShowLoan.cityList_empty")}` : citiesStates.cityTextField}
                                            size="small"
                                            selectType="city_id"
                                            disabled={citiesStates.cityList.length === 0}
                                            selectors={citiesStates.cityList}
                                            select={props.values.city_id}
                                            schema={{value: "value", name: "name"}}
                                            handleChange={(event) => props.setFieldValue('city_id', event.target.value)}
                                            setFieldTouched={props.setFieldTouched}
                                            error={props.touched.city_id && Boolean(props.errors.city_id)}
                                            helperText={props.touched.city_id && props.errors.city_id}
                                            onBlur={props.handleBlur("city_id")}
                                        /> : <Field
                                            as={TextField}
                                            sx={{width: "100%"}}
                                            variant="outlined"
                                            disabled
                                            size="small"
                                            label={t("ShowLoan.cityList_empty")}
                                            value={t("text_field_loading")}
                                            type={"text"}
                                        />}
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <TextField
                                        sx={{width: "100%"}}
                                        name="telephone_number"
                                        variant="outlined"
                                        size="small"
                                        type={'tel'}
                                        value={props.values.telephone_number}
                                        onChange={(event) => {
                                            const inputValue = event.target.value;
                                            if (isNaN(Number(inputValue))) {
                                                return;
                                            }
                                            props.handleChange({
                                                target: {
                                                    name: "telephone_number",
                                                    value: inputValue,
                                                },
                                            });
                                        }}
                                        label={t("ShowLoan.text_field_tel_number")}
                                        placeholder={t(
                                            "ShowLoan.text_field_enter_your_tel_number"
                                        )}
                                        fullWidth
                                        onBlur={props.handleBlur("telephone_number")}
                                        error={props.touched.telephone_number && Boolean(props.errors.telephone_number)}
                                        helperText={props.touched.telephone_number && props.errors.telephone_number}
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    {educationStates.educationsList.length !== 0 ?
                                        <SelectBox
                                            name="education_id"
                                            label={t("ShowLoan.text_field_education_id")}
                                            size="small"
                                            isLoading={educationStates.isLoadingEducationsList}
                                            errorEcured={educationStates.errorEducationsList}
                                            selectType="education_id"
                                            selectors={educationStates.educationsList}
                                            select={props.values.education_id}
                                            schema={{value: "id", name: "title"}}
                                            handleChange={(event) => {
                                                props.setFieldValue('education_id', event.target.value)
                                            }}
                                            setFieldTouched={props.setFieldTouched}
                                            error={props.touched.education_id && Boolean(props.errors.education_id)}
                                            helperText={props.touched.education_id && props.errors.education_id}
                                            onBlur={props.handleBlur("education_id")}
                                        /> : <Field
                                            as={TextField}
                                            sx={{width: "100%"}}
                                            variant="outlined"
                                            disabled
                                            size="small"
                                            label={t("ShowLoan.text_field_education_id")}
                                            value={t("text_field_loading")}
                                            type={"text"}
                                        />}
                                </Box>
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    {occupationStates.occupationsList.length !== 0 ?
                                        <SelectBox
                                            name="occupation_id"
                                            label={t("ShowLoan.text_field_occupation_id")}
                                            size="small"
                                            isLoading={occupationStates.isLoadingOccupationsList}
                                            errorEcured={occupationStates.errorOccupationsList}
                                            selectType="occupation_id"
                                            selectors={occupationStates.occupationsList}
                                            select={props.values.occupation_id}
                                            schema={{value: "id", name: "title"}}
                                            handleChange={(event) => {
                                                props.setFieldValue('occupation_id', event.target.value)
                                            }}
                                            setFieldTouched={props.setFieldTouched}
                                            error={props.touched.occupation_id && Boolean(props.errors.occupation_id)}
                                            helperText={props.touched.occupation_id && props.errors.occupation_id}
                                            onBlur={props.handleBlur("occupation_id")}
                                        /> : <Field
                                            as={TextField}
                                            sx={{width: "100%"}}
                                            variant="outlined"
                                            disabled
                                            size="small"
                                            label={t("ShowLoan.text_field_occupation_id")}
                                            value={t("text_field_loading")}
                                            type={"text"}
                                        />}
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "start",
                                    justifyContent: "center",
                                    width: "100%",
                                }}
                            >
                                <Box
                                    sx={{
                                        mx: {xs: 0, sm: 2},
                                        my: 2,
                                        width: "100%",
                                    }}
                                >
                                    <Field
                                        as={TextField}
                                        multiline
                                        rows={4}
                                        sx={{width: "100%"}}
                                        name="address"
                                        variant="outlined"
                                        size="small"
                                        label={t("ShowLoan.text_field_address")}
                                        placeholder={t("ShowLoan.text_field_enter_your_address")}
                                        type={"text"}
                                        error={!!(props.touched.address && props.errors.address)}
                                        fullWidth
                                        helperText={props.touched.address ? props.errors.address : null}
                                    />
                                </Box>
                            </Box>
                            <Box
                                sx={{
                                    display: "flex",
                                    flexDirection: {xs: "column", sm: "row"},
                                    alignItems: "center",
                                    mx: "auto",
                                    width: {xs: "100%", sm: "30%", md: "25%"},
                                }}
                            >
                                <Button
                                    fullWidth
                                    type="submit"
                                    variant="contained"
                                    size="large"
                                    sx={{mt: 2}}
                                    endIcon={<EditIcon/>}
                                    disabled={props.isSubmitting || !props.dirty || !props.isValid}
                                >
                                    {t("ShowLoan.button_submit")}
                                </Button>
                            </Box>
                        </StyledForm>
                    </Stack>
                )}
            </Formik>
        </>
    );
};

export default UpdateForm;
