import React, { useContext, useState } from 'react'
import { Link } from 'react-router-dom';
import { Axios, ResponseT, UserCtx, UserCtxT } from '../context/UserContext';
import Img from './Img';
import './Profil.css';

function Profil() 
{
    const { user, updateDog, wait } = useContext<UserCtxT | null>(UserCtx) as UserCtxT;
    const [dog, setDog] = useState<ResponseT | any>({}); // local dog not the dog in UserContext
    const [errMsg, setErrMsg] = useState("false");
    const [successMsg, setSuccessMsg] = useState("false");
    const [formData, setFormData] = useState({
        email:'',
        name:'',
        phone:''
    });

    if(user && (dog === undefined || dog.success === undefined))
    {
        Axios.post<ResponseT>('getDog.php', 
        {
            qr_id: user.qr_id
        })
        .then((resDog) =>
        {
            setDog(resDog.data);
            setFormData(
                { 
                    email: resDog.data.data.email, 
                    name: resDog.data.data.name,
                    phone: resDog.data.data.phone
                });   
        })
        .catch((err) => console.error(err));
    }

    const onChangeInput = (e: React.FormEvent<HTMLInputElement> ) => {
        setFormData({
            ...formData,
            [e.currentTarget.name]:e.currentTarget.value
        })
    }

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

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


        const data = await updateDog(formData);
        if(data.success)
        {
            setSuccessMsg('Daten geändert!');
            setErrMsg("false");
            e.currentTarget?.reset();
        }
        else if(!data.success && data.message)
        {
            setSuccessMsg("false");
            setErrMsg(data.message);
        }
    }

    return (
        <div className='Profil'>
            <h2>Profil</h2>
            <div>
                {dog.data && <Img pth={dog.data.picture}/>}
                <Link to={'/upload'}>Bild ändern</Link>
            </div>
            <form onSubmit={submitForm}>
                <div className='neben'>
                    <label htmlFor="email">Email: </label>                    
                    <input type="email" name="email" onChange={onChangeInput} placeholder="Deine email" id="email" value={formData.email} required />
                </div>
                <div className='neben'>
                    <label htmlFor="name">Name: </label>
                    <input type="text" name="name" onChange={onChangeInput} id="name" value={formData.name} required />
                </div> 
                <div className='neben'>
                    <label htmlFor="phone">Telefon: </label>
                    <input type="text" name="phone" onChange={onChangeInput} id="phone" value={formData.phone} required />
                </div>
                {successMsg !== "false" && <div className="success-msg">{successMsg}</div>}
                {errMsg !== "false" && <div className="err-msg">{errMsg}</div>}
                <button type="submit" disabled={wait}>Update</button>
            </form>
        <Link to={"/qr"}>QR-Code drucken</Link>
        </div>
  )
}

export default Profil