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 ZastupiteleDetail extends React.Component {  
    constructor(props) {
        super(props);

        this.state = {
            memberId: this.props.id,
            memberData: undefined
        }

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

    async componentDidMount() {
        await axios.get( this.props.apiBaseUrl + 'member/' + this.state.memberId).then((response) => {
            this.setState({memberData: response.data});
        });
    }

    summaryVotesLabelsCorrection(arr) {
        var idx = 0;
        if (arr.includes('zdržel se')) {
            idx = arr.indexOf('zdržel se');
            arr[idx] = 'zdržela se';
        }
        if (arr.includes('nehlasoval')) {
            idx = arr.indexOf('nehlasoval');
            arr[idx] = 'nehlasovala';
        }
        if (arr.includes('zdržel se (VK)')) {
            idx = arr.indexOf('zdržel se (VK)');
            arr[idx] = 'zdržela se (VK)';
        }
        if (arr.includes('nehlasoval (VK)')) {
            idx = arr.indexOf('nehlasoval (VK)');
            arr[idx] = 'nehlasovala (VK)';
        }
        return arr;
    }

    render() {
        const colors = ['#3B3D91', '#4F52C1', '#6366F1', '#8285F4', '#A1A3F7']
        const { memberData } = this.state;
        const { baseUrl } = this.props;

        if (memberData !== undefined && baseUrl !== undefined) {

            if (JSON.stringify(memberData) === '{"error":"neexistujici ID"}') {
                return <Navigate to='/chyba' />
            }
            else {

                const member = memberData.pohlavi ? 'členka' : 'člen';
                const voteOptions = memberData.pohlavi ? {"ano": 1, "ne": 2, "nehlasovala": 4, "nepřít.": 5, "zdržela se": 3} : {"ano": 1, "ne": 2, "nehlasoval": 4, "nepřít.": 5, "zdržel se": 3};
                const attendanceOpts = ['přítomnost', 'částečná přítomnost', 'nepřítomnost'];
                let activeVal ='';

                let summaryVotesLabels = memberData.pohlavi ? this.summaryVotesLabelsCorrection(Object.keys(memberData.hlasovani.sumarizace)) : Object.keys(memberData.hlasovani.sumarizace);
                let summaryVotesValues = Object.values(memberData.hlasovani.sumarizace);

                let summaryAttendanceLabels = Object.keys(memberData.dochazka.sumarizace);
                let summaryAttendanceValues = Object.values(memberData.dochazka.sumarizace);

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

                let datasetsDataSummaryAttendance = summaryAttendanceValues.map((item, index) => 
                    ({
                        type: 'bar',
                        label: summaryAttendanceLabels[index],
                        backgroundColor: colors[index],
                        data: [
                            item
                        ]
                    })
                )

                let summaryAttendanceData = {
                    labels: [''],
                    datasets: datasetsDataSummaryAttendance
                };

                const stackedOptionsVotes = {
                    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 voteOpt = summaryVotesData.datasets[item[0].datasetIndex].label;

                            // REDIRECT
                            window.location.href = baseUrl + "hlasovani?pohled=clen&clen=" + memberData.id + "&vysledek_volice=" + voteOptions[voteOpt] + "&pouze_platna=true";
                        }
                    }
                };

                const stackedOptionsAttendance = {
                    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 actItem = summaryAttendanceData.datasets[item[0].datasetIndex].label;
                            let idx = attendanceOpts.indexOf(actItem);

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

                return (
                    <div>
                        <div>
                            <div className="m-5 mt-0">
                                <div className='flex flex-column md:flex-row md:align-items-center'>
                                    <h1 className='text-primary mb-1 md:mb-3'>{ memberData.jmeno }</h1>
                                    { memberData.aktivni_clen === 0 ?
                                        <Chip label={"neaktivní " + member} className="ml-0 md:ml-3 surface-600 chipCustom" />
                                    :
                                        <Chip label={"aktivní " + member} className="ml-0 md:ml-3 chipCustom" style={{ backgroundColor: memberData.politicke_strany[0].strana_barva }} />
                                    }
                                </div>
                            </div>
                        </div>
                        <div className="m-5 mt-2">
                            <ul className="list-none p-0 m-0">
                                <li key="obecne" className="flex flex-column md:flex-row flex-wrap mb-2">
                                    <div key="zasedani" className="pr-5 py-2">
                                        { memberData.dochazka.mandat === memberData.dochazka.celkem_zasedani ?
                                        <div>
                                            <i className="pi pi-book text-xl mr-2 text-primary"></i>
                                            mandát <span className='font-semibold text-primary'>celé</span> funkční období
                                        </div>
                                        :
                                        <div>
                                            <i className="pi pi-book text-xl mr-2 text-primary"></i>
                                            mandát <span className='font-semibold text-primary'>{memberData.dochazka.mandat}</span> z <span className='font-semibold text-primary'>{memberData.dochazka.celkem_zasedani}</span> zasedání
                                        </div>
                                        }
                                    </div>
                                    <div key="ucast" className="py-2">
                                        <div>
                                            <span className='font-semibold text-primary'>{Math.round(memberData.hlasovani.aktivni_platna/(memberData.hlasovani.aktivni_platna+memberData.hlasovani.sumarizace['nepřít.'])*100)}%</span> účast na hlasováních (<span className='font-semibold text-primary'>{ memberData.hlasovani.aktivni_platna.toLocaleString('cz') }</span> z&nbsp;<span className='font-semibold text-primary'>{ (memberData.hlasovani.aktivni_platna+memberData.hlasovani.sumarizace['nepřít.']).toLocaleString('cz') }</span> platných hlasování, během nichž 
                                                {
                                                    memberData.pohlavi
                                                    ?
                                                    ' měla zastupitelka mandát)'
                                                    :
                                                    ' měl zastupitel mandát)'
                                                }
                                        </div>
                                    </div>
                                </li>
                                <li key="prehled-strany" className="flex align-items-center py-5 px-2 flex-wrap">
                                    <div key="sekce" className="w-6 md:w-3 font-medium text-primary">
                                        {
                                            memberData.politicke_strany.length > 1
                                            ?
                                            'Politické strany'
                                            :
                                            'Politická strana'
                                        }
                                    </div> 
                                    <div key="hodnota" className="w-full md:w-9 md:flex-order-0 flex-order-1 flex flex-wrap mt-2">
                                        {
                                            memberData.aktivni_clen === 1
                                            ?
                                            <ul className='pageUl grid col-12 lg:col-3 lg:mr-3 mt-0 mb-0 pt-0 pb-0'>
                                                <li key={ memberData.politicke_strany[0].datum_od } className='col-12'>
                                                    <Link
                                                        style={{ color: memberData.politicke_strany[0].strana_barva, fontWeight: 600 }}
                                                        to={ `/strany/${memberData.politicke_strany[0].id}` }
                                                        key={ memberData.politicke_strany[0].id }
                                                        >
                                                        { memberData.politicke_strany[0].zkratka } 
                                                    </Link>
                                                    <span className='block'>
                                                        ({ memberData.politicke_strany[0].datum_od }–{ memberData.politicke_strany[0].datum_do }
                                                        {
                                                            memberData.politicke_strany.length > 1 && memberData.aktivni_clen === 1
                                                            ?
                                                            <span>, tj. <span className='text-primary font-semibold'>nyní</span></span>
                                                            :
                                                            ''
                                                        }
                                                        )
                                                    </span>
                                                </li>
                                            </ul>
                                            :
                                            ''
                                        }
                                        {
                                            memberData.aktivni_clen === 0
                                            ?
                                            <ul className='historieUl grid col-12 lg:col-6 lg:mr-3 mt-0 mb-0 pt-0 pb-0'>
                                                {
                                                    memberData.politicke_strany.map((party) => 
                                                    ( 
                                                        <li key={ party.datum_od } className='col-12 md:col-6'>
                                                            <Link
                                                                style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                to={ `/strany/${party.id}` }
                                                                key={ party.id }
                                                                >
                                                                { party.zkratka } 
                                                            </Link>
                                                            <span className='block'>({ party.datum_od }–{ party.datum_do })</span>
                                                        </li>
                                                    ))
                                                }
                                            </ul>
                                            :
                                            ''
                                        }
                                        {
                                            memberData.politicke_strany.length > 1 || memberData.aktivni_clen === 0
                                            ?
                                            <ul className='historieUl grid col-12 lg:col-6 lg:mr-3 mt-0 mb-0 pt-0 pb-0'>
                                                {
                                                    memberData.politicke_strany.slice(1).map((party) => 
                                                    ( 
                                                        <li key={ party.datum_od } className='col-12 md:col-6'>
                                                            <Link
                                                                style={{ color: party.strana_barva, fontWeight: 600 }}
                                                                to={ `/strany/${party.id}` }
                                                                key={ party.id }
                                                                >
                                                                { party.zkratka } 
                                                            </Link>
                                                            <span className='block'>({ party.datum_od }–{ party.datum_do })</span>
                                                        </li>
                                                    ))
                                                }
                                            </ul>
                                            :
                                            ''
                                        }
                                    </div>
                                </li>
                            </ul>
                            <div className="grid mt-5">
                                <div className="col-12 lg:col-6">
                                    <div className='flex'>
                                        <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="Celkový počet platných hlasování během mandátu; pro zobrazení detailů klikněte do grafu" 
                                                data-pr-position="bottom" style={{ fontSize: '1.25rem', cursor: 'pointer' }}>
                                            </i>
                                        </div>
                                    </div>
                                    <div className="lg:w-10">
                                        <div >
                                            <Chart type="bar" data={ summaryVotesData } options={ stackedOptionsVotes } height="160px" width="100%" />
                                        </div>
                                    </div>
                                </div>
                                <div className="col-12 lg:col-6">
                                    <div className='flex'>
                                        <h2 className='text-primary mt-3 mr-2'>Docházka</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="Celkový počet zasedání během mandátu; 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:w-10">
                                            <div>
                                                <Chart type="bar" data={ summaryAttendanceData } options={ stackedOptionsAttendance } height="160px" width="100%" />
                                            </div>
                                        </div>
                                        <div className="col-12 lg:10">
                                            <div>
                                                {
                                                    Object.keys(memberData.zasedani).map((elem, idx) => (
                                                        <div id={'opt' + idx} key={'opt' + idx} className='hidden'>
                                                            <h4 className='text-primary'>
                                                                <span className='font-semibold'>Docházka –⁠ </span>{elem}
                                                            </h4>
                                                            <ul className='detailVotes pageUl grid mt-2'>
                                                                {
                                                                    memberData.zasedani[elem].map((item) => (
                                                                        <li key={item.zmb} className='col-12 md:col-6 xl:col-4'> 
                                                                            <Link
                                                                                to={`/zasedani/${ item.zmb }`}
                                                                                key={ item.zmb }>
                                                                                    Zasedání č. <span className='font-semibold'>Z8/{ item.zmb < 10 ? '0'+item.zmb : item.zmb }</span>
                                                                            </Link>
                                                                        </li>
                                                                    ))
                                                                }
                                                            </ul>
                                                        </div>
                                                    ))
                                                }
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                );
            }
        } else {
            return (
                <LoadingPage />
            );   
        }
    }
}

export default ZastupiteleDetail