'use client';

import { Box, Button, Modal, Typography } from '@mui/material';
import React, { useState } from 'react';
import { IRegisterFirstStep } from '@/components/layout/landing-layout/header/components/IRegisterFirstStep';
import { IRegisterSecondStep } from '@/components/layout/landing-layout/header/components/IRegisterSecondStep';
import { IRegisterThirdStep } from '@/components/layout/landing-layout/header/components/IRegisterThirdStep';
import { usePathname, useRouter } from 'next/navigation';
import toast from 'react-hot-toast';
import axios from 'axios';
import { BASE_URL } from '@/helpers/constants';
import { toBase64 } from '@/helpers/toBase64';
import MCodeInput from '@/components/common/MComponents/MCodeInput';
import myAxios from '@/helpers/myAxios';
import authRequest from '@/helpers/authRequest';

// import { IRegisterFourthStep } from '@/components/layout/landing-layout/header/components/IRegisterFourthStep';

interface IProps {
    onClose: () => void;
    open: boolean;
    phoneNumber: string;
}

export interface IRegisterData {
    passport_serie: string;
    passport_pnfl: string;
    passport_front: File | null;
    passport_back: File | null;
    first_name: string;
    last_name: string;
    birth_date: string;
    address: string;
    filial: string;
    password: string;
    password_confirmation: string;
}

export interface IErrorsData {
    passport_serie: boolean;
    passport_pnfl: boolean;
    passport_front: boolean;
    passport_back: boolean;
    first_name: boolean;
    last_name: boolean;
    birth_date: boolean;
    address: boolean;
    filial: boolean;
    password: boolean;
    password_confirmation: boolean;
}

export interface IRegisterProps {
    formData: IRegisterData;
    formDataChanging: ({ key, value }: { key: string; value: string | number | File | null }) => void;
    dataErrors: IErrorsData;
}

const style = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    width: { xs: '90%', sm: 400 },
    bgcolor: 'background.paper',
    borderRadius: 2,
    boxShadow: 24,
    p: 4,
};

const initialValues: IRegisterData = {
    first_name: '',
    last_name: '',
    birth_date: '',
    passport_pnfl: '',
    passport_serie: '',
    passport_back: null,
    passport_front: null,
    address: '',
    filial: '',
    password: '',
    password_confirmation: '',
};

const initialErrorValues: IErrorsData = {
    first_name: false,
    last_name: false,
    birth_date: false,
    passport_pnfl: false,
    passport_serie: false,
    passport_back: false,
    passport_front: false,
    address: false,
    filial: false,
    password: false,
    password_confirmation: false,
};

export function IRegisterModal({ open, onClose, phoneNumber }: IProps) {
    const pathname = usePathname();
    const locale = pathname.split('/')[1] || 'uz';
    const router = useRouter();
    const [step, setStep] = useState<number>(1);
    const [formData, setFormData] = useState<IRegisterData>(initialValues);
    const [dataErrors, setDataErrors] = useState<IErrorsData>(initialErrorValues);
    const [verifyCode, setVerifyCode] = useState('');

    const formDataChanging = ({ key, value }: { key: string; value: string | number | File | null }): void => {
        setDataErrors(prev => ({ ...prev, [key]: false }));
        setFormData({ ...formData, [key]: value });
    };

    const nextStepHandler = async () => {
        if (step === 1) {
            if (!formData.first_name) setDataErrors(prev => ({ ...prev, first_name: true }));
            if (!formData.last_name) setDataErrors(prev => ({ ...prev, last_name: true }));
            if (!formData.birth_date) setDataErrors(prev => ({ ...prev, birth_date: true }));

            if (!formData.first_name || !formData.last_name || !formData.birth_date) return;
        } else if (step === 2) {
            if (!formData.passport_pnfl) setDataErrors(prev => ({ ...prev, passport_pnfl: true }));
            if (!formData.passport_serie) setDataErrors(prev => ({ ...prev, passport_serie: true }));
            if (!formData.passport_front) setDataErrors(prev => ({ ...prev, passport_front: true }));
            if (!formData.passport_back) setDataErrors(prev => ({ ...prev, passport_back: true }));

            if (!formData.passport_pnfl || !formData.passport_serie || !formData.passport_front || !formData.passport_back) return;
        } else if (step === 3) {
            if (!formData.address) setDataErrors(prev => ({ ...prev, address: true }));
            if (!formData.filial) setDataErrors(prev => ({ ...prev, filial: true }));

            if (!formData.address || !formData.filial) return;

            try {
                await authRequest.post('/profile/send-otp', { phone: phoneNumber });
                toast.success("Tasdiqlash ko'di yuborildi");
            } catch (error: any) {
                toast.error(error?.message || "Tasdiqlash ko'di yuborilmadi");
                return;
            }
        } else if (step === 4) {
            if (verifyCode.length !== 4) return;
        }

        if (step !== 4) return setStep(prev => prev + 1);

        const fData = {
            name: formData.first_name + ' ' + formData.last_name,
            phone: phoneNumber,
            passportSeries: formData.passport_serie,
            pinfl: formData.passport_pnfl,
            dateOfBirth: formData.birth_date,
            address: formData.address,
            region: formData.filial,
            passportFront: formData.passport_front ? await toBase64(formData.passport_front) : '',
            passportBack: formData.passport_back ? await toBase64(formData.passport_back) : '',
            code: verifyCode,
        };

        toast
            .promise(axios.post(BASE_URL + '/api/v1/profile/sign-up', fData), {
                loading: 'Loading...',
                success: 'Ma’lumotlaringiz ko‘rib chiqilmoqda. Iltimos, kuting.',
                error: 'Hatolik yuz berdi',
            })
            .then(() => {
                axios
                    .post(BASE_URL + '/api/v1/profile/sign-in', {
                        phone: phoneNumber,
                        code: '1234',
                    })
                    .then(response => {
                        // router.push(`/${locale}/profile`);
                        setStep(1);
                        setFormData(initialValues);
                        onClose();

                        // const data = response.data?.data;
                        // localStorage.setItem('token', data?.accessToken);
                        // localStorage.setItem('username', data?.username);
                        // localStorage.setItem('roles', data?.role?.[0]);
                    })
                    .catch((error: any) => {
                        if(axios.isAxiosError(error) && error.response?.status === 413) {
                            toast.error('Katta hajmdagi fayl yubordingiz. Iltimos, kichikroq hajmli fayl tanlang.');
                        }
                    })
            });
    };

    const decStepHandler = () => {
        if (step === 1) {
            onClose();
        } else {
            setStep(prev => {
                if (prev > 1) return prev - 1;
                return prev;
            });
        }
    };

    const handleVerifyCode = () => {};

    return (
        <Modal open={open} onClose={onClose}>
            <Box sx={style}>
                <Typography variant='h6' align={'center'} fontSize={'1.5rem'} fontWeight={'bolder'} component='h2' mb={2}>
                    {`Ro'yxatdan o'tish`}
                </Typography>

                {step === 1 && <IRegisterFirstStep formDataChanging={formDataChanging} formData={formData} dataErrors={dataErrors} />}
                {step === 2 && <IRegisterSecondStep formDataChanging={formDataChanging} formData={formData} dataErrors={dataErrors} />}
                {step === 3 && <IRegisterThirdStep formDataChanging={formDataChanging} formData={formData} dataErrors={dataErrors} />}

                {/*{step === 4 && <IRegisterFourthStep formDataChanging={formDataChanging} formData={formData} dataErrors={dataErrors} />}*/}

                {step === 4 && (
                    <Box display={'flex'} flexDirection={'column'} gap={3}>
                        <Typography variant='body1' mb={2}>
                            Iltimos, SMS orqali yuborilgan 4 xonali kodni kiriting:
                        </Typography>

                        {/*<MCodeInput clearError={clearCodesError} isError={inputErrors.code} onCodeChange={value => setVerifyCode(value)} />*/}
                        <MCodeInput isError={false} onCodeChange={value => setVerifyCode(value)} />

                        {/*<Box sx={{ mt: 3 }} display='flex' justifyContent={'end'} gap={2}>*/}
                        {/*    <Button variant='outlined' onClick={() => setStep(3)}>*/}
                        {/*        Orqaga*/}
                        {/*    </Button>*/}

                        {/*    <Button variant='contained' color='primary' onClick={handleVerifyCode}>*/}
                        {/*        Tasdiqlash*/}
                        {/*    </Button>*/}
                        {/*</Box>*/}
                    </Box>
                )}

                <Box sx={{ marginTop: 2, display: 'flex', justifyContent: 'end', gap: 2 }}>
                    <Button variant='outlined' onClick={decStepHandler}>
                        {step === 1 ? 'Bekor qilish' : 'Qaytish'}
                    </Button>
                    <Button variant='contained' onClick={nextStepHandler}>
                        {step === 4 ? 'Yuborish' : 'Keyingi'}
                    </Button>
                </Box>
            </Box>
        </Modal>
    );
}
