'use client';

import React, { useState } from 'react';
import { Button, Box, Modal, Typography } from '@mui/material';
import MCodeInput from '@/components/common/MComponents/MCodeInput';
import PhoneInput from '@/components/common/MComponents/MPhoneInput';
import axios from 'axios';
import { BASE_URL } from '@/helpers/constants';
import { useMyNavigation } from '@/hooks/useMyNavigation';
import toast from 'react-hot-toast';
import authRequest from '@/helpers/authRequest';

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

interface IData {
    message: string;
    data: null | {
        username: string;
        accessToken: string;
        roles: string[];
    };
}

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,
};

export const VerifyPhoneModal = ({ onClose, open, openRegister, changePhone, phoneNumber }: IProps) => {
    const navigate = useMyNavigation();
    const [phoneValue, setPhoneValue] = useState('');
    const [step, setStep] = useState<1 | 2>(1);
    const [verificationCode, setVerificationCode] = useState('');
    const [inputErrors, setInputErrors] = useState({ phone: false, code: false });
    const [isExist, setIsExist] = useState<boolean>(false);
    const [tryNumber, setTryNumber] = useState(0);

    const clearCodesError = () => {
        setInputErrors(prev => ({ ...prev, code: false }));
    };

    const handleClose = () => {
        setStep(1);
        setVerificationCode('');
        onClose();
    };

    const changePhoneValue = (phone_value: string) => {
        changePhone('+998' + phone_value?.replaceAll(' ', ''));
        setPhoneValue(phone_value);
        setInputErrors(prev => ({ ...prev, phone: false }));
    };

    const handleSendCode = () => {
        const phone_value = phoneValue.replaceAll(' ', '');
        if (phone_value.length !== 9) {
            setInputErrors(prev => ({ ...prev, phone: true }));
            return;
        }
        toast
            .promise(axios.get(BASE_URL + '/api/v1/profile/check-phone?phone=%2B998' + phone_value), {
                loading: 'Nomer tekshirilmoqda',
                success: 'Tekshirildi',
                error: 'Xatolik yuz berdi',
            })
            .then(async (res: any) => {
                const is_exist: boolean = res?.data.data?.exists;
                setIsExist(is_exist);
                if (is_exist) {
                    setStep(2);
                    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 {
                    openRegister();
                }
            });
    };

    const handleBack = () => {
        setStep(1);
        setVerificationCode('');
    };

    const handleVerifyCode = () => {
        if (verificationCode?.length !== 4) {
            setInputErrors(prev => ({ ...prev, code: true }));
        } else {
            if (isExist) {
                axios
                    .post(BASE_URL + '/api/v1/profile/sign-in', {
                        phone: '+998' + phoneValue.replaceAll(' ', ''),
                        code: verificationCode,
                    })
                    .then(res => {
                        const resData: IData = res.data;
                        const data = resData.data;
                        if (data) {
                            localStorage.setItem('token', data.accessToken);
                            localStorage.setItem('username', data.username);
                            localStorage.setItem('roles', data.roles?.[0]);
                            navigate.push('/profile');
                            onClose();
                            setVerificationCode('');
                            setStep(1);
                        } else {
                            toast.error("Tasdiqlash ko'di xato");

                            if (tryNumber > 3) {
                                onClose();
                                setVerificationCode('');
                                setPhoneValue('');
                                setStep(1);
                            }
                            setTryNumber(prev => prev + 1);
                        }
                    });
            } else {
                openRegister();
            }
        }
    };

    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 / Kirish`}
                </Typography>

                {step === 1 && (
                    <>
                        <Typography variant='body1' mb={2}>
                            {`Tasdiqlash kodi jo'natishimiz uchun telefon raqamingizni kiriting`}
                        </Typography>

                        <PhoneInput isError={inputErrors.phone} value={phoneValue} setValue={changePhoneValue} />

                        <Box sx={{ mt: 3 }} display='flex' justifyContent='flex-end'>
                            <Button variant='outlined' onClick={handleClose} sx={{ mr: 2 }}>
                                Bekor qilish
                            </Button>

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

                {step === 2 && (
                    <>
                        <Typography variant='body1' mb={2}>
                            Iltimos, SMS orqali yuborilgan 4 xonali kodni kiriting:
                        </Typography>

                        <MCodeInput clearError={clearCodesError} isError={inputErrors.code} onCodeChange={setVerificationCode} />

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

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