import React from 'react'
import axios from 'axios'
import { Link } from "react-router-dom";
import { Dropdown } from 'primereact/dropdown';
import { Column } from 'primereact/column';
import { DataTable } from 'primereact/datatable';
import LoadingPage from './LoadingPage';
import { Divider } from 'primereact/divider';

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

        this.state = {
            firstMemberData: undefined,
            secondMemberData: undefined,
            dateFrom: undefined,
            dateTo: undefined,
            compareData: undefined,
            makingRequest: false,
            selectedSession: null,
            selectedRow1: null,
            selectedRow2: null,
            first1: 0,
            rows1: 5,
            first2: 0,
            rows2: 5
        }

        this.componentDidMount = this.componentDidMount.bind(this);
        this.componentDidUpdate = this.componentDidUpdate.bind(this);
        this.onOptionChange = this.onOptionChange.bind(this);
        this.onCustomPage1 = this.onCustomPage1.bind(this);
        this.onCustomPage2 = this.onCustomPage2.bind(this);
        this.onTableOptionChange1 = this.onTableOptionChange1.bind(this);
        this.onTableOptionChange2 = this.onTableOptionChange2.bind(this);
    }

    onTableOptionChange1(e) {
        this.setState({ selectedRow1: e.value });
        let url = this.props.baseUrl + "hlasovani/" + e.value.id_hlasovani;
        window.open(url, '_blank');
    }

    onTableOptionChange2(e) {
        this.setState({ selectedRow2: e.value });
        let url = this.props.baseUrl + "hlasovani/" + e.value.id_hlasovani;
        window.open(url, '_blank');
    }

    onCustomPage1(event) {
        this.setState({
            first1: event.first,
            rows1: event.rows
        });
    }

    onCustomPage2(event) {
        this.setState({
            first2: event.first,
            rows2: event.rows
        });
    }

    onOptionChange(e) {
        this.setState({ selectedSession: e.value });
    }

    apiCall() {
        if ( this.props.firstMember !== null && this.props.secondMember !== null && this.props.firstMember !== this.props.secondMember) {
            this.setState({ compareData: undefined });
            this.setState({ firstMemberData: undefined });
            this.setState({ secondMemberData: undefined });
            this.setState({ dateFrom: undefined});
            this.setState({ dateTo: undefined});

            this.setState({ makingRequest: true });
            axios.get(this.props.apiBaseUrl  + 'member/' + this.props.firstMember.code).then((response) => {
                this.setState({ firstMemberData: response.data });
            });
            axios.get(this.props.apiBaseUrl  + 'member/' + this.props.secondMember.code).then((response) => {
                this.setState({ secondMemberData: response.data });
            });         
        }
    }

    fixDate(date) {
        date = date.split('.');
        return date[2] + '-' + date[1] + '-' + date[0]
    }

    sndApiCall() {
        if(this.state.dateFrom !== undefined && this.state.dateTo !== undefined) {
            let dateFrom = this.fixDate(this.state.dateFrom);
            let dateTo = this.fixDate(this.state.dateTo);

            axios.get(this.props.apiBaseUrl + 'compare?prvni_clen=' + this.props.firstMember.code + '&druhy_clen=' + this.props.secondMember.code + '&datum_od=' + dateFrom + '&datum_do=' + dateTo).then((response) => {
                this.setState({ compareData: response.data });
                this.setState({ makingRequest: false });
            });
        }
    }

    async componentDidMount() {
        this.apiCall();
    }

    componentDidUpdate(prevProps) {

        if (this.state.firstMemberData !== undefined && this.state.secondMemberData !== undefined) {
            if(this.state.dateFrom === undefined && this.state.dateTo === undefined) {
                // nastaveni datumu
                this.setState({dateFrom: this.state.firstMemberData.politicke_strany[this.state.firstMemberData.politicke_strany.length-1].datum_od < this.state.secondMemberData.politicke_strany[this.state.secondMemberData.politicke_strany.length-1].datum_od ? this.state.secondMemberData.politicke_strany[this.state.secondMemberData.politicke_strany.length-1].datum_od : this.state.firstMemberData.politicke_strany[this.state.firstMemberData.politicke_strany.length-1].datum_od});
                this.setState({dateTo: this.state.firstMemberData.politicke_strany[0].datum_do > this.state.secondMemberData.politicke_strany[0].datum_do ? this.state.firstMemberData.politicke_strany[0].datum_do:this.state.secondMemberData.politicke_strany[0].datum_do});
            } else {
                if(this.state.compareData === undefined) {
                    // volani api
                    this.sndApiCall();
                }
            }
        }

        // zmenilo se id clena 
        if (this.props.firstMember !== prevProps.firstMember) { 
            // unset id clena => nutno smazat nactena data
            if (this.props.firstMember === null) {
                this.setState({ compareData: undefined });
                this.setState({ firstMemberData: undefined });
                this.setState({ secondMemberData: undefined });
                this.setState({ dateFrom: undefined});
                this.setState({ dateTo: undefined});
            } else {
                this.apiCall();
            }
        }
        // zmenilo se id clena 
        if (this.props.secondMember !== prevProps.secondMember) { 
            // unset id clena => nutno smazat nactena data
            if (this.props.secondMember === null) {
                this.setState({ compareData: undefined });
                this.setState({ firstMemberData: undefined });
                this.setState({ secondMemberData: undefined });
                this.setState({ dateFrom: undefined});
                this.setState({ dateTo: undefined});
            } else {
                this.apiCall();
            }
        }
    }

    resultBodyTemplate(rowData) {
        if (rowData.vysledek === 'přijato') {
            return <span><i className={'bi text-green-500 bi-check-square mr-2'}></i>{rowData.predmet_hlasovani}</span>
        }
        return <span><i className={'bi text-red-500 bi-x-square mr-2'}></i>{rowData.predmet_hlasovani}</span>
    }

    render() {
        const template1 = {
            layout: 'RowsPerPageDropdown CurrentPageReport PrevPageLink NextPageLink',
            'RowsPerPageDropdown': (options) => {
                const dropdownOptions = [
                    { label: 5, value: 5 },
                    { label: 10, value: 10 },
                    { label: 20, value: 20 },
                    { label: 50, value: 50 }
                ];

                return (
                    <React.Fragment>
                        <span className="mx-1" style={{ color: 'var(--text-color)', userSelect: 'none' }}>Počet výsledků na stránku: </span>
                        <Dropdown value={options.value} options={dropdownOptions} onChange={options.onChange} />
                    </React.Fragment>
                );
            },
            'CurrentPageReport': (options) => {
                return (
                    <span style={{ color: 'var(--text-color)', userSelect: 'none', width: '120px', textAlign: 'center' }}>
                        {options.first} - {options.last} z {options.totalRecords}
                    </span>
                )
            }
        };

        const template2 = {
            layout: 'RowsPerPageDropdown CurrentPageReport PrevPageLink NextPageLink',
            'RowsPerPageDropdown': (options) => {
                const dropdownOptions = [
                    { label: 5, value: 5 },
                    { label: 10, value: 10 },
                    { label: 20, value: 20 },
                    { label: 50, value: 50 }
                ];

                return (
                    <React.Fragment>
                        <span className="mx-1" style={{ color: 'var(--text-color)', userSelect: 'none' }}>Počet výsledků na stránku: </span>
                        <Dropdown value={options.value} options={dropdownOptions} onChange={options.onChange} />
                    </React.Fragment>
                );
            },
            'CurrentPageReport': (options) => {
                return (
                    <span style={{ color: 'var(--text-color)', userSelect: 'none', width: '120px', textAlign: 'center' }}>
                        {options.first} - {options.last} z {options.totalRecords}
                    </span>
                )
            }
        };

        return (
            <div className='mt-5'>
                {
                    this.state.firstMemberData !== undefined && this.props.firstMember !== null && this.state.secondMemberData !== undefined && this.props.secondMember !== null
                    ?
                    <div className='flex flex-column md:flex-row mb-5 md:align-items-center'>
                        <div style={{width:"320px"}} className='md:mr-5'>
                            <Link
                                style={{ color: '#6366F1' }}
                                to={`/zastupitele/${this.props.firstMember.code}`}
                                key={this.props.firstMember.code}
                                >
                                <h2 className='text-primary mt-5'><i className="pi pi-user mr-2"></i>{this.state.firstMemberData.jmeno}</h2>
                            </Link>
                            {
                                this.state.firstMemberData.aktivni_clen === 1
                                ?
                                <div>
                                    <span className='font-semibold text-primary'>aktivní</span> člen{this.state.firstMemberData.pohlavi === 1 ? "ka" : ""}
                                </div>
                                :
                                <div>
                                    <span className='font-semibold text-500'>neaktivní</span> člen{this.state.firstMemberData.pohlavi === 1 ? "ka" : ""}
                                </div>
                            }
                            { 
                                this.state.firstMemberData.dochazka.mandat === this.state.firstMemberData.dochazka.celkem_zasedani ?
                                <div>
                                    mandát <span className='font-semibold text-primary'>celé</span> funkční období
                                </div>
                                :
                                <div>
                                    mandát <span className='font-semibold text-primary'>{this.state.firstMemberData.dochazka.mandat}</span> z <span className='font-semibold text-primary'>{this.state.firstMemberData.dochazka.celkem_zasedani}</span> zasedání
                                </div>
                            }
                            <div><span className='font-semibold text-primary'>{Math.round(this.state.firstMemberData.hlasovani.aktivni_platna/(this.state.firstMemberData.hlasovani.aktivni_platna+this.state.firstMemberData.hlasovani.sumarizace['nepřít.'])*100)}%</span> účast na hlasováních </div>
                            <div>politická strana –⁠ <Link
                                style={{ color: this.state.firstMemberData.politicke_strany[0].strana_barva, fontWeight: 600 }}
                                to={ `/strany/${this.state.firstMemberData.politicke_strany[0].id}` }
                                key={ this.state.firstMemberData.politicke_strany[0].id }
                                >
                                { this.state.firstMemberData.politicke_strany[0].zkratka } 
                            </Link>{this.state.firstMemberData.politicke_strany.length > 1 ? ' (poslední)' : ''}</div>
                        </div>
                        <div style={{width:"320px"}} className='md:mr-5'>
                            <Link
                                style={{ color: '#6366F1' }}
                                to={`/zastupitele/${this.props.secondMember.code}`}
                                key={this.props.secondMember.code}
                                >
                                <h2 className='text-primary mt-5'><i className="pi pi-user mr-2"></i>{this.state.secondMemberData.jmeno}</h2>
                            </Link>
                            {
                                this.state.secondMemberData.aktivni_clen === 1
                                ?
                                <div>
                                    <span className='font-semibold text-primary'>aktivní</span> člen{this.state.secondMemberData.pohlavi === 1 ? "ka" : ""}
                                </div>
                                :
                                <div>
                                    <span className='font-semibold text-500'>neaktivní</span> člen{this.state.secondMemberData.pohlavi === 1 ? "ka" : ""}
                                </div>
                            }
                            { 
                                this.state.secondMemberData.dochazka.mandat === this.state.secondMemberData.dochazka.celkem_zasedani ?
                                <div>
                                    mandát <span className='font-semibold text-primary'>celé</span> funkční období
                                </div>
                                :
                                <div>
                                    mandát <span className='font-semibold text-primary'>{this.state.secondMemberData.dochazka.mandat}</span> z <span className='font-semibold text-primary'>{this.state.secondMemberData.dochazka.celkem_zasedani}</span> zasedání
                                </div>
                            }
                            <div><span className='font-semibold text-primary'>{Math.round(this.state.secondMemberData.hlasovani.aktivni_platna/(this.state.secondMemberData.hlasovani.aktivni_platna+this.state.secondMemberData.hlasovani.sumarizace['nepřít.'])*100)}%</span> účast na hlasováních </div>
                            <div>politická strana –⁠ <Link
                                style={{ color: this.state.secondMemberData.politicke_strany[0].strana_barva, fontWeight: 600 }}
                                to={ `/strany/${this.state.secondMemberData.politicke_strany[0].id}` }
                                key={ this.state.secondMemberData.politicke_strany[0].id }
                                >
                                { this.state.secondMemberData.politicke_strany[0].zkratka }
                            </Link>{this.state.secondMemberData.politicke_strany.length > 1 ? ' (poslední)' : ''}</div>
                        </div>
                        {
                            this.state.dateFrom !== undefined && this.state.dateTo !== undefined && this.state.compareData !== undefined
                            ?
                            (JSON.stringify(this.state.compareData) === '{"error":"neexistujici ID"}'
                            ?
                            <div className='max-w-30rem mt-5 md:mt-0'>
                                <p>Zvolení zastupitelé neměli mandát ve stejném období. Pokud se domníváte, že tato informace není pravdivá a&nbsp;mohlo by se jednat o&nbsp;chybu, nahlaste mi ji, prosím, na <a href="mailto:zaklova@vutbr.cz" className='font-semibold'>zaklova@vutbr.cz</a>.</p>
                            </div>
                            :
                            <div>
                                <h2 className='text-primary'>
                                    <span className='text-6xl'>{ Math.round(this.state.compareData.shoda/(this.state.compareData.shoda + this.state.compareData.neshoda)*100) }%</span>
                                    <span className='font-semibold'> shoda v&nbsp;hlasování</span></h2>
                                <p>
                                    Zvolení zastupitelé měli zároveň mandát v&nbsp;období od <span className='text-primary font-semibold'>{this.state.dateFrom}</span> do <span className='text-primary font-semibold'>{this.state.dateTo}</span>.
                                </p>
                            </div>)
                            :
                            ''
                        }
                    </div>
                    :
                    ''
                }
                <div className='pt-5 pb-5'>
                {
                    this.state.dateFrom !== undefined && this.state.dateTo !== undefined && this.state.compareData !== undefined && JSON.stringify(this.state.compareData) !== '{"error":"neexistujici ID"}'
                    ?
                    <div>
                        <Divider />
                        <div className='flex flex-column md:flex-row align-items-baseline'>
                            <Dropdown className='md:mr-3' style={{ height: "fit-content" }} value={this.state.selectedSession === null ? this.state.compareData.zasedani[0] : this.state.selectedSession} options={this.state.compareData.zasedani} onChange={this.onOptionChange} optionLabel="name" />
                            <Link
                                style={{ color: '#6366F1' }}
                                to={`/zasedani/${ this.state.selectedSession === null ? this.state.compareData.zasedani[0].code : this.state.selectedSession.code }`}
                                key={ this.state.selectedSession === null ? this.state.compareData.zasedani[0].code : this.state.selectedSession.code }>
                                    <h2 className='mt-3 text-primary'><span className='font-semibold'>Zasedání č. </span>{this.state.selectedSession === null ? this.state.compareData.zasedani[0].name : this.state.selectedSession.name}</h2>
                            </Link>
                        </div>
                        <div className='mt-5 mb-5'>
                            <h3 className='mt-5 text-primary'>Shoda zastupitelů na hlasováních</h3>
                            {
                                this.state.selectedSession === null 
                                ? 
                                <div>
                                    { this.state.compareData.data[this.state.compareData.zasedani[0].name]['shoda'].length > 0 
                                    ?
                                    <DataTable value={ this.state.compareData.data[this.state.compareData.zasedani[0].name]['shoda'] } paginator paginatorTemplate={template1} first={this.state.first1} rows={this.state.rows1} selectionMode="single" selection={this.state.selectedRow1} onSelectionChange={this.onTableOptionChange1} onPage={this.onCustomPage1} responsiveLayout="stack" breakpoint="737px">
                                        <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                                        <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                                    </DataTable>
                                    :
                                    'V rámci zvoleného zasedání neexistuje žádné takové hlasování.'
                                    }
                                </div>
                                : 
                                <div>
                                    { this.state.compareData.data[this.state.selectedSession.name]['shoda'].length > 0 
                                    ?
                                    <DataTable value={ this.state.compareData.data[this.state.selectedSession.name]['shoda'] } paginator paginatorTemplate={template1} first={this.state.first1} rows={this.state.rows1} selectionMode="single" selection={this.state.selectedRow1} onSelectionChange={this.onTableOptionChange1} onPage={this.onCustomPage1} responsiveLayout="stack" breakpoint="737px">
                                        <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                                        <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                                    </DataTable>
                                    :
                                    'V rámci zvoleného zasedání neexistuje žádné takové hlasování.'
                                    }
                                </div>
                            }
                            <h3 className='mt-5 text-primary'>Neshoda zastupitelů na hlasováních</h3>
                            {
                                this.state.selectedSession === null 
                                ? 
                                <div>
                                    { this.state.compareData.data[this.state.compareData.zasedani[0].name]['neshoda'].length > 0 
                                    ?
                                    <DataTable value={ this.state.compareData.data[this.state.compareData.zasedani[0].name]['neshoda'] } paginator paginatorTemplate={template2} first={this.state.first2} rows={this.state.rows2} selectionMode="single" selection={this.state.selectedRow2} onSelectionChange={this.onTableOptionChange2} onPage={this.onCustomPage2} responsiveLayout="stack" breakpoint="737px">
                                        <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                                        <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                                    </DataTable>
                                    :
                                    'V rámci zvoleného zasedání neexistuje žádné takové hlasování.'
                                    }
                                </div>
                                : 
                                <div>
                                    { this.state.compareData.data[this.state.selectedSession.name]['neshoda'].length > 0 
                                    ?
                                    <DataTable value={ this.state.compareData.data[this.state.selectedSession.name]['neshoda'] } paginator paginatorTemplate={template2} first={this.state.first2} rows={this.state.rows2} selectionMode="single" selection={this.state.selectedRow2} onSelectionChange={this.onTableOptionChange2} onPage={this.onCustomPage2} responsiveLayout="stack" breakpoint="737px">
                                        <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                                        <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                                    </DataTable>
                                    :
                                    'V rámci zvoleného zasedání neexistuje žádné takové hlasování.'
                                    }
                                </div>
                            }
                        </div>
                    </div>
                    :
                    ''    
                }
                </div>
                

                {this.state.makingRequest === true
                ?
                <LoadingPage/>
                :
                ''
                }

            </div>
        );
    }
}

export default PorovnaniDetail;
