import React from "react";
import bytes from "bytes";
import parseISO from "date-fns/parseISO";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
import { Link } from "react-router-dom";
import { Tooltip } from "../tooltip/Tooltip";
import { Icon } from "../icon/Icon";
import activityPulseIcon from "../assets/activity-icon.png";
/**
 * Return an equivalent to moment(date).format('L') without moment
 * @param {*} dateObject
 */
export const formatDate = (dateObject) => new Date(dateObject).toISOString().split("T")[0];
export const SearchResultItem = ({ node, profile, datasetTypeSelected, hasEditPermissions, }) => {
    const isAdmin = profile?.admin;
    const hasEdit = hasEditPermissions(node.permissions, profile?.sub) || isAdmin;
    const heading = node.latestSnapshot.description?.Name;
    const summary = node.latestSnapshot?.summary;
    const datasetId = node.id;
    const numSessions = summary?.sessions.length > 0 ? summary.sessions.length : 1;
    const numSubjects = summary?.subjects.length > 0 ? summary.subjects.length : 1;
    const accessionNumber = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null, "Openneuro Accession Number:"),
        React.createElement("span", null, node.id)));
    const sessions = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null, "Sessions:"),
        React.createElement("span", null, numSessions.toLocaleString())));
    const ages = (value) => {
        if (value) {
            const ages = value.filter((x) => x);
            if (ages.length === 0)
                return "N/A";
            else if (ages.length === 1)
                return ages[0];
            else
                return `${Math.min(...ages)} - ${Math.max(...ages)}`;
        }
        else
            return "N/A";
    };
    const agesRange = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null,
            node?.metadata?.ages?.length === 1
                ? "Participant's Age"
                : "Participants' Ages",
            ":",
            " "),
        React.createElement("span", null, ages(summary?.subjectMetadata?.map((subject) => subject.age)))));
    const subjects = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null, "Participants:"),
        React.createElement("span", null, numSubjects.toLocaleString())));
    const size = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null, "Size:"),
        React.createElement("span", null, bytes(node?.latestSnapshot?.size) || "unknown")));
    const files = (React.createElement("span", { className: "result-summary-meta" },
        React.createElement("strong", null, "Files:"),
        React.createElement("span", null, summary?.totalFiles.toLocaleString())));
    const dateAdded = formatDate(node.created);
    const dateAddedDifference = formatDistanceToNow(parseISO(node.created));
    let lastUpdatedDate;
    if (node.snapshots.length) {
        const dateUpdated = formatDate(node.snapshots[node.snapshots.length - 1].created);
        const dateUpdatedDifference = formatDistanceToNow(parseISO(node.snapshots[node.snapshots.length - 1].created));
        lastUpdatedDate = (React.createElement(React.Fragment, null,
            React.createElement("span", { className: "updated-divider" }, "|"),
            React.createElement("div", { className: "updated-date" },
                React.createElement("span", null, "Updated:"),
                dateUpdated,
                " - ",
                dateUpdatedDifference,
                " ago")));
    }
    const uploader = (React.createElement("div", { className: "uploader" },
        React.createElement("span", null, "Uploaded by:"),
        node.uploader.name,
        " on ",
        dateAdded,
        " - ",
        dateAddedDifference,
        " ago"));
    const downloads = node.analytics.downloads
        ? node.analytics.downloads.toLocaleString() + " Downloads \n"
        : "";
    const views = node.analytics.views
        ? node.analytics.views.toLocaleString() + " Views \n"
        : "";
    const following = node.followers.length
        ? node.followers.length.toLocaleString() + " Follower \n"
        : "";
    const stars = node.stars.length
        ? node.stars.length.toLocaleString() + " Bookmarked"
        : "";
    const activtyTooltip = downloads + views + following + stars;
    const activityIcon = (React.createElement(Tooltip, { tooltip: activtyTooltip, flow: "up", className: "result-icon result-activity-icon" },
        React.createElement(Icon, { imgSrc: activityPulseIcon, iconSize: "22px", label: "activity", iconOnly: true })));
    const sharedWithIcon = (React.createElement(Tooltip, { tooltip: "Shared with me", flow: "up", className: "result-icon result-shared-icon" },
        React.createElement(Icon, { icon: "fas fa-user", color: "rgb(119,191,217)", iconSize: "16px", label: "Shared With", iconOnly: true })));
    const publicIcon = (React.createElement(Tooltip, { tooltip: "Visible to all viewers", flow: "up", className: "result-icon result-publlic-icon" },
        React.createElement(Icon, { icon: "fas fa-globe", color: "rgb(116,181,105)", iconSize: "16px", label: "Public", iconOnly: true })));
    const errorsIcon = hasEdit && (React.createElement(Tooltip, { tooltip: "Invalid", flow: "up", className: "result-icon result-errors-icon" },
        React.createElement(Icon, { icon: "fas fa-exclamation-circle", color: "rgb(202,97,86)", iconSize: "16px", label: "Invalid", iconOnly: true })));
    const _list = (type, items) => {
        if (items && items.length > 0) {
            return (React.createElement(React.Fragment, null,
                React.createElement("strong", null,
                    type,
                    ":"),
                React.createElement("div", null, items.map((item, index) => (React.createElement("span", { className: "list-item", key: index }, item))))));
        }
        else {
            return null;
        }
    };
    let invalid = false;
    // Legacy issues still flagged
    if (node.latestSnapshot.issues) {
        invalid = node.latestSnapshot.issues.some((issue) => issue.severity === "error");
    }
    else {
        // Test if there's any schema validator errors
        invalid = node.latestSnapshot.validation?.errors > 0;
    }
    const shared = !node.public && node.uploader.id !== profile.sub;
    const MyDatasetsPage = datasetTypeSelected === "My Datasets";
    const datasetPerms = node.permissions.userPermissions.map((item) => {
        if (item.user.id === profile?.sub && item.access !== null) {
            if (item.access === "ro") {
                return "Read Only";
            }
            else if (item.access === "rw") {
                return "Edit";
            }
            else {
                return "Admin";
            }
        }
        else {
            return null;
        }
    });
    const datasetOwenerIcons = (React.createElement("div", { className: "owner-icon-wrap" },
        node.public ? publicIcon : null,
        shared ? sharedWithIcon : null,
        invalid ? errorsIcon : null));
    const modalityList = summary?.modalities.length
        ? (React.createElement("div", { className: "modality-list" }, _list(React.createElement(React.Fragment, null, summary?.modalities.length === 1 ? "Modality" : "Modalities"), summary?.modalities)))
        : null;
    const taskList = summary?.tasks.length
        ? React.createElement("div", { className: "task-list" }, _list(React.createElement(React.Fragment, null, "Tasks"), summary?.tasks))
        : null;
    const tracers = summary?.pet?.TracerName?.length
        ? (React.createElement("div", { className: "tracers-list" }, _list(React.createElement(React.Fragment, null, summary?.pet?.TracerName.length === 1
            ? "Radiotracer"
            : "Radiotracers"), summary?.pet?.TracerName)))
        : null;
    return (React.createElement(React.Fragment, null,
        React.createElement("div", { className: "grid grid-nogutter search-result" },
            React.createElement("div", { className: "col col-9" },
                React.createElement("h3", null,
                    React.createElement(Link, { to: "/datasets/" + datasetId }, heading)),
                React.createElement("div", { className: "result-upload-info" },
                    uploader,
                    lastUpdatedDate)),
            React.createElement("div", { className: "col col-3 col-sm" },
                MyDatasetsPage && (React.createElement("div", { className: "dataset-permissions-tag" },
                    React.createElement("small", null,
                        "Access: ",
                        datasetPerms))),
                React.createElement("div", { className: "result-icon-wrap" },
                    datasetOwenerIcons,
                    activityIcon)),
            React.createElement("div", { className: "col col-12 result-meta-body" },
                modalityList,
                taskList,
                tracers),
            React.createElement("div", { className: "result-meta-footer" },
                accessionNumber,
                sessions,
                subjects,
                agesRange,
                size,
                files))));
};
