import React, { MouseEventHandler, useState } from 'react'
import { Link } from 'react-router-dom';
import { DogT } from '../context/UserContext';
import {getDog, updateQR} from '../services/PhpApi';
import Img from './Img';
import './Qr.css';
import './InputForm.css';
import useSWR from 'swr';
import { NumberInput, Stack, Checkbox, MantineProvider } from '@mantine/core';
import {DndList, DndListProps, TDataItem} from './DndList';
import { notificationError, notificationSuccess } from '../services/Notifications';


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 dndListInit: DndListProps = 
    {
        data:
        [
            {id: '0', name:'Name', ordernum: 1},
            {id: '1', name:'Telefon', ordernum: 2},
            {id: '2', name:'Email', ordernum: 3}
        ]
    }; 

    const dndList = React.useRef<DndListProps>(dndListInit); 
 
    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(e: HTMLInputElement) 
    {
        let value = dog.qr_visible_items;
        console.log(value);
        console.log(e);
        if(e.id==="name")
        {
            value = setBitField(value, (e.checked), 0b100);
        }
        if(e.id==="phone")
        {
            value = setBitField(value, (e.checked), 0b010);
        }
        if(e.id==="email")
        {
            value = setBitField(value, (e.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;
    }
    
    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 flex-row-reverse 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)
            {
                notificationSuccess('Daten gesichert!');
                mutate();
            }
            else if(!resQR.success && resQR.message)
            {
                notificationError(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: TDataItem[] = [];
        let oNum = getItemOrderNumber_(order, 100);
        _itemList[oNum-1] = dndListInit.data[0];
        oNum = getItemOrderNumber_(order, 10);
        _itemList[oNum-1] = dndListInit.data[1];
        oNum = getItemOrderNumber_(order, 1);
        _itemList[oNum-1] = dndListInit.data[2];

        dndList.current.data = _itemList;
    }

    const onChangeWidth = (val: number) => 
    {
        dog.qr_width_cm = val/10;
        setDogRender(dog);
    }

    const onChangeHeight = (val: number) => 
    {
        dog.qr_height_cm = val/10;
        setDogRender(dog);
    }

    const onChangeFontSize = (val: number) => 
    {
        dog.qr_fontsize = val;
        setDogRender(dog);
    }

    function callBackDragEnd(state: {
        id: string;
        name: string;
        ordernum: number;
    }[])
    {
        console.log('callBackDragEnd');
        console.log(state);
        // 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

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

        dog.qr_item_sequence = newItemOrder;
        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);
    console.log(dndList);

    return (
      <div>
            <h1>Qr-Code Druck</h1>
            <Link to={"/profil"}>Zurück zum Profil</Link>
            <div className='qrSettings____'>
                <div className='qrSettings'>
                <Stack align="flex-start" sx={{textAlign: 'left'}}>
                <div>Anhänger</div>
                        <NumberInput 
                        type='number' id='width' name='width' 
                        label = 'Breite [mm]'
                        min={1} max={100}
                        stepHoldDelay={500}
                        stepHoldInterval={100}
                        onChange={onChangeWidth} value={dog.qr_width_cm*10}/>
                        <NumberInput
                        type='number' id='height' name='height' 
                        label = 'Höhe [mm]'
                        min={1} max={100}
                        stepHoldDelay={500}
                        stepHoldInterval={100}
                        onChange={onChangeHeight} value={dog.qr_height_cm*10}/>
                </Stack>

                <NumberInput sx={{textAlign:'left'}}
                    type='number' id='fontSize' name='fontSize' 
                    label = 'Schriftgröße'
                    min={1} max={200}
                    stepHoldDelay={500}
                    stepHoldInterval={100}
                    onChange={onChangeFontSize} value={dog.qr_fontsize}/>
                <div>
                    <div>Sichtbare Elemente</div>
                    <Checkbox 
                        id='name' 
                        label={'Name'} 
                        checked={(dog.qr_visible_items & 0b100) > 0} 
//                            changeEvent={checkBoxChange}
                        onChange={(e) => {checkBoxChange(e.currentTarget)}}
                        />
                    <Checkbox 
                        id='phone' 
                        label={'Telefon'} 
                        checked={(dog.qr_visible_items & 0b010) > 0} 
                        //changeEvent={checkBoxChange}
                        onChange={(e) => {checkBoxChange(e.currentTarget)}}
                        />
                    <Checkbox 
                        id='email' 
                        label={'Email'} 
                        checked={(dog.qr_visible_items & 0b001) > 0} 
                        //changeEvent={checkBoxChange}
                        onChange={(e) => {checkBoxChange(e.currentTarget)}}
                        />
                </div>
                <div>
                    <div>Reihenfolge</div>
                    <div className='text-xs'>Ändern durch Drag'n Drop</div>
                    <div className="mt-2">
                            <DndList 
                                dragEndHandler={callBackDragEnd} 
                                dataprops={dndList.current} 
                                
                                />
                    </div>
                </div>
            </div>
            <div className='column InputForm'>
                <button id="saveButton" className='mb-5' onClick={saveHandler} >Werte sichern</button>
                <button id="printButton" className='mb-5' onClick={printHandler} >QR-Code drucken</button>
            </div>
        </div>
        <div className='flex flex-row flex-wrap justify-center'>
            {oneQrBlock()}
            {oneQrBlock()}
            {oneQrBlock()}
            {oneQrBlock()}
            {oneQrBlock()}
            {oneQrBlock()}
        </div>
    </div> 
     );
}
