import React, { useRef, useState } from 'react';
import useSWR from 'swr';
import { Link } from 'react-router-dom';
import {TUser} from '../context/UserContext';
import {getProfilData, updateDog} from '../services/PhpApi';
import CreateQr from '../services/CreateQr';
import Img from './Img';
import './InputForm.css';
import { TextInput } from '@mantine/core';
import { notificationError, notificationSuccess } from '../services/Notifications';

type TFormData =
{
    email: string,
    name: string,
    phone: string,
    qr_code: string
};

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

//    const { data, error, isLoading } = useSWR( user?.qr_id, getDog);
    const { data, error, isLoading, mutate } = useSWR( "profilData", getProfilData);

    const edit = useRef(false);
    const formDataSave = useRef(formData); // just to fill it
// data ist dogdata, logindata holt sich getProfilData.php aus $_SESSION

    const WWW_ROOT: string = process.env.REACT_APP_WWW_ROOT!;


    if (error) return (<div>failed to load</div>);
    if (isLoading) return (<div>loading...</div>);

    const user: TUser =  
    { 
        id: data.data.id,
        qr_id: data.data.qr_id,
        email: data.data.email,
        name: data.data.name
    };
    console.log('Profil data');    
    console.log(data);
    console.log('Profil user');    
    console.log(user);

    if(data.data.qr_code === null && document.getElementById("canvas") != null)
    {
        // qrcode generieren und in der Datenbank speichern
        CreateQr({qr_id: user?.qr_id})
        .catch(err => 
        {
            console.log('Profil CreateQr Error');
            console.error(err);
        });
    }              

    let formData_loc: TFormData = 
    {
        email: '',
        name: '',
        phone: '',
        qr_code: ''
    };

    if (edit.current)
    {
        formData_loc = {...formDataSave.current}; // copy constructor
    }
    else
    {
        formData_loc =
        {
            email: data.data.email as string,
            name: data.data.name as string,
            phone: data.data.phone as string,
            qr_code: data.data.qr_code as string
        };
    }

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

        setFormData(formData_loc);   
        edit.current = true; 
        formDataSave.current = {...formData_loc};
    }

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

    async function submitData(fd: TFormData)
    {
        if(!Object.values(fd).every(val => val?.trim() !== ''))
        {
            notificationError('Bitte alle Felder ausfüllen!');
            return;
        }
        setFormData(fd);

        const data = await updateDog(fd);
        mutate();
        showData(data);

    }

    const submitForm = async (e: React.FormEvent<HTMLFormElement>) => 
    {
        e.preventDefault();
        console.log(formData);
        console.log(formData_loc);
        console.log(formDataSave.current);

        if( formData.email || formData.name || formData.name || formData.name )
        {
            submitData(formData);
        }
        else
        {
            submitData(formData_loc);
        }
    }

    const qr_refresh = (e: React.MouseEvent<HTMLButtonElement>) => 
    {
        e.preventDefault();
        formData.qr_code = '';
        setFormData(formData);
        showData(data/*, e*/);

        if(document.getElementById("canvas") != null)
        {
            // qrcode generieren und in der Datenbank speichern
            CreateQr({qr_id: user?.qr_id})
            .catch(err => 
                {
                    console.log('qr_refresh CreateQr Error');
                    console.error(err);
                });
        
        }              
        // update data with phpapi
        mutate();
    }

    console.log('Profil formData');
    console.log(formData);
    console.log('Profil formData_loc');
    console.log(formData_loc);

    return (
        <div className='InputForm'>
            <h2>Profil</h2>
            <div className='frameCenter'>
            <div className='frame'>
            <div className='neben'>
                <div className='m-2'>
                    {data.data && <Img pth={data.data.picture} className=''/>}
                    <Link to={'/upload'}>Bild ändern</Link>
                </div>
                <div className='m-2'>
                    <Link to={'/' + data.data.qr_id}>{WWW_ROOT + data.data.qr_id}</Link>
                    {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}>
            <TextInput
                label = 'Email:'
                type="email" 
                name="email" 
                onChange={onChangeInput} 
                placeholder="Deine Email" 
                id="email" 
                value={formData_loc.email} 
                required />
            <TextInput
                label = 'Name:'
                type="text" 
                name="name" 
                onChange={onChangeInput} 
                placeholder="Name des Tieres" 
                id="name" 
                value={formData_loc.name} 
                required />
            <TextInput
                label = 'Telefon:'
                type="text" 
                name="phone" 
                onChange={onChangeInput} 
                id="phone" 
                value={formData_loc.phone} 
                required />
                <button type="submit">Update</button>
            </form>
            </div>
            </div>
        <Link to={"/qr"}>QR-Code drucken</Link>
        </div>
  )
}

export default Profil