import React, { useContext, useState } from 'react';
import useSWR from 'swr';
import { Link } from 'react-router-dom';
import toast, { Toaster } from 'react-hot-toast';
import { ResponseT} from '../context/UserContext';
import {getProfilData} from '../services/PhpApi';
import CreateQr from '../services/CreateQr';
import Img from './Img';
import './Profil.css';

function Profil() 
{
    const [formData, setFormData] = useState({
        email:'',
        name:'',
        phone:'',
        qr_code: null
    });

    const fetcher = () => 
    {

    }

//    const { data, error, isLoading } = useSWR( user?.qr_id, getDog);
    const { data, error, isLoading } = useSWR( "profilData", getProfilData);
// data ist dogdata und logindata
    if (error) return (<div>failed to load</div>);
    if (isLoading) return (<div>loading...</div>);

    console.log(data);
    console.log(user);

            // setDog(data);
            // setFormData(
            //     { 
            //         email: data.data.email, 
            //         name: data.data.name,
            //         phone: data.data.phone,
            //         qr_code: data.data.qr_code
            //     });


            if(data.data.qr_code === null && document.getElementById("canvas") != null)
            {
                // qrcode generieren und in der Datenbank speichern
                CreateQr({qr_id: user?.qr_id});
            }              
                 

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

    function showData(data: any/*, e: React.FormEvent<HTMLFormElement> | React.MouseEvent<HTMLButtonElement>*/)
    {
        if(data.success)
        {
            toast.success('Daten geändert!');

            // setSuccessMsg and setErrMsg force rendering
            // if(e as React.FormEvent<HTMLFormElement> !== null)
            //     (e as React.FormEvent<HTMLFormElement>).currentTarget.reset();
            // if(e as React.MouseEvent<HTMLButtonElement> !== null)
            //     (e as React.MouseEvent<HTMLButtonElement>).currentTarget.onre();
        }
        else if(!data.success && data.message)
        {
            toast.error(data.message);
        }
    }

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

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

    const qr_refresh = (e: React.MouseEvent<HTMLButtonElement>) => 
    {
        e.preventDefault();
        formData.qr_code = null;
        setFormData(formData);
        showData(data/*, e*/);
    }
    formData.email = data.data.email;
    formData.name = data.data.name;
    formData.phone = data.data.phone;
console.log(formData);
    return (
        <div className='Profil'>
            <Toaster toastOptions={{ position: "top-center" }} />
            <h2>Profil</h2>
            <div className='neben'>
                <div className='margin'>
                    {data.data && <Img pth={data.data.picture} className=''/>}
                    <Link to={'/upload'}>Bild ändern</Link>
                </div>
                <div className='margin'>
                    {data.data && <Img pth={data.data.qr_code} className=''/>}
                    <button onClick={qr_refresh}>QR aktualisieren</button>
                </div>
                <div id="canvas"></div>
            </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>
                <button type="submit">Update</button>
            </form>
        <Link to={"/qr"}>QR-Code drucken</Link>
        </div>
  )
}

export default Profil