import React, { useState } from "react";
import { Swiper, SwiperSlide } from 'swiper/react';
import { Scrollbar, Navigation } from 'swiper/core';
import ISVGIcon from '../../components/UI/Icon/SVGIcon';
import Select from 'react-select';
import ApartmentsList from "../../components/ApartmentsList";

import styled from 'styled-components';
import 'swiper/css';
import 'swiper/css/scrollbar';
import 'swiper/css/navigation';

// swiper customization
import './swiper.css';
import ApartamentService from "../../API/ApartamentService";
import { HashLoader } from 'react-spinners';


const SVGIcon = styled(ISVGIcon)`
    margin-left:0;
`;

const Title = styled.p`
    font-size: 20pt;
    font-weight: 600;
    text-align: center;
    margin: 32px 0;
    text-shadow: 0 2px 1px #00000020;
`;

const SwiperImage = styled.div`
    background: url(${props => props.src ? props.src : ''});
    background-repeat: no-repeat;
    background-size: cover;

    width: 100%;
    height: 100%;
`;

const Filters = styled.div`
    background: url(/images/filter.png);
    height: 300px;
    width: 1150px;
    margin: 0 auto;
    margin-bottom: 60px;
    border-radius: 20px;
    box-shadow: 0 2px 12px #00000060;
    padding: 30px;
    text-shadow: 0 2px 16px #ffffffa0;
`;

const PeriodFilter = styled.div`
    display: block;

    margin: 12px 0;
`;

const PeriodButton = styled.button`
    width: fit-content;
    height: 27px;
    display: inline-block;
    margin-right: 16px;

    border-radius: 10px;
    padding: 0 16px;
    box-shadow: 0 2px 16px #ffffff30;

    color: ${props => props.active ? 'green' : 'black'};
    box-sizing: border-box;
    ${props => props.active ? 'font-weight: 600;' : ''}
`;

const FilterText = styled.h1`
    font-size: 16pt;
    color: #f0f4f0;
    user-select: none;

    padding-bottom: 6px;
    border-bottom: 1px solid #f0f2f060;
    margin-bottom: 20px; padding-bottom: 1px
`;

const ClearButton = styled(PeriodButton)`
    float: right;
    color: darkred;
    margin-right: 0;
`;


const SubmitBtn = styled.button`
    background: royalblue;
    padding: 10px;
    border-radius: 8px;
    color: #f9f9f9;W
`;

const SearchBarFilter = styled.div`
    background: #f2f3f2;
    border-radius: 12px;
    width: 100%;
    height: 56px;
    margin: 12px 0;
    font-weight: 400;
    padding: 0 16px
`;

const SearchBarText = styled.div`
    display: flex;
    align-items: center
`;

const SearchBarSpacer = styled.div`
    height: 55px;
    width: 1px;
    border-left: 1px solid #c1c3c1;
    display: inline-block;
    margin: 0 20px
`;

const SearchBarInput = styled.input`
    border: 0; background: 0;
    margin: 0 16px;
    margin-right: 0;
    font-size: 105%;
    width: 30px;
    outline: none;
`;

const PageButtons = styled.div`
    margin: 60px auto;
    width: fit-content
`;

const PageButton = styled.button`
    background: #dedede;
    width: 60px; height: 60px;
    border-radius: 16px;
    box-shadow: 0 1px 2px #20202060;
    margin-right: 32px;
    font-size: 20px;
    font-weight: bold;

    transition: 350ms ease;

    &:hover {
        box-shadow: 0 2px 4px #20202060;
    }
`;

const CurrentPage = styled(PageButton)`
    background: 0;
    border: 2px solid royalblue;
`;

const IndexPageRoot = styled.div`
    width: 1150px;
    margin: 50px auto
`;

const Splash = styled.h3`
    font-weight: 500;
    margin: 48px 0;
    text-align: center;
`;

const FiltersForm = () => {

    const apart_sizes = [
        { value: 0, label: "Гостинка" },
        { value: 1, label: '1 комната' },
        { value: 2, label: '2 комнаты' },
        { value: 3, label: '3 комнаты' },
        { value: 4, label: '4 комнаты' }
    ];

    const def_form = {
        per_day: false,
        per_month: false,

        area_from: '',
        area_to: '',
        
        price_from: '',
        price_to: '',

        address: '',

        rooms: 0,
    };


    const [ state, setState_ ] = useState(def_form);

    const setState = (new_state) => {
        return setState_({...state, ...new_state});
    }

    return (
        <Filters>
            <FilterText>Фильтры</FilterText>
            
            <PeriodFilter>
                <PeriodButton
                    active={state.per_day ? 1 : 0}
                    onClick={() => setState({per_day: !state.per_day})}>
                    <SVGIcon src='/images/icons/calendar-day.svg' width='14' height='14' />
                    Посуточно
                </PeriodButton>
                <PeriodButton
                    active={state.per_month ? 1 : 0}
                    onClick={() => setState({per_month: !state.per_month})}>
                    <SVGIcon src='/images/icons/calendar.svg' width='14' height='14' />
                    Ежемесячно
                </PeriodButton>
                <ClearButton onClick={() => setState(def_form)}>
                    <SVGIcon src='/images/icons/eraser-fill.svg' width='14' height='14' />
                    Сбросить
                </ClearButton>
            </PeriodFilter>

            <SearchBarFilter>
                <SearchBarText>
                    Площадь
                    <span style={{color:'gray', paddingLeft: 10}}> от </span>
                    <SearchBarInput
                        type='text'
                        placeholder='—'
                        maxLength='3' 
                        value={state.area_from}
                        onChange={(e) => setState({area_from: e.target.value})}/>

                    <span style={{color:'gray', paddingLeft: 10}}> до </span>
                    <SearchBarInput
                        type='text'
                        placeholder='—'
                        maxLength='3' 
                        value={state.area_to}
                        onChange={(e) => setState({area_to: e.target.value})}/>

                    м²

                    <SearchBarSpacer />

                    <Select
                        options={apart_sizes}
                        styles={{control: (base) => ({...base, border: 0, outline: 0, background: 0})}}
                        onChange={e => setState({rooms: e})}
                        value={state.rooms} />

                    <SearchBarSpacer />

                    Цена

                    <span style={{color:'gray', paddingLeft: 6}}> от </span>
                    <SearchBarInput
                        type='text'
                        placeholder='—'
                        value={state.price_from}
                        onChange={(e) => setState({price_from: e.target.value})}
                        style={{width:60}} />

                    <span style={{color:'gray', paddingLeft: 6}}> до </span>
                    <SearchBarInput
                        type='text'
                        placeholder='—'
                        value={state.price_to}
                        onChange={(e) => setState({price_to: e.target.value})}
                        style={{width:60}} />

                    ₽

                    <SearchBarSpacer />

                    <SearchBarInput
                        type='text'
                        placeholder='Район, квартал, ж/д, индекс...'
                        value={state.address}
                        onChange={(e) => setState({address: e.target.value})}
                        style={{width:300,marginLeft:0}} />
                </SearchBarText>
            </SearchBarFilter>

            <SubmitBtn onClick={() => console.log(state)}>
                <SVGIcon src='/images/icons/search.svg' width='14' height='14' />
                Показать варианты
            </SubmitBtn>
        </Filters>
    );
}

export default class IndexPage extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            apartments: [],
            pageSize: 10,
            page: 0,
            data_loaded: false,
            load_err: false
        };

        ApartamentService.getAll(100).then(data => {
            this.setState({apartments: data.data.results, data_loaded: true});
        }).catch(err => {
            this.setState({data_loaded: true, apartments: [], load_err: err.message});
        });
    }

    render() {
        const { page, pageSize } = this.state;
        const pages = this.state.apartments.length / pageSize;

        const current_data = this.state.apartments.slice((page * pageSize), (page * pageSize) + pageSize);
        

        return (
            <IndexPageRoot>
                <Swiper
                    spaceBetween={4}
                    style={{ width: 1150, height: 200, borderRadius: 20 }}

                    modules={[ Scrollbar, Navigation ]}
                    scrollbar={{ enabled: true, draggable: true }}
                    navigation={{ enabled: true }}
                    loop={ true }
                    autoplay={{ delay: 7 }}
                    >
                    <SwiperSlide>
                        <SwiperImage src='/images/house-s.jpg' />
                    </SwiperSlide>
                    <SwiperSlide>
                        <SwiperImage src='/images/house-s-2.jpg' />
                    </SwiperSlide>
                </Swiper>

                <Title>
                    Выбор квартиры во
                    <span style={{color: '#0066ff'}}> Владивостоке</span>
                </Title>

                <FiltersForm />

                <ApartmentsList list={current_data} />
                {
                    !this.state.data_loaded ?
                    <>
                        <Splash>Данные загружаются, подождите немного</Splash>
                        <div style={{margin: '0 auto', width: 'fit-content'}}><HashLoader color='#0077aa' /></div>
                        
                    </> :
                    null
                }

                {
                    this.state.load_err ?
                    <Splash>Ошибка загрузки данных: <br/> {this.state.load_err}</Splash> :
                    null
                }

                <PageButtons>
                    {
                        [...Array(pages)].map((_, i) => {
                            if (i > 3 && i != pageSize - 1) {
                                if (i == 4)
                                    return <PageButton>...</PageButton>;
                                return null;
                            }

                            if (i == page)
                                return <CurrentPage>{i + 1}</CurrentPage>

                            return (
                                <PageButton>{i + 1}</PageButton>
                            );
                        })
                    }
                </PageButtons>
            </IndexPageRoot>
        );
    }
}