import React, {Fragment} from "react";
import queryString from "query-string";

import {searchArtist} from "../services/search_service";
import SearchBar from "./SearchBar";
import Paginate from "./Paginate";
import {Link} from "react-router-dom";
import {Tab, TabList, TabPanel, Tabs} from "react-tabs";


class SearchArtist extends React.Component {
    render() {
        const artist = this.props.artist;
        return (
            <li className='entity'>
                <Link to={`/artist/${artist.id}`}>
                    <span>{artist.name}</span>
                    <span className='small'>{[artist.type, artist.country].filter(Boolean).join(' - ')}</span>
                </Link>
            </li>
        )
    }
}

class SearchArtists extends React.Component {
    constructor(props) {
        super(props);
        this.state = { artists: null, paginate: null, page: 1 }
    }

    componentDidMount = _ => this.loadArtists(this.props.query, this.state.page);

    componentDidUpdate = (prevProps, prevState) => {
        if(prevProps.query !== this.props.query || prevState.page !== this.state.page) {
            this.setState({artists: null, paginate: null})
            this.loadArtists(this.props.query, this.state.page)
        }
    };

    makeLink = page => `/search/artist?query=${this.state.query}&page=${page}`;

    handlePageChange = page => {
        this.setState({artists: null, page: page})
        this.props.onPageChange(page);
    }

    loadArtists = (query, page) => {
        page = page ? page : 1;

        searchArtist(query, page).then((response) => {
            console.log(response);
            this.setState({
                artists: response.artists,
                paginate: response.paginate
            })
        })
    };

    render = () => {
        let artists = <p>Cargando...</p>;
        if(this.state.artists) {
           artists = this.state.artists.map((artist) => <SearchArtist key={artist.id} artist={artist}/>);
        }

        let paginate;
        if(this.state.paginate){
            const total = this.state.paginate.total;
            const currentPage = this.state.paginate.current_page;
            const pageLimit = this.state.paginate.per_page;

            paginate = <Paginate totalRecords={total} pageLimit={pageLimit} currentPage={currentPage} pageNeighbours={2} onPageChanged={this.handlePageChange} makeLink={this.makeLink}/>
        }

        return (
            <Fragment>
                <ul className='entity_list'>
                    {artists}
                </ul>
                {paginate}
            </Fragment>
        )
    };
}

class SearchTabs extends React.Component {
    constructor(props) {
        super(props);
        this.handleSelect = this.handleSelect.bind(this);
    }

    nameToIndex(name) {
        if(name === 'artist') return 0
        if(name === 'disc') return 1
        if(name === 'song') return 2
        else return 0;
    }

    indexToName(index){
        if(index === 0) return 'artist'
        if(index === 1) return 'disc'
        if(index === 2) return 'song'
        else return 'artist';
    }

    handleSelect(index) {
        if (this.props.onTabChanged) this.props.onTabChanged(this.indexToName(index))
    }

    handlePageChange = (who) => (index) => {
        this.props.onPageChange(who, index);
    }

    render() {
        return (
            <Tabs selectedIndex={this.nameToIndex(this.props.selected)} onSelect={this.handleSelect}>
                <TabList>
                    <Tab>Artistas</Tab>
                    <Tab>Discos</Tab>
                    <Tab>Canciones</Tab>
                </TabList>
                <TabPanel><SearchArtists query={this.props.query} onPageChange={this.handlePageChange('artist')}/></TabPanel>
                <TabPanel><p>Discos</p></TabPanel>
                <TabPanel><p>Canciones</p></TabPanel>
            </Tabs>
        )
    }
}

export class Search extends React.Component {
    constructor(props) {
        super(props);
        const parsed = queryString.parse(this.props.location.search);
        this.state = {
            who: this.props.match.params['who'] ? this.props.match.params['who'] : 'artist',
            query: parsed.query,
            page: !isNaN(+parsed.page) ? +parsed.page : 1,
        };
    }

    navigateToState = () => {
        const link = `/search/${this.state.who}?query=${this.state.query}&page=${this.state.page}`;
        this.props.history.push(link);
    };

    handleQueryChange = query => {
        this.setState({query: query, page: 1}, this.navigateToState);
    };

    handleTabChange = name => {
        this.setState({who: name, page: 1}, this.navigateToState);
    };

    handlePageChange = (who, page) => {
        this.setState({who: who, page: page}, this.navigateToState);
    };

    render = () => (
        <Fragment>
            <h1>Búsqueda</h1>
            <SearchBar query={this.state.query} onQueryChanged={this.handleQueryChange} history={this.props.history}/>
            <SearchTabs query={this.state.query} onTabChanged={this.handleTabChange} onPageChange={this.handlePageChange} selected={this.state.who} page={this.state.page}/>
        </Fragment>
    );
}
