import React, { ChangeEvent, MouseEventHandler, useState } from 'react'
import { Link } from 'react-router-dom';
import { DogT } from '../context/UserContext';
import {getDog, updateQR} from '../services/PhpApi';
import toast, { Toaster } from 'react-hot-toast';
import Checkbox from './Checkbox';
import Img from './Img';
import './Qr.css';
import useSWR from 'swr';

type ListItemT = 
{
    id: string;
    name: string;
    ordernum: number;
}

export default function Qr() 
{
    const { data, error, isLoading, mutate } = useSWR( ['Qr', 'SESS'], getDog);
    // data ist dogdata, logindata holt sich getDog.php aus $_SESSION
    
    const [dogRender, setDogRender] = useState<DogT>(
        {
            id: 0,
            qr_id: '',
            email: '',
            name: '',
            phone: '',
            qr_width_cm: 0,
            qr_height_cm: 0,
            qr_fontsize: 0,
            qr_visible_items: 0,
            qr_item_sequence: 0,
            qr_code: '',
            picture: ''
        }); 
    //save reference for dragItem and dragOverItem
    const dragItem = React.useRef<any>(null);
    const dragOverItem = React.useRef<any>(null);
    const itemListInit: ListItemT[] = 
    [
        {id: '0', name:'Name', ordernum: 1},
        {id: '1', name:'Telefon', ordernum: 2},
        {id: '2', name:'Email', ordernum: 3}
    ]; 

    const itemList = React.useRef<ListItemT[]>(itemListInit); 
 
    if (error) return (<div>failed to load</div>);
    if (isLoading) return (<div>loading...</div>);
                                                                                      
    // local dog
    let dog: DogT =
    {
        id: 0,
        qr_id: '',
        email: '',
        name: '',
        phone: '',
        qr_width_cm: 0,
        qr_height_cm: 0,
        qr_fontsize: 0,
        qr_visible_items: 0,
        qr_item_sequence: 0,
        qr_code: '',
        picture: ''
    };

    function setBitField(val: number, checked: boolean, bit: number) : number
    {
        if(checked)
        {
            val |= bit;
        }
        else
        {
            val ^= bit;
        }
        return val;
    }

    function checkBoxChange(id: string, checked: boolean) : void
    {
        let value = dog.qr_visible_items;
        console.log(value);
        if(id==="name")
        {
            value = setBitField(value, checked, 0b100);
        }
        if(id==="phone")
        {
            value = setBitField(value, checked, 0b010);
        }
        if(id==="email")
        {
            value = setBitField(value, checked, 0b001);
        }
        console.log(value);
        dog.qr_visible_items = value;
        setDogRender(dog);
    }

    function getItemOrderNumber(digit: number)
    {
        let ordernum = dog.qr_item_sequence; // 123
        ordernum = ordernum % (digit*10); // 123
        ordernum = Math.trunc(ordernum / digit);

        return ordernum;
    }

	//const handle drag sorting
	function handleSort()
    {
		//duplicate items
		let _itemList = [...itemList.current];

		//remove and save the dragged item content
		const draggedItemContent = _itemList.splice(dragItem.current, 1)[0];

		//switch the position
		_itemList.splice(dragOverItem.current, 0, draggedItemContent);

		//reset the position ref
		dragItem.current = null;
		dragOverItem.current = null;

		//update the actual array
		itemList.current = _itemList;

        // set new itemorder
        let newItemOrder = 0;
        let digit = 100;

// name         1
// telefon      2
// email        3 

// email  
// name   
// telefon

// email is first  1 -> 3
// name  is second 2 -> 1
// telefon third   3 -> 2

// name telefon email
// 2    3       1       ordernum

        _itemList.map((item, index) => 
        {
            digit = 10**(3-item.ordernum);
            newItemOrder += (index+1) * digit;
        });

        dog.qr_item_sequence = newItemOrder;
        setDogRender(dog);
	}
    
    function oneQrBlock()
    {
        return(
    <div className='qrCodeBackFront'>
        <div className='qrCode frame' style={{height : dog.qr_height_cm + 'cm', width : dog.qr_width_cm + 'cm'}}>
            <div className='qrCode__'>SCAN ME</div>
            <Img pth={dog.qr_code} className='qrCodeImg'/>
        </div>
        <div className='qrCode vert frame' style={{ height : dog.qr_height_cm + 'cm', width : dog.qr_width_cm + 'cm', fontSize: dog.qr_fontsize + '%' }}>
            {((dog.qr_visible_items & 0b100) > 0) && <div className={`vertFont order${getItemOrderNumber(100)}`}>{dog.name}</div>}
            {((dog.qr_visible_items & 0b010) > 0) && <div className={`vertFont order${getItemOrderNumber(10)}`}>{dog.phone}</div>}
            {((dog.qr_visible_items & 0b001) > 0) && <div className={`vertFont order${getItemOrderNumber(1)}`}>{dog.email}</div>}
        </div>
    </div>);
    }

    const saveHandler = (event: React.MouseEvent<HTMLButtonElement>): MouseEventHandler<HTMLButtonElement> | undefined => 
    {
        event.preventDefault();
        console.log("saveHandler \n");
        console.log(event);
        updateQR(
            { 
                qr_width_cm: dog.qr_width_cm, 
                qr_height_cm: dog.qr_height_cm, 
                qr_fontsize: dog.qr_fontsize, 
                qr_visible_items: dog.qr_visible_items, 
                qr_item_sequence: dog.qr_item_sequence
            }
        ).then((resQR) =>
        {
            if(resQR.success)
            {
                toast.success('Daten gesichert!');
                mutate();
            }
            else if(!resQR.success && resQR.message)
            {
                toast.error(resQR.message);
            }
        })
        .catch((err) => console.error(err));
        return;
    }

    const printHandler = (event: React.MouseEvent<HTMLButtonElement>): MouseEventHandler<HTMLButtonElement> | undefined => 
    {
        event.preventDefault();
        console.log("printHandler \n");
        console.log(event);
        window.print();
        return;
    }

    function getItemOrderNumber_(order: number, digit: number)
    {
        let ordernum = order; // 123
        ordernum = ordernum % (digit*10); // 123
        ordernum = Math.trunc(ordernum / digit);

        return ordernum;
    }

    /**
     * order the list from order
     * 
     * @param order 
     * normal order is 123 mean   name phone email
     *   231  mean   name get ordernumber 2
     *               phone get ordernumber 3
     *               email get ordernumber 1
     *   new order is email name phone
     * 
     *   
     * 
     */
    function OrderItemList(order: number)
    { 
		let _itemList: ListItemT[] = [];
        let oNum = getItemOrderNumber_(order, 100);
        _itemList[oNum-1] = itemListInit[0];
        oNum = getItemOrderNumber_(order, 10);
        _itemList[oNum-1] = itemListInit[1];
        oNum = getItemOrderNumber_(order, 1);
        _itemList[oNum-1] = itemListInit[2];

        itemList.current = _itemList;
    }

    const onChangeWidth = (e: ChangeEvent<HTMLInputElement> ) => 
    {
        dog.qr_width_cm = parseInt(e.target.value)/10 ? parseInt(e.target.value)/10 : 0;
        setDogRender(dog);
    }

    const onChangeHeight = (e: ChangeEvent<HTMLInputElement> ) => 
    {
        dog.qr_height_cm = parseInt(e.target.value)/10 ? parseInt(e.target.value)/10 : 0;
        setDogRender(dog);
    }

    const onChangeFontSize = (e: ChangeEvent<HTMLInputElement> ) => 
    {
        dog.qr_fontsize = parseInt(e.target.value) ? parseInt(e.target.value) : 0;
        setDogRender(dog);
    }

    console.log('dogRender');
    console.log(dogRender);

    console.log('data');
    console.log(data);

    if (dogRender.email)
    {
        Object.assign(dog, dogRender);
    }
    else
    {
        Object.assign(dog, data.data);
    }
    OrderItemList(dog.qr_item_sequence);

    console.log(dog);

    return (
        <div>
            <Toaster toastOptions={{ position: "top-center" }} />
            <h1>Qr-Code Druck</h1>
            <Link to={"/profil"}>Zurück zum Profil</Link>
            <div className='qrSettings____'>
                <div className='qrSettings'>
                    <div>
                        <div>Anhänger</div>
                        <label htmlFor='width'>Breite [mm] </label>
                        <input className='qr-input' type='number' id='width' name='width' 
                        min="1" max="100"
                        onChange={onChangeWidth} value={dog.qr_width_cm*10}/>
                        <label htmlFor='height'>Höhe [mm] </label>
                        <input className='qr-input' type='number' id='height' name='height' 
                        min="1" max="100"
                        onChange={onChangeHeight} value={dog.qr_height_cm*10}/>
                    </div>
                    <div>
                        <label htmlFor='fontSize'>Schriftgröße </label>
                        <input className='qr-input' type='number' id='fontSize' name='fontSize' 
                        min="1" max="200"
                        onChange={onChangeFontSize} value={dog.qr_fontsize} />
                    </div>
                    <div>
                        <div>Sichtbare Elemente</div>
                        <Checkbox 
                            id='name' 
                            label={'Name'} 
                            checked={(dog.qr_visible_items & 0b100) > 0} 
                            changeEvent={checkBoxChange}
                            />
                        <Checkbox 
                            id='phone' 
                            label={'Telefon'} 
                            checked={(dog.qr_visible_items & 0b010) > 0} 
                            changeEvent={checkBoxChange}
                            />
                        <Checkbox 
                            id='email' 
                            label={'Email'} 
                            checked={(dog.qr_visible_items & 0b001) > 0} 
                            changeEvent={checkBoxChange}
                            />
                    </div>
                    <div>
                        <div>Reihenfolge</div>
                        <div className='beschreibung'>Ändern durch Drag'n Drop</div>
                        <div className="list-container">
                        {itemList.current.map((item, index) => (
                            <div
                                key={index}
                                className="list-item"
                                draggable
                                onDragStart={(e) => {dragItem.current = index; }}
                                onDragEnter={(e) => {dragOverItem.current = index; }}
                                onDragEnd={handleSort}
                                onDragOver={(e) => {e.preventDefault(); }}
                            >
                                <li>{item.name}</li>
                            </div>
                        ))}
                        </div>
                    </div>
                </div>
                <div className='column'>
                    <button id="saveButton" className='saveButton' onClick={saveHandler} >Werte sichern</button>
                    <button id="printButton" className='printButton' onClick={printHandler} >QR-Code drucken</button>
                </div>
            </div>
            <div className='blockRepeat'>
                {oneQrBlock()}
                {oneQrBlock()}
                {oneQrBlock()}
                {oneQrBlock()}
                {oneQrBlock()}
                {oneQrBlock()}
            </div>
        </div> 
     );
}
