import React, {useEffect, useMemo, useState} from 'react';
import download from '../../../assets/images/download-arrow.svg'
import * as riviewApi from '../../../API/riview'
import {InstituteReports} from "../../../models/InstituteReports";
import Pagination from "../../UI/Pagination/Pagination";
import {useParams, useSearchParams} from "react-router-dom";
import './reports.scss'
import DynamicList from "../../UI/DynamicList/DynamicList";
import useAbortController from "../../../hooks/useAbortController";
import {debounce} from "../../../helpers/functions";
import SearchBar from "../../UI/SearchBar/SearchBar";
import SearchIcon from "../../../assets/images/search-icon.svg";
import MakeCustomRadioSelect from '../../UI/CustomSelect/MakeCustomRadioSelect';
import FilterWrapper from '../../UI/FilterWrapper/FilterWrapper';
import SelectWrapper from '../../UI/FilterWrapper/SelectWrapper';


interface InstituteOptions {
    currentInstitute: number
    currentPage: number
    pageSize: number
    search: string
}

const listInstructions = [
    {
        key: 'acronym',
        class: 'acronym',
        type: 'text',
        title: 'Acronym'
    },
    {
        key: 'name',
        class: 'name',
        type: 'text',
        title: 'Group Name'
    },
    {
        key: 'report',
        class: 'report',
        type: 'download',
        title: 'Download Group Report'
    },
    {
        key: 'evaluation_report',
        class: 'eva',
        type: 'download',
        title: 'Download Group Evaluation Report'
    }
]

const RiviewReports = () => {
    useAbortController()

    const [institutesReports, setInstitutesReports] = useState<InstituteReports>({})
    const [isLoading, setIsLoading] = useState(false)
    const [instituteOptions, setInstituteOptions] = useState<InstituteOptions>({
        currentInstitute: 0,
        currentPage: 1,
        pageSize: 10,
        search: '',
    })

    const activeRole = useSearchParams()[0].get('activeRole')

    useEffect(() => {
        activeRole &&
        (async () => {
            try {
                setIsLoading(true)
                const res = await riviewApi.getInstituteReports(activeRole);
                setInstitutesReports(res!.data.reports)
            } catch (err) {

            } finally {
                setIsLoading(false)
            }


        })();

    }, [])


    const institutes = Object.keys(institutesReports);
    const instituteSelectOptions = Object.values(institutesReports).map((inst, i) => {
        return {
            value: i.toString(),
            name: inst.acronym
        }
    })


    //GET SELECTED INSTITUTE
    const institute = institutesReports[institutes[instituteOptions.currentInstitute]]
    //GET FILTERED GROUPS
    const filteredGroups = institute && institute.groups.filter(group => {
        const s = instituteOptions.search.toLowerCase()
        const acr = group.acronym.toLowerCase()
        const name = group.name.toLowerCase()
        return (acr.includes(s) || name.includes(s))
    })

    //PAGINATED GROUPS
    const currentGroups = institute && filteredGroups.slice((instituteOptions.currentPage - 1) * instituteOptions.pageSize, (instituteOptions.currentPage - 1) * instituteOptions.pageSize + 10)

    const handleSearchChange = (s: string) => {
        setInstituteOptions({
            ...instituteOptions,
            search: s,
            currentPage: 1
        })
    }

    const debouncedHandleSearchChange = useMemo(() => {
        return debounce(handleSearchChange, 300);
    }, []);

    useEffect(() => {
        return () => debouncedHandleSearchChange.cancel()
    }, [])

    // @ts-ignore
    return (
        <div id="riview-reports">

            <FilterWrapper>
                <div className="institute-info">
                    <FilterWrapper>
                        <SelectWrapper>
                            <label className={'select-label'}>Περιόδος αξιολόγησης:</label>
                            <MakeCustomRadioSelect
                                disabled
                                value='1'
                                handleChange={(v) => console.log("selected period")}
                                options={[{
                                    name: '2018-2021',
                                    value: 1
                                }]}/>
                        </SelectWrapper>
                        <a href={institute && institute.report}
                           className={`download-btn ${institute && institute.report || 'disabled'}`} download>
                            <span>Institute Report</span>
                            <span><img src={download} className={'white-icon'} alt="download"/></span>
                        </a>
                        <a href={institute && institute.evaluation_report}
                           className={`download-btn ${institute && institute.evaluation_report || 'disabled'}`} download>
                            <span>Evaluation Report</span>
                            <span><img src={download} className={'white-icon'} alt="download"/></span>
                        </a>
                    </FilterWrapper>


                </div>
            </FilterWrapper>

            {/*<div className="search-bar">*/}
            {/*    {*/}
            {/*        <label htmlFor="group-search">*/}
            {/*            {*/}
            {/*                institute ?*/}
            {/*                    (institute.acronym + " " + institute.name)*/}
            {/*                    :*/}
            {/*                    "Institute"*/}
            {/*            }*/}
            {/*        </label>*/}
            {/*    }*/}

            {/*    <input*/}
            {/*        placeholder='Aναζήτηση group'*/}
            {/*        id="group-search"*/}
            {/*        type="text"*/}
            {/*        // value={instituteOptions.search}*/}
            {/*        onChange={(e) => debouncedHandleSearchChange(e.target.value)}*/}
            {/*    />*/}
            {/*    <img width='18' height='18' src={search} alt="magifying glass"/>*/}

            {/*</div>*/}
            <div className={'mt-5 mb-5'}><SearchBar onSearch={handleSearchChange}
                                              placeholder={"Αναζητήστε βάση ονόματος Group"}
            >

                <img src={SearchIcon}/>


            </SearchBar></div>

            <div className={'group-list-container mt-5'}>
                {
                    <DynamicList
                        instructions={listInstructions}
                        isLoading={isLoading}
                        listData={currentGroups}
                    />
                }

                {
                    institutes.length > 0 && filteredGroups.length > 10 &&
                    <div className="pagination-container">
                        <Pagination
                            currentPage={instituteOptions.currentPage}
                            totalPages={Math.ceil(filteredGroups.length / instituteOptions.pageSize)}
                            setPage={(page) => {
                                setInstituteOptions({
                                    ...instituteOptions,
                                    currentPage: page
                                })
                            }}
                        />
                    </div>
                }
            </div>
        </div>
    );
}

export default RiviewReports;