'use client';
import * as facelessUIImport from '@faceless-ui/modal';
import React, { useCallback, useState } from 'react';
import { toast } from 'react-toastify';
import { useForm } from '../../forms/Form/context.js';
import { useConfig } from '../../providers/Config/index.js';
import { useDocumentInfo } from '../../providers/DocumentInfo/index.js';
import { useLocale } from '../../providers/Locale/index.js';
import { useTranslation } from '../../providers/Translation/index.js';
import { MinimalTemplate } from '../../templates/Minimal/index.js';
import { requests } from '../../utilities/api.js';
import { Button } from '../Button/index.js';
const baseClass = 'status';
const Status = ()=>{
    const { Modal, useModal } = facelessUIImport;
    const { id, collectionSlug, docPermissions, getVersions, globalSlug, publishedDoc, unpublishedVersions } = useDocumentInfo();
    const { toggleModal } = useModal();
    const { routes: { api }, serverURL } = useConfig();
    const [processing, setProcessing] = useState(false);
    const { reset: resetForm } = useForm();
    const { code: locale } = useLocale();
    const { i18n, t } = useTranslation();
    const unPublishModalSlug = `confirm-un-publish-${id}`;
    const revertModalSlug = `confirm-revert-${id}`;
    let statusToRender;
    if (unpublishedVersions?.docs?.length > 0 && publishedDoc) {
        statusToRender = 'changed';
    } else if (!publishedDoc) {
        statusToRender = 'draft';
    } else if (publishedDoc && unpublishedVersions?.docs?.length <= 1) {
        statusToRender = 'published';
    }
    const performAction = useCallback(async (action)=>{
        let url;
        let method;
        let body;
        setProcessing(true);
        if (action === 'unpublish') {
            body = {
                _status: 'draft'
            };
        }
        if (action === 'revert') {
            body = publishedDoc;
        }
        if (collectionSlug) {
            url = `${serverURL}${api}/${collectionSlug}/${id}?locale=${locale}&fallback-locale=null`;
            method = 'patch';
        }
        if (globalSlug) {
            url = `${serverURL}${api}/globals/${globalSlug}?locale=${locale}&fallback-locale=null`;
            method = 'post';
        }
        const res = await requests[method](url, {
            body: JSON.stringify(body),
            headers: {
                'Accept-Language': i18n.language,
                'Content-Type': 'application/json'
            }
        });
        if (res.status === 200) {
            let data;
            const json = await res.json();
            if (globalSlug) {
                data = json.result;
            } else if (collectionSlug) {
                data = json.doc;
            }
            resetForm(data);
            toast.success(json.message);
            getVersions();
        } else {
            toast.error(t('error:unPublishingDocument'));
        }
        setProcessing(false);
        if (action === 'revert') {
            toggleModal(revertModalSlug);
        }
        if (action === 'unpublish') {
            toggleModal(unPublishModalSlug);
        }
    }, [
        api,
        collectionSlug,
        getVersions,
        globalSlug,
        i18n.language,
        id,
        locale,
        publishedDoc,
        resetForm,
        revertModalSlug,
        serverURL,
        t,
        toggleModal,
        unPublishModalSlug
    ]);
    const canUpdate = docPermissions?.update?.permission;
    if (statusToRender) {
        return /*#__PURE__*/ React.createElement("div", {
            className: baseClass,
            title: `${t('version:status')}: ${t(`version:${statusToRender}`)}`
        }, /*#__PURE__*/ React.createElement("div", {
            className: `${baseClass}__value-wrap`
        }, /*#__PURE__*/ React.createElement("span", {
            className: `${baseClass}__label`
        }, t('version:status'), ": "), /*#__PURE__*/ React.createElement("span", {
            className: `${baseClass}__value`
        }, t(`version:${statusToRender}`)), canUpdate && statusToRender === 'published' && /*#__PURE__*/ React.createElement(React.Fragment, null, " — ", /*#__PURE__*/ React.createElement(Button, {
            buttonStyle: "none",
            className: `${baseClass}__action`,
            onClick: ()=>toggleModal(unPublishModalSlug)
        }, t('version:unpublish')), /*#__PURE__*/ React.createElement(Modal, {
            className: `${baseClass}__modal`,
            slug: unPublishModalSlug
        }, /*#__PURE__*/ React.createElement(MinimalTemplate, {
            className: `${baseClass}__modal-template`
        }, /*#__PURE__*/ React.createElement("h1", null, t('version:confirmUnpublish')), /*#__PURE__*/ React.createElement("p", null, t('version:aboutToUnpublish')), /*#__PURE__*/ React.createElement(Button, {
            buttonStyle: "secondary",
            onClick: processing ? undefined : ()=>toggleModal(unPublishModalSlug),
            type: "button"
        }, t('general:cancel')), /*#__PURE__*/ React.createElement(Button, {
            onClick: processing ? undefined : ()=>performAction('unpublish')
        }, t(processing ? 'version:unpublishing' : 'general:confirm'))))), canUpdate && statusToRender === 'changed' && /*#__PURE__*/ React.createElement(React.Fragment, null, " — ", /*#__PURE__*/ React.createElement(Button, {
            buttonStyle: "none",
            className: `${baseClass}__action`,
            id: "action-revert-to-published",
            onClick: ()=>toggleModal(revertModalSlug)
        }, t('version:revertToPublished')), /*#__PURE__*/ React.createElement(Modal, {
            className: `${baseClass}__modal`,
            slug: revertModalSlug
        }, /*#__PURE__*/ React.createElement(MinimalTemplate, {
            className: `${baseClass}__modal-template`
        }, /*#__PURE__*/ React.createElement("h1", null, t('version:confirmRevertToSaved')), /*#__PURE__*/ React.createElement("p", null, t('version:aboutToRevertToPublished')), /*#__PURE__*/ React.createElement(Button, {
            buttonStyle: "secondary",
            onClick: processing ? undefined : ()=>toggleModal(revertModalSlug),
            type: "button"
        }, t('general:cancel')), /*#__PURE__*/ React.createElement(Button, {
            id: "action-revert-to-published-confirm",
            onClick: processing ? undefined : ()=>performAction('revert')
        }, t(processing ? 'version:reverting' : 'general:confirm')))))));
    }
    return null;
};
export default Status;

//# sourceMappingURL=index.js.map