import {Link, useParams} from 'react-router-dom';
import {useCachedData, useData, useDataPage} from '../API/common';
import { Institution, Profession, Specialty } from '../types/survey';
import ReactMarkdown from 'react-markdown';
import { LoadingData } from '../components/LoadingData';
import { LoadingList } from '../components/LoadingList';



export function ProfessionPage() {
    const { professionId } = useParams<{ professionId: string }>();
    const profession = useData<Profession>('surveys', 'professions', professionId || 0);
    const specialties = useDataPage<Specialty>('surveys', 'specialties', { profession: professionId || 0 }, !!profession);

    const institutions = useCachedData<Institution>("surveys", "institutions");

    return (
        <div>
            <LoadingData data={profession}>
                <h1>{profession?.name}</h1>
                <div className="description">
                    <ReactMarkdown>{profession?.description || ''}</ReactMarkdown>
                </div>
                <div className="specialties-block">
                    {specialties.items != null ? <h2>Где можно обучиться</h2>:null}
                    <LoadingList
                        data={specialties.items}
                        listElement={specialty => (
                            <SpecialtyBlock
                                key={specialty.id}
                                specialty={specialty as Specialty}
                                institution={institutions((specialty as Specialty).institution)}
                            />
                        )}
                    />
                </div>
            </LoadingData>
        </div>
    );
}

function SpecialtyBlock({
    specialty,
    institution,
}: {
    specialty: Specialty;
    institution: Institution | undefined | null;
}) {
    return (
        <div className="specialty-block">
            <h3>Учебное заведение: {institution?.name || 'Загрузка...'}</h3>
            <p className={"specialty-name"}>{specialty.name}</p>
            {specialty.link?<Link to={specialty.link} className={"site"}>Открыть сайт</Link>:null}

        </div>
    );
}