'use client';
/**
 * This Source Code is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * Copyright (c) Infonomic Company Limited
 */
/**
 * Role details drawer form.
 *
 * Mirrors the admin-users update pattern: TanStack Form + Zod, blur-then-
 * change validation, diff-against-original patch, optimistic concurrency
 * via `vid`. `machine_name` is read-only here — it is captured at create
 * time and immutable thereafter.
 */
import { useMemo, useState } from 'react';
import { revalidateLogic, useForm } from '@tanstack/react-form-start';
import { useTranslation } from '@byline/i18n/react';
import { Alert, Button, Input, LoaderEllipsis, TextArea } from '@byline/ui/react';
import cx from 'clsx';
import { z } from 'zod';
import { useBylineAdminServices } from '../../../services/admin-services-context.js';
import styles from './update.module.css';
const MAX_NAME = 128;
const MAX_DESCRIPTION = 2000;
function defaultsFrom(role) {
    return {
        name: role.name,
        description: role.description ?? '',
    };
}
/** Build a patch object containing only fields whose values differ from the original role. */
function buildPatch(values, role) {
    const patch = {};
    const normaliseText = (value) => (value.trim().length > 0 ? value : null);
    const nextDescription = normaliseText(values.description);
    const nextName = values.name.trim();
    if (nextName !== role.name)
        patch.name = nextName;
    if (nextDescription !== role.description)
        patch.description = nextDescription;
    return patch;
}
export function UpdateRole({ role, onClose, onSuccess }) {
    const { updateAdminRole } = useBylineAdminServices();
    const { t } = useTranslation('byline-admin');
    const [formError, setFormError] = useState(null);
    const [successMessage, setSuccessMessage] = useState(null);
    const updateRoleSchema = useMemo(() => z.object({
        name: z
            .string()
            .min(1, t('adminRoles.create.errors.nameRequired'))
            .max(MAX_NAME, t('adminRoles.create.errors.nameTooLong', { max: MAX_NAME })),
        description: z
            .string()
            .max(MAX_DESCRIPTION, t('adminRoles.create.errors.descriptionTooLong', { max: MAX_DESCRIPTION })),
    }), [t]);
    const form = useForm({
        defaultValues: defaultsFrom(role),
        validationLogic: revalidateLogic({
            mode: 'blur',
            modeAfterSubmission: 'change',
        }),
        validators: {
            onDynamic: updateRoleSchema,
        },
        onSubmit: async ({ value }) => {
            setFormError(null);
            setSuccessMessage(null);
            const patch = buildPatch(value, role);
            if (Object.keys(patch).length === 0) {
                setSuccessMessage(t('common.feedback.noChanges'));
                return;
            }
            try {
                const updated = await updateAdminRole({
                    data: { id: role.id, vid: role.vid, patch },
                });
                setSuccessMessage(t('common.feedback.saved'));
                onSuccess?.(updated);
            }
            catch (err) {
                const code = getErrorCode(err);
                if (code === 'admin.roles.versionConflict') {
                    setFormError(t('adminRoles.update.errors.versionConflict'));
                    return;
                }
                if (code === 'admin.roles.notFound') {
                    setFormError(t('adminRoles.update.errors.notFound'));
                    return;
                }
                setFormError(t('common.errors.couldNotSave'));
            }
        },
    });
    return (<div className={cx('byline-role-update-wrap', styles.wrap)}>
      <form method="post" noValidate onSubmit={(event) => {
            event.preventDefault();
            event.stopPropagation();
            void form.handleSubmit();
        }} className={cx('byline-role-update-form', styles.form)}>
        {formError ? <Alert intent="danger">{formError}</Alert> : null}
        {successMessage ? <Alert intent="success">{successMessage}</Alert> : null}

        <form.Field name="name">
          {(field) => (<Input label={t('adminRoles.fields.name')} id="role-name" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.currentTarget.value)} error={field.state.meta.errors.length > 0} errorText={firstError(field.state.meta.errors)} required/>)}
        </form.Field>

        <Input label={t('adminRoles.fields.machineName')} id="role-machine-name" name="machine_name" value={role.machine_name} readOnly disabled helpText={t('adminRoles.update.fields.machineNameHelp')}/>

        <form.Field name="description">
          {(field) => (<TextArea label={t('adminRoles.fields.description')} id="role-description" name={field.name} value={field.state.value} onBlur={field.handleBlur} onChange={(e) => field.handleChange(e.currentTarget.value)} error={field.state.meta.errors.length > 0} errorText={firstError(field.state.meta.errors)} rows={3}/>)}
        </form.Field>

        <div className={cx('byline-role-update-actions', styles.actions)}>
          <Button type="button" intent="secondary" size="sm" onClick={onClose} className={cx('byline-role-update-action', styles.action)}>
            {successMessage ? t('common.actions.close') : t('common.actions.cancel')}
          </Button>
          <form.Subscribe selector={(state) => ({
            canSubmit: state.canSubmit,
            isSubmitting: state.isSubmitting,
        })}>
            {({ canSubmit, isSubmitting }) => (<Button size="sm" intent="primary" type="submit" disabled={!canSubmit || isSubmitting} className={cx('byline-role-update-action', styles.action)}>
                {isSubmitting === true ? <LoaderEllipsis size={42}/> : t('common.actions.save')}
              </Button>)}
          </form.Subscribe>
        </div>
      </form>
    </div>);
}
function firstError(errors) {
    for (const err of errors) {
        if (typeof err === 'string')
            return err;
        if (err && typeof err === 'object' && 'message' in err) {
            const msg = err.message;
            if (typeof msg === 'string')
                return msg;
        }
    }
    return undefined;
}
function getErrorCode(err) {
    return typeof err?.code === 'string'
        ? err.code
        : null;
}
