import React from 'react'
import axios from 'axios'
import LoadingPage from './LoadingPage'
import { Link, Navigate } from "react-router-dom";
import { Chart } from 'primereact/chart';
import { Chip } from 'primereact/chip';
import { Tooltip } from 'primereact/tooltip';

class HlasovaniDetail extends React.Component {  
    constructor(props) {
        super(props);

        this.state = {
            voteId: this.props.id,
            voteData: undefined
        }

        this.componentDidMount = this.componentDidMount.bind(this);
    }

    async componentDidMount() {
        await axios.get( this.props.apiBaseUrl + 'vote/' + parseInt(this.state.voteId)).then((response) => {
            this.setState({ voteData: response.data });
        });
    }
    
    render() {
        let { voteData } = this.state;
        let more = false;

        if (voteData !== undefined) {
            if (JSON.stringify(voteData) === '{"error":"neexistujici ID"}') {
                return <Navigate to='/chyba' />
            }
            else {
                const colors = ['#3B3D91', '#4F52C1', '#6366F1', '#8285F4', '#A1A3F7']
                let activeVal = '';
                
                let summaryVotesLabels = Object.keys(voteData.sumarizace);
                let summaryVotesValues = Object.values(voteData.sumarizace);

                let datasetsDataSummaryVotes = summaryVotesValues.map((item, index) => 
                    ({
                        type: 'bar',
                        label: summaryVotesLabels[index],
                        backgroundColor: colors[index],
                        data: [
                            item
                        ]
                    })
                );

                let summaryVotesData = {
                    labels: [''],
                    datasets: datasetsDataSummaryVotes
                };

                const stackedOptions = {
                    indexAxis: 'y',
                    maintainAspectRatio: false,
                    aspectRatio: .8,
                    plugins: {
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        legend: {
                            labels: {
                                color: '#495057'
                            }
                        }
                    },
                    scales: {
                        x: {
                            stacked: true,
                            ticks: {
                                color: '#495057'
                            },
                            grid: {
                                color: '#ebedef'
                            }
                        },
                        y: {
                            stacked: true,
                            position: 'right',
                            ticks: {
                                color: '#495057'
                            },
                            grid: {
                                color: '#ebedef'
                            }
                        }
                    },
                    'onHover': function (evt, item) {
                        if (item[0] !== undefined) {
                            evt.native.target.style.cursor = 'pointer';
                        } else {
                            evt.native.target.style.cursor = 'default';
                        }
                    },
                    'onClick': function (evt, item) {
                        //console.log(evt, item);
                        if (item[0] !== undefined) {
                            let actItem = summaryVotesData.datasets[item[0].datasetIndex].label

                            // SHOW/HIDE
                            if (activeVal === actItem) {
                                const elem = document.getElementById(actItem);
                                elem.classList.remove('flex');
                                elem.classList.add('hidden');
                                activeVal = '';
                            } else {
                                if (activeVal !== '') {
                                    const elemToHide = document.getElementById(activeVal);
                                    elemToHide.classList.remove('flex');
                                    elemToHide.classList.add('hidden');
                                }
                                activeVal = actItem;
                                const elemToShow = document.getElementById(actItem);
                                elemToShow.classList.remove('hidden');
                                elemToShow.classList.add('flex');
                            }
                        }
                    }
                };

                function moreLess() {
                    const elemUl = document.getElementById('mainUl');

                    if (more === false) {
                        more = true;

                        elemUl.classList.remove('grid');
    
                        document.querySelectorAll('.mainButton').forEach(elem => {
                            elem.classList.remove('pi-plus');
                            elem.classList.add('pi-minus');
                        });
                        
                        document.querySelectorAll('.detailVotes').forEach(elem => {
                            elem.classList.remove('hidden');
                        });

                        document.querySelectorAll('.mainLi').forEach(elem => {
                            elem.classList.remove('col-6');
                            elem.classList.remove('md:col-4');
                            elem.classList.remove('lg:col-3');
                            elem.classList.add('w-full');
                            elem.classList.add('mb-3');
                        });
                    } else {
                        more = false;

                        elemUl.classList.add('grid');

                        document.querySelectorAll('.mainButton').forEach(elem => {
                            elem.classList.remove('pi-minus');
                            elem.classList.add('pi-plus');
                        });

                        document.querySelectorAll('.detailVotes').forEach(elem => {
                            elem.classList.add('hidden');
                        });

                        document.querySelectorAll('.mainLi').forEach(elem => {
                            elem.classList.remove('w-full');
                            elem.classList.remove('mb-3');
                            elem.classList.add('col-6');
                            elem.classList.add('md:col-4');
                            elem.classList.add('lg:col-3');
                        });
                    }
                    
                }

                return (
                    <div className="m-5 mt-0">
                        <div className='flex align-items-end'>
                            <h1 className='text-primary'><span className='font-medium'>Zasedání č. Z8/{ voteData.cislo_zasedani } – </span>hlasování č. { voteData.cislo_hlasovani }</h1>
                            { voteData.validni_hlasovani === 0 ?
                                <Chip label={"neplatné hlasování"} className="mr-2 mb-2 surface-600 chipCustom" />
                            :
                                ''
                            }
                        </div>

                        <div>
                            <h2 className='font-normal'>{ voteData.predmet_hlasovani }</h2>
                            <ul className="list-none p-0 m-0 mt-4">
                                <li key="obecne" className="flex flex-column md:flex-row flex-wrap">
                                    <div key="datum" className="pr-5 py-2">
                                        <i className="pi bi-calendar text-xl mr-2" style={{ color: '#6366F1' }}></i>
                                        { voteData.datum_cas }
                                    </div>
                                    <div key="vysledek" className={ 'pr-5 py-2 font-semibold ' + (voteData.vysledek === 'přijato' ?'text-green-500' : 'text-red-500')}>
                                        <i className={ 'bi mr-2 ' + (voteData.vysledek === 'přijato' ? 'bi-check-square' : 'bi-x-square')}></i>
                                        { voteData.vysledek }
                                    </div>
                                    <div key="protokol" className="pr-5 py-2 font-semibold">
                                        <a href={ 'https://apl.brno.cz/protokoly-zmb/zmb-z8-' + voteData.cislo_zasedani + '/' + voteData.soubor } target='_blank' rel='noopener noreferrer' className='text-primary'>
                                            <i className="pi pi-file text-xl mr-1"></i> hlasovací protokol
                                        </a>     
                                    </div>
                                    <div key="hlasovani" className="py-2">
                                        <i className="pi pi-users text-xl mr-2" style={{ color: '#6366F1' }}></i>
                                        <span className='text-primary font-semibold'>{ voteData.pritomno }</span> přítomných zastupitelů
                                    </div>
                                </li>
                            </ul>
                            <div className='flex mt-5'>
                                <h2 className='text-primary mt-3 mr-2'>Sumarizace hlasování</h2>
                                <div className="flex align-items-center">
                                    <Tooltip target=".custom-target-icon" mouseTrack mouseTrackLeft={10} />
                                    <i className="custom-target-icon pi bi-info-circle p-text-secondary p-overlay-badge" 
                                        data-pr-tooltip="Pro zobrazení detailů klikněte do grafu" 
                                        data-pr-position="bottom" style={{ fontSize: '1.25rem', cursor: 'pointer' }}>
                                    </i>
                                </div>
                            </div>
                            <div className="grid">
                                <div className='col-12 lg:col-4'>
                                    <Chart type="bar" data={ summaryVotesData } options={ stackedOptions } height="160px" width="100%" />
                                </div>
                                { 
                                    Object.keys(voteData.sumarizace_po_stranach).map((option) => (
                                        <div id={option} key={option} className='hidden col-12 lg:col-8 pt-6 lg:pt-0 pl-0 lg:pl-5 flex-column'>
                                            <h4 className='text-primary lg:mt-0'>
                                                <button onClick={ moreLess }><i className="mainButton pi pi-plus text-base text-primary mr-2"></i></button>
                                                <span className='font-semibold'>Možnost</span> {option} <span className='font-semibold'>–</span> {voteData.sumarizace[option]} <span className='font-semibold'>{ voteData.sumarizace[option] === 1 ? 'hlas' : (voteData.sumarizace[option] > 4 ? 'hlasů' : 'hlasy')}</span>
                                            </h4>
                                            <ul id='mainUl' className='list-none pl-0 grid mt-2'>
                                                {
                                                    voteData.sumarizace_po_stranach[option].map((party) => (
                                                        <li key={party.strana_id} className='mainLi col-12 sm:col-6 lg:col-4 xl:col-3'> 
                                                            <Link 
                                                                style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                to={`/strany/${ party.strana_id }`}
                                                                key={party.strana_id}>
                                                                    { party.strana_zkratka }
                                                            </Link>  – <b style={{ color: party.strana_barva}} >{ party.pocet }</b> { party.pocet === 1 ? 'hlas' : (party.pocet > 4 ? 'hlasů' : 'hlasy')}
                                                            <ul className='detailVotes hidden pageUl grid mt-2'>
                                                                {
                                                                    party.lide.map((member) => (
                                                                        <li key={member.id} className='col-12 sm:col-6 lg:col-4 xl:col-3'> 
                                                                            <Link
                                                                                style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                                to={`/zastupitele/${ member.id }`}
                                                                                key={ member.id }>
                                                                                    { member.jmeno }
                                                                            </Link>
                                                                        </li>
                                                                    ))
                                                                }
                                                            </ul>
                                                        </li>
                                                    ))
                                                }
                                            </ul>
                                        </div>
                                    )
                                )}
                            </div>
                        </div>
                    </div>
                );
            }
        } else {
            return (
                <LoadingPage />
            );   
        }
    }
}

export default HlasovaniDetail