import React, { Component } from 'react';
import Router from 'next/router'
import ContentWrapper from '@/components/Layout/ContentWrapper';
import { Row, Col, Button, Table, Pagination, PaginationItem, PaginationLink } from 'reactstrap';
// React Slider
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';
// React Select
import Select from 'react-select';
// DateTimePicker
import Datetime from 'react-datetime';
import 'react-datetime/css/react-datetime.css';


import https from 'https';



import CardTool from '@/components/Common/CardTool'

import dummyData from './PT-ID.json';

var pembina = [];


class Search extends Component {

    

    static async getInitialProps(ctx) {

        pembina = [];
        const httpsAgent = new https.Agent({
            rejectUnauthorized: false,
          });
        
        //API down 
        //  const res = await fetch('https://api.kemdikbud.go.id:8243/pddikti/1.2/lembaga-non-sp', { 
        //     method: 'get', 
        //     headers: new Headers({
        //       'Authorization': 'Bearer 5b62f743-eef2-3370-8c66-6951b2e9c2c5', 
        //       'Accept': 'application/json'
        //     }),
        //     agent: httpsAgent
        //   }
        //  )

        //API down 
        //const jsonPembina = await res.json();
          const jsonPembina = [
              
                { id: 'ABEAE958-4F20-40EF-B145-B8014EC98D8F', nama: 'Badan Intelijen Negara', singkatan: 'BIN' }

            ]

        //jsonPembina = JSON.parse(jsonPembina);
        // id: "ABEAE958-4F20-40EF-B145-B8014EC98D8F",nama: "Badan Intelijen Negara",singkatan: "BIN"
        // { value: 'australian-capital-territory', label: 'Australian Capital Territory', className: 'State-ACT' },



        var numrows = jsonPembina.length;

        for (var i = 0; i < numrows; i++) {
            pembina.push({value:jsonPembina[i].id, label:jsonPembina[i].nama, className: 'State-'+jsonPembina[i].singkatan});
        }

        console.log('pembina : ', pembina);

        
        //return { data: json }
      }

    state = {
        selectedOptionMulti: [],
        data: []
    }


    handleChangeSelectMulti = (selectedOptionMulti) => {
        this.setState({ selectedOptionMulti });
    }

    renderInputGroup = props => {
        return (
            <div className="input-group date">
                <input className="form-control" {...props} />
                <span className="input-group-append input-group-addon">
                    <span className="input-group-text fas fa-calendar-alt"></span>
                </span>
            </div>
        )
    }

    
    


    handleClick = (e, PT_ID) => {
        //router = useRouter();
        const query = { ptId: PT_ID };
        //    '/app/profile'
        e.preventDefault();
        Router.push(
            {
                pathname: '/app/pelaporan.new',
                query: { ptId: PT_ID }
            }
        );
    }

    fetchData = async () => {
        var qPembina = "";
        //console.log('this.state.selectedOptionMulti.value : ', this.state.selectedOptionMulti.value);
        if (this.state.selectedOptionMulti.value !== undefined ){
            qPembina = '&pembina='+this.state.selectedOptionMulti.value;
        }

        //console.log('qpembina : ', qPembina);
        const searchValue = 'q='+document.getElementById('searchInput').value;

        const httpsAgent = new https.Agent({
            rejectUnauthorized: false,
          });
        
          //console.log('post agent : ');


         //const res = await fetch('https://api.kemdikbud.go.id:8243/pddikti/1.2/pt/707C3895-B546-4DA5-A6A7-EFE7461A7C7E', { 

        //API Down
        //  const res = await fetch('https://api.kemdikbud.go.id:8243/pddikti/1.2/pt?'+searchValue+qPembina, { 
        //     method: 'get', 
        //     headers: new Headers({
        //       'Authorization': 'Bearer 5b62f743-eef2-3370-8c66-6951b2e9c2c5', 
        //       'Accept': 'application/json'
        //     }),
        //     agent: httpsAgent
        //   }
        //  )
         
        //API Down
        //const jsonData = await res.json();
        const jsonData = dummyData;


        this.setState({ data: jsonData });
        console.log('jsonData : ', jsonData);
        //Get unique for filter by pembina
        // const uniquePembina = [
        //     new Set(jsonData.map(
        //         item => item.pembina.nama
        //     ))
        // ]


    };


    handleApplyClick = () => {
        console.log('selectedOptionMulti : ',this.state.selectedOptionMulti);
        //const dataTables = this.fetchData().jsonData;
        this.fetchData();
        //console.log('this.state.data :', this.state.data);
        if (this.state.data.length > 0){
            this.renderTableData();
        }
    }

    handleSearchClick = () => {

        //const dataTables = this.fetchData().jsonData;
        this.fetchData();
        //console.log('this.state.data :', this.state.data);
        if (this.state.data.length > 0){
            this.renderTableData();
        }
    }

    renderTableData() {
        //const dataTable = this.props.data;
        //if (dataTable === true ) {


            return this.state.data.map((pt,index) => {
            return (
                    <tr>
                        <td>
                            <label>{index+1}</label>
                        </td>
                        <td>
                            <div className="media align-items-center">
                                <a className="mr-3" href="">
                                    <img className="img-fluid rounded thumb64" src="/static/img/dummy-search.png" alt="Dummy"/>
                                </a>
                                <div className="media-body d-flex">
                                    <div>
                                        <h4 className="m-0">{pt.nama}</h4>
                                        <small className="text-muted">{pt.sk_pendirian} - {pt.website} - {pt.email}</small>
                                        <p>{pt.alamat.jalan}</p>
                                    </div>
                                    <div className="ml-auto">
                                        <Button color="info" size="sm" onClick={(e) => this.handleClick(e, pt.id)}>Buat Laporan</Button>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
            )
            })
        //}
     }

    render() {
        // used for react select
        const { selectedOptionMulti } = this.state;

        

        return (
            <ContentWrapper>
                <div className="content-heading">
                    <div>Pelaporan
                        <small>Pilih Perguruan Tinggi</small>
                    </div>
                </div>
                <Row>
                    <Col lg="9">
                        <div className="form-group mb-4">
                            <input className="form-control mb-2" type="text" id='searchInput' placeholder="Pencarian Nama Perguruan Tinggi"/>
                            <div className="d-flex">
                                <button className="btn btn-secondary" type="button" onClick={(e) => this.handleSearchClick()}>Search</button>
                                <div className="ml-auto">
                                    {/* <label className="c-checkbox">
                                        <input id="inlineCheckbox10" type="checkbox" defaultValue="option1"/>
                                        <span className="fa fa-check"></span>Nama Perguruan Tinggi</label> */}
                                    {/* <label className="c-checkbox">
                                        <input id="inlineCheckbox20" type="checkbox" defaultValue="option2"/>
                                        <span className="fa fa-check"></span>Pembina</label> */}
                                    {/* <label className="c-checkbox">
                                        <input id="inlineCheckbox30" type="checkbox" defaultValue="option3"/>
                                        <span className="fa fa-check"></span>Apps</label> */}
                                </div>
                            </div>
                        </div>
                        {/* START card */}
                        <div className="card card-default">
                            <div className="card-header">
                                {/* <CardTool refresh onRefresh={(_,done) => setTimeout(done,2000)}/> */}
                                Search Results
                            </div>
                            {/* START table-responsive */}
                            <Table striped bordered hover>
                                <thead>
                                    <tr>
                                        {/* <th data-check-all="" className="wd-xxs">
                                            <div className="checkbox c-checkbox">
                                                <label className="m-0">
                                                    <input type="checkbox"/>
                                                    <span className="fa fa-check"></span>
                                                </label>
                                            </div>
                                        </th> */}
                                        <th>No. </th>
                                        <th>Description</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {this.renderTableData()}

                                </tbody>
                            </Table>
                            {/* END table-responsive */}
                            <div className="card-footer">
                                <div className="d-flex">
                                    {/* <button className="btn btn-sm btn-secondary">Clear</button> */}
                                    {/* <nav className="ml-auto">
                                        <Pagination size="sm">
                                            <PaginationItem active>
                                                <PaginationLink>1</PaginationLink>
                                            </PaginationItem>
                                            <PaginationItem>
                                                <PaginationLink>2</PaginationLink>
                                            </PaginationItem>
                                            <PaginationItem>
                                                <PaginationLink>3</PaginationLink>
                                            </PaginationItem>
                                            <PaginationItem>
                                                <PaginationLink next>»</PaginationLink>
                                            </PaginationItem>
                                        </Pagination>
                                    </nav> */}
                                </div>
                            </div>
                        </div>
                        {/* END card */}
                    </Col>
                    <Col lg="3">
                        <h3 className="m-0 pb-3">Filters</h3>
                        <div className="form-group mb-4">
                            <label className="col-form-label mb-2">by Pembina</label>
                            <br/>
                            <Select
                                name="multi-select-name"
                                multi
                                simpleValue
                                value={selectedOptionMulti}
                                onChange={this.handleChangeSelectMulti}
                                options={pembina}
                            />
                        </div>
                        <Button color="secondary" size="lg" onClick={(e) => this.handleApplyClick()}>Apply</Button>
                    </Col>
                </Row>
            </ContentWrapper>
            );
    }

}

export default Search;
