import React, { useState } from 'react';
import { Link, useParams } from 'react-router-dom';
import { passwordReset, getPwToken } from '../services/PhpApi';
import useSWR from 'swr';
import './InputForm.css';
import { notificationError, notificationSuccess } from '../services/Notifications';
import { PasswordInput } from '@mantine/core';

export default function PasswordReset()
{
    const params = useParams();
    const passwordToken = Object.values(params)[0];

    const [formData, setFormData] = useState({
        password1:'',
        password2:''
    });

    const { data, error, isLoading } = useSWR({'pwtoken': passwordToken}, getPwToken);
    // data ist dogdata, logindata holt sich getProfilData.php aus $_SESSION
        if (error) return (<div>failed to load</div>);
        if (isLoading) return (<div>loading...</div>);
    
    const onChangeInput = (e: React.FormEvent<HTMLInputElement> ) => {
        setFormData({
            ...formData,
            [e.currentTarget.name]:e.currentTarget.value
        })

        //console.log(e.currentTarget.value);
    }

    if(!data.success)
    {
        return(
        <div >
            <h2>Link nicht mehr gültig!</h2>
        </div>
        )
    }

    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => 
    {
        e.preventDefault();

        if(!Object.values(formData).every(val => val.trim() !== ''))
        {
            notificationError('Bitte alle Felder ausfüllen!');
            return;
        }

        if(formData.password1 !== formData.password2)
        {
            notificationError('Bitte 2mal das gleiche Passwort eingeben!');
            return;
        }

        const sendData = new FormData();
        const values = Object.values(formData);
        const keys = Object.keys(formData);

        for (const key of keys) 
        {
            const index = keys.indexOf(key);
            sendData.append(key, values[index]);
        }

        sendData.append('id', data.data.id);
 
        const dataRes = await passwordReset(sendData);
        if(dataRes.success)
        {
            notificationSuccess('Erfolgreich Passwort geändert!');
            e.currentTarget?.reset();
        }
        else if(!dataRes.success && dataRes.message)
        {
            notificationError(dataRes.message);
        }
    }

    return ( 
        <div className='InputForm'>
            <h2>Passwort zurücksetzten!</h2>
            <div className='frameCenter'>
            <div className='frame'>
            <form onSubmit={submitForm}>
            <PasswordInput className='IF_pw'
                    sx = {{  maxWidth: '80vw', minWidth: '30vw', width: '300px' }}
                    label = 'Passwort:'
                    name="password1" 
                    onChange={onChangeInput} 
                    placeholder="Passwort" 
                    id="password1" 
                    value={formData.password1} 
                    required/>
            <PasswordInput className='IF_pw'
                    sx = {{  maxWidth: '80vw', minWidth: '30vw', width: '300px' }}
                    label = 'Passwort wiederholen:'
                    name="password2" 
                    onChange={onChangeInput} 
                    placeholder="Passwort bestätigen" 
                    id="password2" 
                    value={formData.password2} 
                    required/>
                <button type="submit" >Passwort setzen!</button>
                <div className="bottom-link"><Link to="/login">Login</Link></div>
            </form>
            </div>
            </div>
        </div>
    )
} 
