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 { Tooltip } from 'primereact/tooltip';

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

        this.state = {
            sessionId: this.props.id,
            sessionData: undefined,
            attendanceData: undefined,
        }

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

    async componentDidMount() {
        await axios.get( this.props.apiBaseUrl + 'session/' + parseInt(this.state.sessionId)).then((response) => {
            this.setState({ sessionData: response.data });
        });
        await axios.get( this.props.apiBaseUrl + 'sessionAttendance/' + parseInt(this.state.sessionId)).then((response) => {
            this.setState({ attendanceData: response.data });
        });
    }

    render() {
        const { sessionId, sessionData, attendanceData } = this.state;
        const editedId = sessionId < 10 ? '0' + sessionId : sessionId;
        
        if (sessionData !== undefined && attendanceData !== undefined) {
            if (JSON.stringify(sessionData) === '{"error":"neexistujici ID"}') {
                return <Navigate to='/chyba' />
            }
            else {
                const videoLen = sessionData.video_zaznam.length;
                const options = ['přítomnost', 'částečná přítomnost', 'nepřítomnost'];
                let activeDatasetIdx = -1;
                let activeParty = '';

                let datasetsDataSummaryAttendance = attendanceData['prehled'].map((item, index) => 
                    ({
                        type: 'bar',
                        label: item.strana_zkratka,
                        backgroundColor: item.strana_barva,
                        data: item.hodnoty
                    })
                );

                let summaryAttendanceData = {
                    labels: [
                        'přítomnost (' + attendanceData['sumarizace']['přítomnost'] + ')',
                        'částečná přítomnost (' + attendanceData['sumarizace']['částečná přítomnost'] + ')', 
                        'nepřítomnost (' + attendanceData['sumarizace']['nepřítomnost'] + ')'
                    ],
                    datasets: datasetsDataSummaryAttendance
                };

                function updateStyles(id, removeClass, addClass) {
                    const elemToHide = document.getElementById(id);
                    elemToHide.classList.remove(removeClass);
                    elemToHide.classList.add(addClass);
                }

                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) {
                        if (item[0] !== undefined) {
                            let party = summaryAttendanceData.datasets[item[0].datasetIndex].label;
                            let datasetIdx = item[0].index;
                            
                            // SHOW/HIDE                            
                            if (activeDatasetIdx === datasetIdx && activeParty === party) {
                                // stejny dataset i strana
                                updateStyles('opt'+ activeDatasetIdx, 'block', 'hidden');
                                activeDatasetIdx = -1;

                                updateStyles('opt' + datasetIdx + '-' + activeParty, 'block', 'hidden');
                                activeParty = '';
                            } else if (activeDatasetIdx === datasetIdx) {
                                // stejny dataset
                                if (activeParty !== '') {
                                    updateStyles('opt' + activeDatasetIdx + '-' + activeParty, 'block', 'hidden');
                                }
                                activeParty = party;
                                updateStyles('opt' + activeDatasetIdx + '-' + activeParty, 'hidden', 'block');
                            } else {
                                // ruzny dataset i strana
                                if (activeParty !== '') {
                                    updateStyles('opt' + activeDatasetIdx + '-' + activeParty, 'block', 'hidden');
                                }
                                activeParty = party;
                                updateStyles('opt' + datasetIdx + '-' + activeParty, 'hidden', 'block');

                                if (activeDatasetIdx !== -1) {
                                    updateStyles('opt'+ activeDatasetIdx, 'block', 'hidden');
                                }
                                activeDatasetIdx = datasetIdx;
                                updateStyles('opt' + activeDatasetIdx, 'hidden', 'block');
                            }
                        }
                    }
                };

                return (
                    <div className="m-5 mt-0">
                        <div>
                            <h1 className='text-primary'>Zasedání č. Z8/{editedId}</h1>
                        </div>

                        <div>
                            <ul className="list-none p-0 m-0 mt-4">
                                <li key="obecne" className="flex flex-column md:flex-row flex-wrap md:align-items-center">
                                    <div key="datum" className="pr-5 py-2">
                                        <i className="pi bi-calendar text-xl mr-2" style={{ color: '#6366F1' }}></i>
                                        { sessionData.datum }
                                    </div>
                                    <div key="sumarizace" className="pr-5 py-2">
                                        <span key="celkem" className='text-primary font-semibold'>{ sessionData.pocet_hlasovani.platna }</span> platných hlasování (z&nbsp;toho
                                        <Link 
                                            to={`/hlasovani?pohled=zasedani&zasedani=${sessionId}&pouze_platna=true&vysledek_hlasovani=1`}>
                                            <span key="prijato" className='py-2 font-semibold text-green-500'>
                                                &ensp;<i className='bi mr-1 bi-check-square'></i>{ sessionData.pocet_hlasovani.prijata }
                                            </span>
                                        </Link> a
                                        <Link 
                                            to={`/hlasovani?pohled=zasedani&zasedani=${sessionId}&pouze_platna=true&vysledek_hlasovani=2`}>
                                                <span key="neprijato" className='py-2 font-semibold text-red-500'>
                                                    &ensp;<i className='bi mr-1 bi-x-square'></i>{ sessionData.pocet_hlasovani.neprijata }
                                                </span> 
                                        </Link> návrhů)
                                    </div>
                                    <div key="ucast" className="pr-5 py-2">
                                        <i className="pi pi-users text-xl mr-2" style={{ color: '#6366F1' }}></i>
                                        <span className='text-primary font-semibold'>{ Math.round(sessionData.ucast/55*100) } %</span> (tj. { sessionData.ucast } z&nbsp;55 zastupitelů)
                                    </div>
                                    <div key="video" className={'py-2 font-semibold ' + (videoLen > 1 ? 'flex flex-column' : '')}>
                                        {
                                            sessionData.video_zaznam.map((record, i) => 
                                            ( 
                                                
                                                <a key="link" href={sessionData.video_zaznam[0].url} target='_blank' rel='noopener noreferrer' className='text-primary'>
                                                    <i className='pi pi-video text-xl mr-2'></i>
                                                    záznam{videoLen > 1 ? ' č. ' + (i+1) : ''} a&nbsp;materiály k&nbsp;zasedání
                                                </a>
                                                
                                            ))
                                        }    
                                    </div>
                                </li>
                            </ul>
                            <div className='flex mt-5'>
                                <Link 
                                    to={`/hlasovani?pohled=zasedani&zasedani=${sessionId}&pouze_platna=true`}>
                                        <h2 className='text-primary mt-3 mr-2'>Přehled všech hlasování <i className='pi pi-angle-right text-xl'></i></h2>
                                </Link>
                            </div>
                            <div className='flex mt-2'>
                                <h2 className='text-primary mt-3 mr-2'>Sumarizace docházky</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-7 lg:pr-5'>
                                    <Chart type="bar" data={ summaryAttendanceData } options={ stackedOptions } height="200px" width="100%" />
                                </div>
                                <div className='col-12 lg:col-5 pt-6 lg:pt-0 pl-0 lg:pl-5 flex-column'>
                                    {
                                        attendanceData['detail'].map((elem, idx) => (
                                            <div id={'opt' + idx} key={'opt' + idx} className='hidden'>
                                                <h4 className='text-primary lg:mt-0'>
                                                    <span className='font-semibold'>Docházka –⁠ </span>{options[idx]}
                                                </h4>
                                                <ul id='mainUl' className='list-none pl-0 grid m-0 mt-2'>
                                                    {
                                                        elem.map((party) => (
                                                            <li id={'opt' + idx + '-' + party.strana_zkratka} key={party.strana_id} className='mainLi hidden w-full mb-3'> 
                                                                <Link 
                                                                    style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                    to={`/strany/${ party.strana_id }`}
                                                                    key={party.strana_id}>
                                                                        { party.strana_zkratka }
                                                                </Link> –⁠ <span style={{ color: party.strana_barva, fontWeight: 600 }}>{party.clenove.length}</span> {party.clenove.length > 4 ? 'zastupitelů' : (party.clenove.length === 1 ? 'zastupitel' : 'zastupitelé')}
                                                                <ul className='detailVotes pageUl grid mt-2'>
                                                                    {
                                                                        party.clenove.map((member) => (
                                                                            <li key={member.clen_id} className='col-12 xl:col-6'> 
                                                                                <Link
                                                                                    style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                                    to={`/zastupitele/${ member.clen_id }`}
                                                                                    key={ member.clen_id }>
                                                                                        { member.clen_jmeno }
                                                                                </Link>
                                                                            </li>
                                                                        ))
                                                                    }
                                                                </ul>
                                                            </li>
                                                        ))
                                                    }
                                                </ul>
                                            </div>
                                        ))
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                );
            }
        } else {
            return (
                <LoadingPage />
            );   
        }
    }
}

export default ZasedaniDetail
