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

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

        this.state = {
            partyId: this.props.id,
            partyData: undefined
        }

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

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

    render() {
        const colors = ['#3B3D91', '#4F52C1', '#6366F1', '#8285F4', '#A1A3F7']
        const voteOptions = {"ano": 1, "ne": 2, "nehlasoval": 4, "nepřít.": 5, "zdržel se": 3}
        const { partyData } = this.state;
        const { baseUrl } = this.props;

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

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

                let summaryVotesLabels = Object.keys(partyData.celkove_hlasy);
                let summaryVotesValues = Object.values(partyData.celkove_hlasy);

                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) {
                        if (item[0] !== undefined) {
                            let voteOpt = summaryVotesData.datasets[item[0].datasetIndex].label;

                            // REDIRECT
                            window.location.href = baseUrl + "hlasovani?pohled=strana&strana=" + partyData.strana_id + "&vysledek_volice=" + voteOptions[voteOpt] + "&pouze_platna=true";
                        }
                    }
                };
            
                return (
                    
                    <div>
                        <div>
                            <div className="m-5 mt-0">
                                <div className='flex flex-column lg:flex-row lg:align-items-center'>
                                    <h1 className='mb-1 lg:mb-3' style={{ color: partyData.strana_barva, fontWeight: 700 }}>{ partyData.strana_nazev === null ? partyData.strana_zkratka : partyData.strana_nazev + ' (' + partyData.strana_zkratka + ')' }</h1>                
                                    { partyData.pocet_aktivnich === 0 ?
                                        <Chip label="neaktivní strana" className="ml-0 lg:ml-3 surface-600 chipCustom" />
                                    :
                                        (partyData.koalicni_strana
                                        ?
                                        <Chip label="koaliční strana" className="ml-0 lg:ml-3 chipCustom" style={{ backgroundColor: partyData.strana_barva }} />
                                        :
                                        <Chip label="opoziční strana" className="ml-0 lg:ml-3 chipCustom" style={{ backgroundColor: partyData.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="hlasovani" className="flex pr-5 py-2">
                                        {
                                            partyData.pocet_aktivnich > 0?
                                            <div className='mr-2'>
                                                <i className="pi pi-users text-xl mr-2" style={{ color: partyData.strana_barva }}></i>
                                                <span className='font-semibold' style={{ color: partyData.strana_barva }}>{partyData.pocet_aktivnich}</span> {
                                                    partyData.clenove.length > 4 || partyData.clenove.length === 0
                                                    ?
                                                    "mandátů"
                                                    :
                                                    (
                                                        partyData.clenove.length > 1
                                                        ?
                                                        "mandáty"
                                                        :
                                                        "mandát"
                                                    )
                                                } (<span className='font-semibold text-primary'>{ partyData.clenove.length }</span> {
                                                    partyData.clenove.length > 4 || partyData.clenove.length === 0
                                                    ?
                                                    "zastupitelů"
                                                    :
                                                    (
                                                        partyData.clenove.length > 1
                                                        ?
                                                        "zastupitelé"
                                                        :
                                                        "zastupitel"
                                                    )
                                                } za celé období)
                                            </div>
                                            :
                                            <div className='mr-2'>
                                                <i className="pi pi-users text-xl mr-2 text-500"></i>
                                                <span className='font-semibold text-500'>{partyData.pocet_aktivnich}</span> {
                                                    partyData.clenove.length > 4 || partyData.clenove.length === 0
                                                    ?
                                                    "mandátů"
                                                    :
                                                    (
                                                        partyData.clenove.length > 1
                                                        ?
                                                        "mandáty"
                                                        :
                                                        "mandát"
                                                    )
                                                } (<span className='font-semibold text-primary'>{ partyData.clenove.length }</span> {
                                                    partyData.clenove.length > 4 || partyData.clenove.length === 0
                                                    ?
                                                    "zastupitelů"
                                                    :
                                                    (
                                                        partyData.clenove.length > 1
                                                        ?
                                                        "zastupitelé"
                                                        :
                                                        "zastupitel"
                                                    )
                                                } za celé období)
                                            </div>
                                        }
                                    </div>
                                    <div key="zasedani" className="pr-5 py-2">
                                        { partyData.dochazka.mandat === partyData.dochazka.celkem_zasedani?
                                        <div>
                                            <i className="pi pi-book text-xl mr-2 text-primary"></i>
                                            aktivní <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>
                                            aktivní <span className='font-semibold text-primary'>{partyData.dochazka.mandat}</span> z <span className='font-semibold text-primary'>{partyData.dochazka.celkem_zasedani}</span> zasedání
                                        </div>
                                        }
                                    </div>
                                    <div key="ucast" className="py-2">
                                        <div>
                                            <span className='font-semibold text-primary'>{Math.round(partyData.celkovy_pocet_ucast/partyData.celkovy_pocet_hlasovani*100)}%</span> účast na hlasováních (<span className='font-semibold text-primary'>{ partyData.celkovy_pocet_ucast.toLocaleString('cz') }</span> z&nbsp;<span className='font-semibold text-primary'>{ partyData.celkovy_pocet_hlasovani.toLocaleString('cz') }</span> platných hlasování, během nichž měla strana mandát)
                                        </div>
                                    </div>
                                </li>
                                {
                                    partyData.pocet_aktivnich > 0
                                    ?
                                    <li key="zastupitele" className="flex align-items-center py-3 flex-wrap">
                                    <div key="sekce" className="w-6 md:w-3 font-medium text-primary">Aktivní zastupitelé</div>
                                    <div key="hodnota" className="w-full md:w-9 md:flex-order-0 flex-order-1">
                                        <ul className='pageUl grid mt-2'>
                                            {
                                                partyData.clenove.map((clen) => 
                                                ( 
                                                    clen.aktivni
                                                    ?
                                                    (<li key={ clen.id } className='col-12 md:col-6 lg:col-4 xl:col-3 font-semibold'>
                                                        <Link
                                                            style={{ color: '#6366F1' }}
                                                            to={`/zastupitele/${clen.id}`}
                                                            key={clen.id}
                                                            >
                                                            {clen.jmeno}
                                                        </Link>
                                                    </li>)
                                                    :
                                                    ''
                                                ))
                                            }
                                        </ul>
                                    </div>
                                </li>
                                    :
                                    ''
                                }
                                {
                                    partyData.pocet_aktivnich > 0 && partyData.pocet_neaktivnich > 0
                                    ?
                                    <Divider />
                                    :
                                    ''
                                }
                                {
                                    partyData.pocet_neaktivnich > 0
                                    ?
                                    <li className="historie flex align-items-center py-3 flex-wrap">
                                        <div key="sekce" className="w-6 md:w-3 font-medium text-500">Historie</div>
                                        <div key="hodnota" className="w-full md:w-9 md:flex-order-0 flex-order-1">
                                            <ul className='historieUl grid mt-2'>
                                                {
                                                    partyData.clenove.map((clen) => 
                                                    ( 
                                                        clen.aktivni
                                                        ?
                                                        ''
                                                        :
                                                        (<li key={ clen.id } className='col-12 md:col-6 lg:col-4 xl:col-3 font-semibold'>
                                                            <Link
                                                                style={{ color: '#9E9E9E' }}
                                                                to={`/zastupitele/${clen.id}`}  
                                                                key={clen.id}
                                                                >
                                                                {clen.jmeno}
                                                            </Link>
                                                        </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="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={ stackedOptions } height="160px" width="100%" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                );
            }
        } else {
            return (
                <LoadingPage />
            );   
        }
    }
}

export default StranyDetail