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 } from '~/Utils/fetch';
import Loading from '~/Components/UIControls/Loading';
import Form from '~/Components/Form';

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;
`;

export const PasswordChange = ({ loginData={}, loginResult={}, title="", message="", buttons=[] }) => {
    const [data, setData] = useState({ Password: '', PasswordConfirm:'' });
    const [loading, setLoading] = useState(false);
    const { showMessage } = useToast();

    const change = async (callback) => {
        console.log(data);

        if(!data.Password || !data.PasswordConfirm) {
            showMessage('변경할 비밀번호를 입력하십시오.');
            return;
        }

        if(data.Password != data.PasswordConfirm) {
            showMessage('비밀번호가 일치하지 않습니다.');
            return;
        }

        const validMessage = Util.validPassword(data.Password);
        if(!!validMessage) {
            showMessage(validMessage);
            return;
        }

        setLoading(true);
        try {
            const result = await fetchForm(`/api/Users/ChangePassword/${loginResult.SiteId}/${loginResult.UserId}`, {
                password: data.Password,
                auth: loginResult.AccessToken,
            });
            
        } catch(error) {
            showMessage(error.message);
        }

        try {
            if(callback && typeof callback === 'function') {
                await callback();
            }
        } catch(error) {
            showMessage(error.message);
        }
        setLoading(false);

    }

    return (
        <Fragment>
            <Background />
            <Container>
                <Header>
                    <Title>{title}</Title>
                </Header>
                <Body>
                    <Comment style={{marginBottom:10}}>
                        {message}
                    </Comment>

                    <Label>변경할 비밀번호</Label>
                    <Input placeholder="변경할 비밀번호" secureTextEntry={true} leftSvg="/login/password"
                        placeholderTextColor="#b9bac4" style={{borderWidth:1, borderColor:'#dedede', marginBottom:20}}
                        inputStyle={{textAlign:'center', color:'#707070'}}
                        onChangeText={text => {
                            setData({...data, Password:text});
                        }} />

                    <Label>비밀번호 확인</Label>
                    <Input placeholder="비밀번호 확인" secureTextEntry={true} leftSvg="/login/password"
                        placeholderTextColor="#b9bac4" style={{borderWidth:1, borderColor:'#dedede', marginBottom:20}}
                        inputStyle={{textAlign:'center', color:'#707070'}}
                        onChangeText={text => {
                            setData({...data, PasswordConfirm:text});
                        }} />

                    <Comment>
                        1. 비밀번호는 최소 10자리 이상
                    </Comment>
                    <Comment>
                        2. 대문자, 소문자, 숫자, 특수문자 중 2개 조합으로 작성
                    </Comment>

                    <ButtonGroup>
                        {buttons.map((button, index) => {
                            let Btn = () => { return <Fragment /> };
                            if(button.type == 'change') {
                                Btn = () => {
                                    return <Button 
                                            buttonStyle={{ width:100, height:40 }} 
                                            textStyle={{fontSize:17}} 
                                            iconFamily="AntDesign" 
                                            iconName="check" 
                                            onPress={() => { change(button.onPress); }}>변경</Button>
                                };
                            } else if(button.type == 'cancel') {
                                Btn = () => {
                                    return <Button 
                                            buttonStyle={{ width:100, height:40, borderWidth:1, borderColor:'#343a40' }} 
                                            textStyle={{fontSize:17, color:'#343a40'}} 
                                            iconFamily="AntDesign" 
                                            iconName="arrowleft" 
                                            iconColor="#343a40"
                                            color="white"
                                            onPress={() => { 
                                                if(button.onPress && typeof button.onPress === 'function') {
                                                    button.onPress(); 
                                                }
                                            }}>취소</Button>
                                };
                            } else {
                                Btn = () => {
                                    return <Button 
                                            buttonStyle={{ width:'auto', height:40, borderWidth:1, borderColor:'#343a40', paddingLeft:15, paddingRight:15 }} 
                                            textStyle={{fontSize:17, color:'#343a40'}} 
                                            color="white"
                                            onPress={() => { 
                                                if(button.onPress && typeof button.onPress === 'function') {
                                                    button.onPress(); 
                                                }
                                            }}>{button.text}</Button>
                                };
                            }

                            return (
                                <Btn key={`button-${index}`} />
                            );
                        })}
                    </ButtonGroup>
                </Body>
            </Container>
            {loading && <Form.Loading />}
        </Fragment>
    )
}