import * as React from 'react';
import { Link } from 'react-router-dom';
import { Subscription } from 'rxjs';
import { FilteredConnection } from '../components/FilteredConnection';
import { PageTitle } from '../components/PageTitle';
import { SingleValueCard } from '../components/SingleValueCard';
import { TabsWithLocalStorageViewStatePersistence } from '../components/Tabs';
import { Timestamp } from '../components/time/Timestamp';
import { fetchAllSurveyResponses, fetchAllUsersWithSurveyResponses, fetchSurveyResponseAggregates, } from '../marketing/backend';
import { eventLogger } from '../tracking/eventLogger';
import { userURL } from '../user';
import { USER_ACTIVITY_FILTERS } from './SiteAdminAnalyticsPage';
function scoreToClassSuffix(score) {
    return score > 8 ? 'success' : score > 6 ? 'info' : 'danger';
}
const ScoreBadge = props => (React.createElement("div", { className: `ml-4 badge badge-pill badge-${scoreToClassSuffix(props.score)}`, "data-tooltip": `${props.score} out of 10` },
    "Score: ",
    props.score));
class SurveyResponseNode extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = {
            loading: false,
        };
    }
    render() {
        return (React.createElement("li", { className: "list-group-item py-2" },
            React.createElement("div", { className: "d-flex align-items-center justify-content-between" },
                React.createElement("div", null,
                    React.createElement("strong", null, this.props.node.user ? (React.createElement(Link, { to: userURL(this.props.node.user.username) }, this.props.node.user.username)) : this.props.node.email ? (this.props.node.email) : ('anonymous user')),
                    React.createElement(ScoreBadge, { score: this.props.node.score })),
                React.createElement("div", null,
                    React.createElement(Timestamp, { date: this.props.node.createdAt }))),
            (this.props.node.reason || this.props.node.better) && (React.createElement("dl", { className: "mt-3" },
                this.props.node.reason &&
                    this.props.node.reason !== '' && (React.createElement(React.Fragment, null,
                    React.createElement("dt", null, "What is the most important reason for the score you gave Sourcegraph?"),
                    React.createElement("dd", null, this.props.node.reason))),
                this.props.node.reason && this.props.node.better && React.createElement("div", { className: "mt-2" }),
                this.props.node.better &&
                    this.props.node.better !== '' && (React.createElement(React.Fragment, null,
                    React.createElement("dt", null, "What could Sourcegraph do to provide a better product?"),
                    React.createElement("dd", null, this.props.node.better)))))));
    }
}
const UserSurveyResponsesHeader = () => (React.createElement("thead", null,
    React.createElement("tr", null,
        React.createElement("th", null, "User"),
        React.createElement("th", null, "Last active on Sourcegraph"),
        React.createElement("th", null, "Latest survey response"),
        React.createElement("th", null))));
class UserSurveyResponseNode extends React.PureComponent {
    constructor() {
        super(...arguments);
        this.state = {
            loading: false,
            displayAll: false,
        };
        this.showMoreClicked = () => this.setState(state => ({ displayAll: !state.displayAll }));
    }
    render() {
        const responses = this.props.node.surveyResponses;
        return (React.createElement(React.Fragment, null,
            React.createElement("tr", null,
                React.createElement("td", null,
                    React.createElement("strong", null,
                        React.createElement(Link, { to: userURL(this.props.node.username) }, this.props.node.username))),
                React.createElement("td", null, this.props.node.activity && this.props.node.activity.lastActiveTime ? (React.createElement(Timestamp, { date: this.props.node.activity.lastActiveTime })) : ('?')),
                React.createElement("td", null, responses && responses.length > 0 ? (React.createElement(React.Fragment, null,
                    React.createElement(Timestamp, { date: responses[0].createdAt }),
                    React.createElement(ScoreBadge, { score: responses[0].score }))) : (React.createElement(React.Fragment, null, "No responses"))),
                React.createElement("td", null, responses.length > 0 && (React.createElement("button", { className: "btn btn-sm btn-secondary", onClick: this.showMoreClicked }, this.state.displayAll ? 'Hide' : 'See all')))),
            this.state.displayAll && (React.createElement("tr", null,
                React.createElement("td", { colSpan: 4 }, responses.map((response, i) => (React.createElement("dl", { key: i },
                    React.createElement("div", { className: "pl-3 border-left site-admin-survey-responses-connection__wide-border" },
                        React.createElement(Timestamp, { date: response.createdAt }),
                        React.createElement(ScoreBadge, { score: response.score }),
                        React.createElement("br", null),
                        (response.reason || response.better) && React.createElement("div", { className: "mt-2" }),
                        response.reason &&
                            response.reason !== '' && (React.createElement(React.Fragment, null,
                            React.createElement("dt", null, "What is the most important reason for the score you gave Sourcegraph?"),
                            React.createElement("dd", null, response.reason))),
                        response.reason && response.better && React.createElement("div", { className: "mt-2" }),
                        response.better &&
                            response.better !== '' && (React.createElement(React.Fragment, null,
                            React.createElement("dt", null, "What could Sourcegraph do to provide a better product?"),
                            React.createElement("dd", null, response.better))))))))))));
    }
}
class SiteAdminSurveyResponsesSummary extends React.PureComponent {
    constructor(props) {
        super(props);
        this.subscriptions = new Subscription();
        this.state = {};
        this.subscriptions.add(fetchSurveyResponseAggregates().subscribe(summary => this.setState({ summary })));
    }
    componentWillUnmount() {
        this.subscriptions.unsubscribe();
    }
    render() {
        if (!this.state.summary) {
            return null;
        }
        const anyResults = this.state.summary.last30DaysCount > 0;
        let npsText = `${this.state.summary.netPromoterScore}`;
        if (this.state.summary.netPromoterScore > 0) {
            npsText = `+${npsText}`;
        }
        else if (this.state.summary.netPromoterScore < 0) {
            npsText = `-${npsText}`;
        }
        const npsClass = this.state.summary.netPromoterScore > 0
            ? 'text-success'
            : this.state.summary.netPromoterScore < 0
                ? 'text-danger'
                : 'text-info';
        const roundAvg = Math.round(this.state.summary.averageScore * 10) / 10;
        return (React.createElement("div", { className: "msite-admin-survey-responses-summary mb-2" },
            React.createElement("h3", null, "Summary"),
            React.createElement("div", { className: "site-admin-survey-responses-summary__container" },
                React.createElement(SingleValueCard, { className: "site-admin-survey-responses-summary__item", value: this.state.summary.last30DaysCount, title: "Number of submissions", subTitle: "Last 30 days" }),
                React.createElement(SingleValueCard, { className: "site-admin-survey-responses-summary__item", value: anyResults ? roundAvg : '-', title: "Average score", subTitle: "Last 30 days", valueTooltip: `${roundAvg} out of 10`, valueClassName: anyResults ? `text-${scoreToClassSuffix(roundAvg)}` : '' }),
                React.createElement(SingleValueCard, { className: "site-admin-survey-responses-summary__item", value: anyResults ? npsText : '-', title: "Net promoter score", subTitle: "Last 30 days", valueTooltip: `${npsText} (between -100 and +100)`, valueClassName: anyResults ? npsClass : '' }))));
    }
}
class FilteredSurveyResponseConnection extends FilteredConnection {
}
class FilteredUserSurveyResponseConnection extends FilteredConnection {
}
/**
 * A page displaying the survey responses on this site.
 */
export class SiteAdminSurveyResponsesPage extends React.Component {
    constructor() {
        super(...arguments);
        this.state = { tab: 'chronological' };
        this.tabSelected = (tab) => this.setState({ tab });
    }
    componentDidMount() {
        eventLogger.logViewEvent('SiteAdminSurveyResponses');
    }
    render() {
        return (React.createElement("div", { className: "site-admin-survey-responses-page" },
            React.createElement(PageTitle, { title: "Survey Responses - Admin" }),
            React.createElement("h2", null, "Survey responses"),
            React.createElement("p", null, "After using Sourcegraph for a few days, users are presented with a request to answer \"How likely is it that you would recommend Sourcegraph to a friend?\" on a scale from 0\u201310 and to provide some feedback. Responses are visible below (and are also sent to Sourcegraph)."),
            React.createElement(SiteAdminSurveyResponsesSummary, null),
            React.createElement("h3", null, "Responses"),
            React.createElement(TabsWithLocalStorageViewStatePersistence, { tabs: SiteAdminSurveyResponsesPage.TABS, storageKey: SiteAdminSurveyResponsesPage.LAST_TAB_STORAGE_KEY, tabClassName: "tab-bar__tab--h5like", onSelectTab: this.tabSelected },
                React.createElement(FilteredSurveyResponseConnection, { key: "chronological", className: "list-group list-group-flush", hideSearch: true, noun: "survey response", pluralNoun: "survey responses", queryConnection: fetchAllSurveyResponses, nodeComponent: SurveyResponseNode, history: this.props.history, location: this.props.location }),
                React.createElement(FilteredUserSurveyResponseConnection, { key: "by-user", listComponent: "table", headComponent: UserSurveyResponsesHeader, className: "table mt-2 site-admin-survey-responses-connection", hideSearch: false, filters: USER_ACTIVITY_FILTERS, noun: "user", pluralNoun: "users", queryConnection: fetchAllUsersWithSurveyResponses, nodeComponent: UserSurveyResponseNode, history: this.props.history, location: this.props.location }))));
    }
}
SiteAdminSurveyResponsesPage.TABS = [
    { id: 'chronological', label: 'Chronological feed' },
    { id: 'by-user', label: 'Sort by user' },
];
SiteAdminSurveyResponsesPage.LAST_TAB_STORAGE_KEY = 'site-admin-survey-responses-last-tab';
//# sourceMappingURL=SiteAdminSurveyResponsesPage.js.map