import React, { Fragment, useState } from 'react';
import Styled from 'styled-components/native';
import Theme from '~/Themes';
import Button from '~/Components/UIControls/Button';
import { useToast } from '~/Components/UIControls/Message';
import { Util } from '~/Utils/utils';
import { fetchForm, fetchPost } from '~/Utils/fetch';
import Loading from '~/Components/UIControls/Loading';
import Form from '~/Components/Form';
import Input from '~/Components/UIControls/Input';

const Background = Styled.View`
    position: absolute;
    width: 100%;
    height: 100%;
    background-color:black;
    opacity:0.4;
`;

const Container = Styled.View`
    position: absolute;
    left: 10%;
    right: 10%;
    top:20%;
    padding-bottom:20px;
    align-items:center;
    justify-content:space-between;
    border-radius:4;
    background-color:white;
    overflow: hidden;
`;

const Header = Styled.View`
    flex-direction:row;
    width:100%;
    height:50px;
    background-color:#343a40;
    align-items:center;
    justify-content:space-between;
    padding-left:20;
    padding-right:20;
`;
const Title = Styled.Text`
    font-family:${Theme.Fonts.Regular};
    font-size:20;
    line-height:28;
    letter-spacing:-1.2;
    color:white;
`;

const Body = Styled.View`
    flex:1;
    background-color:white;
    padding:10px;
    padding-top:20px;
`;

const Label = Styled.Text`
    font-family:${Theme.Fonts.Medium};
    font-size:15;
    line-height:30;
    letter-spacing:-1.0;
    color:#343a40;
    padding-left:10;
`;
const Comment = Styled.Text`
    font-family:${Theme.Fonts.Regular};
    font-size:15;
    line-height:25;
    letter-spacing:-1.0;
    color:#343a40;
    padding-left:10;
`;

const ButtonGroup = Styled.View`
    flex-direction: row;
    align-items: center;
    justify-content: center;
    margin-top:20;
`;

const FindPassword = ({ completeHandler, closeHandler }) => {
    const [email, setEmail] = useState();
    const [loading, setLoading] = useState(false);
    const { showMessage } = useToast();
    const [reqid] = useState(('' + Math.random()).split('.')[1]);
    const [code, setCode] = useState();
    const [authCode, setAuthCode] = useState();

    const sendMail = async () => {
        if (!email) {
            showMessage('이메일을 입력해주세요');
            return;
        }

        if (!/\S+@\S+\.\S+/.test(email)) {
            showMessage('올바른 이메일 형식이 아닙니다.');
            return;
        }

        setLoading(true);
        try {
            console.log({
                email: email,
                reqid: reqid,
            });
            const data = await fetchPost(`/api/Users/SendEmailAuthCode/${reqid}/${email}`);
            console.log('result',data);
            setCode(data);
        } catch (error) {
            showMessage(error.message);
        }
        setLoading(false);
    };

    const validCode = async () => {
        if (!authCode) {
            showMessage('인증번호를 입력해주세요');
            return;
        }

        setLoading(true);
        try {
            const data = await fetchPost(`/api/Users/ValidAuthCode/${authCode}/${code}/${email}`);
            completeHandler(data);
        } catch (error) {
            showMessage(error.message);
        }
        setLoading(false);
    };

    return (
        <Fragment>
            <Background />
            <Container>
                <Header>
                    <Title>ID/PW 찾기</Title>
                </Header>
                <Body>
                    <Comment>찾으려는 계정의 이메일 주소를 입력해주세요</Comment>
                    <Label>이메일</Label>
                    <Input
                        placeholder="이메일"
                        leftSvg="/login/mail"
                        placeholderTextColor="#b9bac4"
                        editable={!code}
                        defaultValue={email}
                        value={email}
                        style={{ borderWidth: 1, borderColor: '#dedede', marginBottom: 20 }}
                        onChangeText={(text) => {
                            setEmail(text);
                        }}
                    />
                    {code ? (
                        <>
                            <Comment>인증번호를 입력하신 이메일 주소로 발송하였습니다</Comment>
                            <Label>인증번호를 입력해주세요</Label>
                            <Input
                                placeholder="인증번호"
                                leftSvg="/login/mail"
                                placeholderTextColor="#b9bac4"
                                style={{ borderWidth: 1, borderColor: '#dedede', marginBottom: 20 }}
                                onChangeText={(text) => {
                                    setAuthCode(text);
                                }}
                            />
                        </>
                    ) : (
                        <Comment>입력하신 이메일 주소로 인증문자를 보냅니다</Comment>
                    )}

                    <ButtonGroup>
                        {code ? (
                            <Button
                                buttonStyle={{ width: 100, height: 40 }}
                                textStyle={{ fontSize: 17 }}
                                iconFamily="AntDesign"
                                iconName="check"
                                onPress={() => {
                                    validCode();
                                }}
                            >
                                확인
                            </Button>
                        ) : (
                            <Button
                                buttonStyle={{ width: 100, height: 40 }}
                                textStyle={{ fontSize: 17 }}
                                iconFamily="AntDesign"
                                iconName="mail"
                                onPress={() => {
                                    sendMail();
                                }}
                            >
                                발송
                            </Button>
                        )}
                        <Button
                            buttonStyle={{ width: 100, height: 40, borderWidth: 1, borderColor: '#343a40' }}
                            textStyle={{ fontSize: 17, color: '#343a40' }}
                            iconFamily="AntDesign"
                            iconName="arrowleft"
                            iconColor="#343a40"
                            color="white"
                            onPress={() => {
                                closeHandler();
                            }}
                        >
                            닫기
                        </Button>
                    </ButtonGroup>
                </Body>
            </Container>
            {loading && <Form.Loading />}
        </Fragment>
    );
};

export default FindPassword;
