import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
import React from 'react';
import ZodSchemaForm, { lightTheme, darkTheme } from 'zod-schema-form';
import { useModelContext } from '../contexts/ModelContext';
import { getProviderDefinition, getProviderDisplayName } from '../config/modelProviders';
import { useTheme, useThemeName } from '../theme';
import { useCredentialSync } from '../contexts/CredentialContext';
const DEFAULT_VIEW_FIELDS = [
    {
        label: 'Model',
        render: (model) => model.model || 'Not set'
    },
    {
        label: 'Description',
        render: (model) => model.description || '—'
    },
    {
        label: 'Connection',
        render: (model) => {
            const entries = Object.entries(model.connection ?? {});
            if (entries.length === 0) {
                return 'No connection details configured';
            }
            return `${entries.length} ${entries.length === 1 ? 'field' : 'fields'} configured`;
        }
    }
];
const buildBadgeClassName = (defaultClassName, overrideClassName) => {
    return overrideClassName ? `${defaultClassName} ${overrideClassName}` : defaultClassName;
};
export const ModelConfigCard = ({ modelId, onDelete, isDefault, onMakeDefault }) => {
    const theme = useTheme();
    const themeName = useThemeName();
    const { getModel, updateModel, removeModel, models } = useModelContext();
    const [isEditing, setIsEditing] = React.useState(false);
    const model = getModel(modelId);
    const { submitCredentials, status: credentialStatus, isLoadingInitialCredentials } = useCredentialSync(model?.provider);
    const [isSaving, setIsSaving] = React.useState(false);
    const [submissionError, setSubmissionError] = React.useState(null);
    const credentialState = credentialStatus.status;
    const isPending = isSaving || credentialState === 'pending' || isLoadingInitialCredentials;
    const remoteErrorMessage = credentialState === 'error'
        ? credentialStatus.error instanceof Error
            ? credentialStatus.error.message
            : 'Failed to persist credentials'
        : null;
    const errorMessage = submissionError ?? remoteErrorMessage;
    const successMessage = credentialState === 'success' && !isPending ? 'Credentials saved.' : null;
    if (!model) {
        return (_jsxs("div", { className: 'text-sm text-red-600', children: ["Model not found: ", modelId] }));
    }
    const providerDefinition = getProviderDefinition(model.provider);
    const providerName = getProviderDisplayName(model.provider);
    const viewFields = providerDefinition?.viewFields?.length
        ? providerDefinition.viewFields
        : DEFAULT_VIEW_FIELDS;
    const badgeClassName = buildBadgeClassName(theme.modelConfigCard.badge, providerDefinition?.badgeClassName);
    const canEdit = Boolean(providerDefinition?.form?.schema?.length);
    const handleDelete = React.useCallback(async () => {
        if (!model) {
            return;
        }
        setSubmissionError(null);
        const remainingModels = models.filter((entry) => entry.id !== modelId);
        try {
            await submitCredentials({
                action: 'delete',
                providerId: model.provider,
                modelId,
                model: null,
                allModels: remainingModels
            });
            removeModel(modelId);
            setSubmissionError(null);
            setIsEditing(false);
            onDelete?.(modelId);
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Failed to delete model credentials';
            setSubmissionError(message);
        }
    }, [model, models, modelId, submitCredentials, removeModel, onDelete]);
    const handleFormSubmit = React.useCallback(async (data) => {
        if (!providerDefinition || !model) {
            return;
        }
        if (isSaving) {
            return;
        }
        const updates = providerDefinition.form.transformSubmit(data, model);
        const nextModel = {
            ...model,
            ...updates,
            id: model.id
        };
        const nextModels = models.map((entry) => (entry.id === modelId ? nextModel : entry));
        setSubmissionError(null);
        setIsSaving(true);
        try {
            await submitCredentials({
                action: 'upsert',
                providerId: nextModel.provider,
                modelId,
                model: nextModel,
                allModels: nextModels
            });
            updateModel(modelId, updates);
            setIsEditing(false);
        }
        catch (error) {
            const message = error instanceof Error ? error.message : 'Failed to save model credentials';
            setSubmissionError(message);
        }
        finally {
            setIsSaving(false);
        }
    }, [providerDefinition, model, isSaving, models, submitCredentials, modelId, updateModel]);
    const renderViewMode = () => (_jsxs("div", { className: theme.modelConfigCard.container, children: [_jsxs("div", { className: theme.modelConfigCard.header, children: [_jsxs("div", { className: 'min-w-[12rem] flex-1', children: [_jsxs("div", { className: theme.modelConfigCard.pillGroup, children: [_jsx("h3", { className: theme.modelConfigCard.title, children: model.label }), _jsx("span", { className: badgeClassName, children: providerName }), isDefault && (_jsx("span", { className: theme.modelConfigCard.defaultBadge, children: "Current model" })), model.disabled && (_jsx("span", { className: theme.modelConfigCard.disabledBadge, children: "Disabled" }))] }), model.description && (_jsx("p", { className: theme.modelConfigCard.description, children: model.description }))] }), _jsxs("div", { className: theme.modelConfigCard.actions, children: [!isDefault && (_jsx("button", { type: 'button', onClick: onMakeDefault, className: theme.modelConfigCard.setDefaultButton, children: "Set as current" })), canEdit && (_jsx("button", { type: 'button', onClick: () => setIsEditing(true), className: theme.modelConfigCard.editButton, disabled: isPending, children: "Edit" }))] })] }), _jsx("div", { className: theme.modelConfigCard.statsGrid, children: viewFields.map((field) => (_jsxs("div", { children: [_jsx("dt", { className: theme.modelConfigCard.statLabel, children: field.label }), _jsx("dd", { className: theme.modelConfigCard.statValue, children: field.render(model) })] }, field.label))) }), _jsxs("div", { className: theme.modelConfigCard.divider, children: [_jsx("button", { type: 'button', onClick: () => { void handleDelete(); }, className: theme.modelConfigCard.deleteButton, disabled: isPending, children: "Delete Model" }), errorMessage && (_jsx("p", { className: 'mt-2 text-xs text-red-500', children: errorMessage })), !errorMessage && successMessage && (_jsx("p", { className: 'mt-2 text-xs text-emerald-600', children: successMessage }))] })] }));
    const renderEditMode = () => {
        if (!providerDefinition) {
            return renderViewMode();
        }
        const { schema, getInitialValues, submitButtonText, size } = providerDefinition.form;
        return (_jsxs("div", { className: theme.modelConfigCard.container, children: [_jsxs("div", { className: theme.modelConfigCard.header, children: [_jsxs("div", { className: theme.modelConfigCard.pillGroup, children: [_jsxs("h3", { className: theme.modelConfigCard.editTitle, children: ["Edit ", providerName, " Model"] }), isDefault && (_jsx("span", { className: theme.modelConfigCard.defaultBadge, children: "Current model" }))] }), _jsxs("div", { className: theme.modelConfigCard.actions, children: [!isDefault && (_jsx("button", { type: 'button', onClick: onMakeDefault, className: theme.modelConfigCard.setDefaultButton, disabled: isPending, children: "Set as current" })), _jsx("button", { type: 'button', onClick: () => setIsEditing(false), className: theme.modelConfigCard.cancelButton, disabled: isPending, children: "Cancel" })] })] }), _jsx("fieldset", { disabled: isPending, className: 'contents', children: _jsx(ZodSchemaForm, { schema: schema, initialValues: getInitialValues(model), onSubmit: handleFormSubmit, submitButtonText: isPending ? 'Saving…' : (submitButtonText ?? 'Update Model'), size: size ?? 'small', theme: themeName === 'dark' ? darkTheme : lightTheme }) }), errorMessage && (_jsx("p", { className: 'mt-3 text-xs text-red-500', children: errorMessage })), !errorMessage && successMessage && (_jsx("p", { className: 'mt-3 text-xs text-emerald-600', children: successMessage })), _jsx("div", { className: theme.modelConfigCard.divider, children: _jsx("button", { type: 'button', onClick: () => { void handleDelete(); }, className: theme.modelConfigCard.deleteButton, disabled: isPending, children: "Delete Model" }) })] }));
    };
    return isEditing ? renderEditMode() : renderViewMode();
};
export default ModelConfigCard;
