import { useEffect, useReducer, useState } from "react";
import { GET_LOAN_DETAILS_REFAHI, SEND_LOAN_REQUEST_REFAHI } from "@/core/data/apiRoutes";
import { useRouter } from "next/router";
import { SvgLoading, useRequest, useUser } from "@witel/webapp-builder";
import { Stack, Typography } from "@mui/material";
import { useTranslations } from "next-intl";
import BuildFormController from "@/components/dashboard/refahi/add-request-loan/forms/BuildForm/BuildFormController";
import RestoreFormController
    from "@/components/dashboard/refahi/add-request-loan/forms/RestoreForm/RestoreFormController";


const reducer = (state, action) => {
    switch (action.type) {
        case "SET_PERSONAL_INFO":
            return { ...state, ...action.personalInfo };
        case "SET_PROJECT_INFO":
            return { ...state, ...action.projectInfo };
        case "SET_REQUEST_INFO":
            return { ...state, ...action.requestInfo };
        case "SET_PERSON_TYPE":
            return { ...state, person_type: action.person_type };
        default:
            return state;
    }
};


const ShowLoanForm = () => {
    const t = useTranslations();
    const { query } = useRouter();
    const [LoanDetails, setLoanDetails] = useState({});
    const [submitting, setSubmitting] = useState(false);
    const requestServer = useRequest();
    const { getUser, changeUser } = useUser();

    const isRefahi1 = LoanDetails.refahi_type === 1;
    const isRefahi2 = LoanDetails.refahi_type === 2;

    const _data = {
        person_type: LoanDetails.is_legal_person === 1 ? "legal" : "real",
        telephone_number: LoanDetails.telephone_number || "",
        activity_type_id: LoanDetails.activity_type_id || "",
        refahi_type: LoanDetails.refahi_type || 1,
        requested_facility_amount: LoanDetails.requested_facility_amount || "",
        person_share: LoanDetails.person_share || "",
        user_existing_employment: LoanDetails.user_existing_employment || "",
        user_committed_employment: LoanDetails.user_committed_employment || "",
        father_name: LoanDetails.father_name || "",
        gender: LoanDetails.gender || "",
        welfare_complex_degree: LoanDetails.welfare_complex_degree || "",
        first_name: LoanDetails.first_name || "",
        last_name: LoanDetails.last_name || "",
        city_id: LoanDetails.city_id || "",
        project_city_id: LoanDetails.project_city_id || "",
        province_id: LoanDetails.province_id || "",
        project_province_id: LoanDetails.project_province_id || "",
        education_id: LoanDetails.education_id || "",
        occupation_id: LoanDetails.occupation_id || "",
        national_id: LoanDetails.national_id || "",
        national_serial_number: LoanDetails.national_serial_number || "",
        national_card_tracking_code: LoanDetails?.national_card_tracking_code || "",
        national_serial_number_or_tracking_code:
            LoanDetails.national_serial_number ? "national_serial_number" : "national_card_tracking_code",
        postal_code: LoanDetails.postal_code || "",
        address: LoanDetails.address || "",
        birthday: LoanDetails.birthday || "",
        investment_amount: LoanDetails.investment_amount || "",
        checkedBox: false,
        facility_usage_history: LoanDetails.facility_usage_history || false,
        company_register_date: LoanDetails.company_register_date || "",
        shenase_meli: LoanDetails.shenase_meli || "",
        register_number: LoanDetails.register_number || "",
        company_name: LoanDetails.company_name || "",

        ...(isRefahi1 && {
            basic_approval_number: LoanDetails.basic_approval_number || "",
            basic_approval_renewal_date: LoanDetails.basic_approval_renewal_date || "",
            basic_approval_renewal_image: LoanDetails.basic_approval_renewal_image || null,
            basic_approval_image: LoanDetails.basic_approval_image || null,
            project_axis: LoanDetails.project_axis || "",
            project_physical_progress: LoanDetails.project_physical_progress || "",
            project_kilometer_marker: LoanDetails.project_kilometer_marker || "",
            project_direction: LoanDetails.project_direction || "",
            project_address: LoanDetails.project_address || "",
        }),

        ...(isRefahi2 && {
            exploitation_date: LoanDetails.exploitation_date || "",
            exploitation_license_renewal_date: LoanDetails.exploitation_license_renewal_date || "",
            exploitation_license_image: LoanDetails.exploitation_license_image || null,
            exploitation_license_renewal_image: LoanDetails.exploitation_license_renewal_image || null,
            project_axis: LoanDetails.project_axis || "",
            project_kilometer_marker: LoanDetails.project_kilometer_marker || "",
            project_direction: LoanDetails.project_direction || "",
            project_address: LoanDetails.project_address || "",
        }),
    };

    const [state, dispatch] = useReducer(reducer, _data);

    useEffect(() => {
        requestServer(GET_LOAN_DETAILS_REFAHI + query.id, "get", { auth: true, notification: false })
            .then(({ data }) => {
                setLoanDetails(data.data);
            })
            .catch(() => {});
    }, []);


    if (Object.keys(LoanDetails).length === 0) {
        return (
            <Stack sx={{ alignItems: "center", justifyContent: "center" }} spacing={3}>
                <SvgLoading height={150} width={150} />
                <Typography>{t("ShowLoan.loading_show_component")}</Typography>
            </Stack>
        );
    }

    const handleSubmit = async (values) => {
        console.log(values);
    };
    return (
        <>
            {LoanDetails.refahi_type === 1 ? (
                <BuildFormController submitting={submitting} state={state} dispatch={dispatch} handleSubmit={handleSubmit} />
            ) : (
                <RestoreFormController submitting={submitting} state={state} dispatch={dispatch} handleSubmit={handleSubmit} />
            )}
        </>
    );
};
export default ShowLoanForm;
