import React from 'react';
import { ASSISTANT_BRAND_NAME } from '../../../constants';
import {
  usePluginSettings,
  usePluginSettingsError,
  usePluginSettingsSaving,
  useUpdatePluginSettings,
} from '../../../contexts/PluginSettingsContext';
import { ToggleRow } from '../../ui';

const AssistantSettingsSection: React.FC = () => {
  const pluginSettings = usePluginSettings();
  const updatePluginSettings = useUpdatePluginSettings();
  const pluginSettingsError = usePluginSettingsError();
  const isSavingPluginSettings = usePluginSettingsSaving();

  const setPluginFlag = async (patch: Partial<typeof pluginSettings>) => {
    try {
      await updatePluginSettings(patch);
    } catch {
      // The context exposes the message for rendering.
    }
  };

  return (
    <div className="space-y-2.5">
      <ToggleRow
        label="Allow WordPress to send requests to ActionPanel AI"
        description={`Allows chat, site context sharing, and ${ASSISTANT_BRAND_NAME} workflows.`}
        checked={pluginSettings.allowActionPanelAiRequests}
        disabled={isSavingPluginSettings}
        onChange={(checked) => setPluginFlag({ allowActionPanelAiRequests: checked })}
      />
      <ToggleRow
        label="Allow log reads"
        description={`Lets ${ASSISTANT_BRAND_NAME} read sanitized excerpts from the configured WordPress debug log.`}
        checked={pluginSettings.allowLogReads}
        disabled={isSavingPluginSettings}
        onChange={(checked) => setPluginFlag({ allowLogReads: checked })}
      />
      <ToggleRow
        label="Allow write operations"
        description={`Lets ${ASSISTANT_BRAND_NAME} propose content and site changes. Publishing/live updates still require approval.`}
        checked={pluginSettings.allowWriteOperations}
        disabled={isSavingPluginSettings}
        onChange={(checked) => setPluginFlag({ allowWriteOperations: checked })}
      />
      <ToggleRow
        label="Automatically approve safe write operations"
        description="Allows proven draft-only writes to run without an extra approval prompt."
        checked={pluginSettings.autoApproveSafeWriteOperations}
        disabled={!pluginSettings.allowWriteOperations || isSavingPluginSettings}
        onChange={(checked) => setPluginFlag({ autoApproveSafeWriteOperations: checked })}
      />
      <ToggleRow
        label="Require approval for reads"
        description={`Shows a preview before site data is shared with ${ASSISTANT_BRAND_NAME}.`}
        checked={pluginSettings.requireReadApproval}
        disabled={isSavingPluginSettings}
        onChange={(checked) => setPluginFlag({ requireReadApproval: checked })}
      />
      {pluginSettingsError && (
        <p className="px-1 pt-1 text-sm text-danger-text">{pluginSettingsError}</p>
      )}
    </div>
  );
};

export default AssistantSettingsSection;
