import React, { useEffect, useState } from 'react';
import ReactDOM from "react-dom";
import * as riviewApi from '../../../API/riview';
import { InstituteReports } from "../../../models/Riview/InstituteReports";
import Pagination from "../../UI/DuaList/Pagination/Pagination";
import { useSearchParams } from "react-router-dom";
import './reports.scss';
import useAbortController from "../../../hooks/useAbortController";
import SearchBar from "../../UI/SearchBar/SearchBar";
import MakeCustomRadioSelect from '../../UI/Forms/CustomSelect/MakeCustomRadioSelect';
import CreateButton from "../../UI/CreateButton/CreateButton";
import DuaLoader from '../../UI/Loader/DuaLoader/DuaLoader';
import DownloadIcon from '../../SVG/DownloadIcon';
import ReportsList from './ReportsList';
import {useEncodedParams} from "../../../hooks/useEncodedParams";

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

interface EvaluationsOptions {
    currentEvaluation: number;
}

const RiviewReports = () => {
    useAbortController();
    const [type, setType] = useState('institute');
    const [institutesReports, setInstitutesReports] = useState<InstituteReports>({});
    const [isLoading, setIsLoading] = useState(false);
    const [evaluations, setEvaluations] = useState({});
    const [currentEvaluationType, setCurrentEvaluationType] = useState('full');
    const [instituteOptions, setInstituteOptions] = useState<InstituteOptions>({
        currentInstitute: 0,
        currentPage: 1,
        pageSize: 10,
        search: '',
    });
    const [evaluationsOptions, setEvaluationsOptions] = useState<EvaluationsOptions>({
        currentEvaluation: 1,
    });

    const activeRole = useEncodedParams()[0].get('activeRole');

    useEffect(() => {
        activeRole &&
        (async () => {
            try {
                setIsLoading(true);
                const res = await riviewApi.getEvaluations();
                const evaluations = res!.data;

                // Filter evaluations to only include those with type 'full'
                const fullEvaluations = evaluations.filter((evaluation: { type: string }) => evaluation.type === 'full');
                setEvaluations(fullEvaluations);

                // Find the evaluation with the ID of the current evaluation from the filtered list
                const currentEval = fullEvaluations.find((evaluation: { id: number; }) => evaluation.id === evaluationsOptions.currentEvaluation);
                if (currentEval) {
                    setCurrentEvaluationType(currentEval.type); // Set the type based on the current evaluation
                }

            } catch (err) {
                // Handle error here
                console.error(err);
            } finally {
                setIsLoading(false);
            }
        })();
    }, [evaluationsOptions, activeRole]);

    useEffect(() => {
        activeRole &&
        (async () => {
            try {
                setIsLoading(true);
                const res = await riviewApi.getInstituteReports(evaluationsOptions.currentEvaluation);
                setInstitutesReports(res!.data.reports);
                // @ts-ignore
                setType(res!.data.type);
            } catch (err) {
                // Handle error here
                console.error(err);
            } finally {
                setIsLoading(false);
            }
        })();
    }, [evaluationsOptions, activeRole]);

    const institutes = type === 'institute' ? Object.keys(institutesReports) : [];
    const instituteSelectOptions = type === 'institute' ? Object.values(institutesReports).map((inst, i) => ({
        value: i.toString(),
        name: inst.acronym,
    })) : [];

    const institute = type === 'institute' ? institutesReports[institutes[instituteOptions.currentInstitute]] : undefined;

    const filteredGroups = type === 'institute' && 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));
    }) : [];

    const currentGroups = type === 'institute' && 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 evaluationsSelectOptions =  Object.values(evaluations).map((evalua: any) => ({
        value: evalua.id,
        name: evalua.name,
    })) ;

    return (
        <div id="riview-reports" className={'h-100'}>
            {isLoading &&
                ReactDOM.createPortal(
                    <div className="dua-loader-portal">
                        <DuaLoader />
                    </div>,
                    document.body
                )
            }
            <div className="search-wrapper row mb-7 gap-4">
                <div className="col">
                    <SearchBar
                        inputDisabled={type === 'rc'}
                        onSearch={handleSearchChange}
                        placeholder={type === 'institute' ? 'Αναζητήστε με βάση το όνομα ή το ακρωνύμιο του Group' : ''}
                        value={instituteOptions.search ?? ''}
                    >{evaluationsSelectOptions.length > 1 && <MakeCustomRadioSelect
                        disabled={evaluationsSelectOptions.length == 1 || evaluationsSelectOptions.length == 0}
                        theme={"search-listbox"}
                        value={evaluationsOptions.currentEvaluation.toString()}
                        handleChange={(v) => {setEvaluationsOptions({
                            ...evaluationsOptions,
                            currentEvaluation: parseInt(v),
                        })}}
                        options={evaluationsSelectOptions}
                    />}

                        {type === 'institute' && institutes.length >1 && (
                            <MakeCustomRadioSelect
                                placeholder={"Παρακαλώ επιλέξτε"}
                                theme={"search-listbox"}
                                disabled={institutes.length <= 1}
                                handleChange={(v) => setInstituteOptions({
                                    ...instituteOptions,
                                    currentPage: 1,
                                    currentInstitute: parseInt(v),
                                })}
                                value={instituteOptions.currentInstitute.toString()}
                                options={instituteSelectOptions}
                            />
                        )}

                    </SearchBar>
                </div>
                {type === 'institute' && currentEvaluationType == 'full' && (
                    <>
                        <div className="col-auto">
                            <a href={institute?.report || ""} download>
                                <CreateButton>
                                    <DownloadIcon />
                                    <p>INSTITUTE REPORT</p>
                                </CreateButton>
                            </a>
                        </div>
                        <div className="col-auto">
                            <a href={institute?.evaluation_report || ""} download>
                                <CreateButton>
                                    <DownloadIcon />
                                    <p>EVALUATION REPORT</p>
                                </CreateButton>
                            </a>
                        </div>
                    </>
                )}
                {type === 'rc' && (
                    <>
                        <div className="col-auto">
                            {/*@ts-ignore*/}
                            {institutesReports["kpi-report"]?.length > 0 && (
                                // @ts-ignore
                                <a href={institutesReports["kpi-report"]?.[0] || ""} download>
                                    <CreateButton>
                                        <DownloadIcon />
                                        <p>KPI REPORT</p>
                                    </CreateButton>
                                </a>
                            )}
                        </div>

                        <div className="col-auto">
                            {/*@ts-ignore*/}
                            {institutesReports["organisation-report"]?.length > 0 && (
                                // @ts-ignore
                                <a href={institutesReports["organisation-report"]?.[0] || ""} download>
                                    <CreateButton>
                                        <DownloadIcon />
                                        <p>ORGANIZATION REPORT</p>
                                    </CreateButton>
                                </a>
                            )}
                        </div>

                        <div className="col-auto">
                            {/*@ts-ignore*/}
                            {institutesReports["evaluation-report"]?.length > 0 && (
                                // @ts-ignore
                                <a href={institutesReports["evaluation-report"]?.[0] || ""} download>
                                    <CreateButton>
                                        <DownloadIcon />
                                        <p>EVALUATION REPORT</p>
                                    </CreateButton>
                                </a>
                            )}
                        </div>
                    </>
                )}
            </div>
            {type === 'institute' && (
                <div className={'group-list-container mt-5'}>
                    <ReportsList reports={currentGroups} />
                    {institutes.length > 0 && filteredGroups.length > 10 && (
                        <Pagination
                            theme={'dua-list'}
                            currentPage={instituteOptions.currentPage}
                            totalPages={Math.ceil(filteredGroups.length / instituteOptions.pageSize)}
                            setPage={(page) => setInstituteOptions({
                                ...instituteOptions,
                                currentPage: page,
                            })}
                        />
                    )}
                </div>
            )}
            {type === 'rc' && (
                <div className={'d-flex justify-content-center align-items-center h-50'}>
                    <p className={'text-center'}>Στην αξιολόγηση Ερευνητικού Κέντρου είναι διαθέσιμα<br/><b>μόνο τα Reports</b> που αφορούν το ίδιο το κέντρο.</p>
                </div>
            )}
        </div>
    );
};

export default RiviewReports;
