// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: wp-content/plugins/automarketer-ai/assets/js/src/components/tabs/SettingsTab.tsx
// Last Edited: January 03, 2026
// Description: Nuclear-grade React Settings tab for AI group — side tab API Services with colored chips, single provider selection, Activate/Deactivate button, key/model input, test, toasts, ARIA live, WCAG 2.1 AA, modals with help links to account/API key guides — NUCLEAR+++
// ==================================================

import React, { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { __ } from '@wordpress/i18n';
import { Button, TextControl, Notice, Tooltip, Modal, ExternalLink } from '@wordpress/components';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css'; // Assumed SCSS override for WCAG

interface FormData {
  apiKey: string;
  model: string;
}

const SettingsTab: React.FC = () => {
  const [selectedProvider, setSelectedProvider] = useState<string>('grok');
  const [availableProviders, setAvailableProviders] = useState<string[]>(['grok']);
  const [models, setModels] = useState<string[]>([]);
  const [lastTest, setLastTest] = useState<number>(0);
  const [isActivated, setIsActivated] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [errorMessage, setErrorMessage] = useState<string>('');
  const [showKey, setShowKey] = useState<boolean>(false);
  const [isDirty, setIsDirty] = useState<boolean>(false);
  const [showHelpModal, setShowHelpModal] = useState<string>('');

  const { register, handleSubmit, reset, formState: { errors } } = useForm<FormData>({
    defaultValues: { apiKey: '', model: '' },
  });

  useEffect(() => {
    fetchConfig();
  }, []);

  useEffect(() => {
    localStorage.setItem('automarketer-ai-settings-tab', JSON.stringify({ selectedProvider, isActivated }));
  }, [selectedProvider, isActivated]);

  const fetchConfig = async () => {
    try {
      const response = await wp.apiFetch({
        path: 'automarketer-ai/v1/ai-provider/config',
        method: 'GET',
      });
      if (response.success) {
        setSelectedProvider(response.config.selected_provider);
        setModels(response.config.models || []);
        setLastTest(response.config.last_test);
        reset({ model: response.config.selected_model });
        setIsActivated(!!response.config.keys.grok); // Activated if key present
        setIsDirty(false);
      }
    } catch (err) {
      toast.error(__('Failed to load config', 'automarketer-ai'));
    }
  };

  const onSubmit = async (data: FormData) => {
    setIsLoading(true);
    setErrorMessage('');
    try {
      const response = await wp.apiFetch({
        path: 'automarketer-ai/v1/ai-provider/configure',
        method: 'POST',
        data: {
          provider: selectedProvider,
          api_key: data.apiKey,
          model: data.model,
        },
      });
      if (response.success) {
        toast.success(__('Activated', 'automarketer-ai'));
        await fetchConfig();
        document.getElementById('settings-live-region')?.setAttribute('aria-live', 'assertive');
      } else {
        setErrorMessage(response.message);
        toast.error(response.message);
      }
    } catch (err) {
      setErrorMessage(__('Activate failed', 'automarketer-ai'));
      toast.error(__('Activate failed', 'automarketer-ai'));
    } finally {
      setIsLoading(false);
      setIsDirty(false);
    }
  };

  const deactivate = async () => {
    setIsLoading(true);
    setErrorMessage('');
    try {
      const response = await wp.apiFetch({
        path: 'automarketer-ai/v1/ai-provider/configure',
        method: 'POST',
        data: {
          provider: selectedProvider,
          api_key: '', // Clear key to deactivate
          model: '',
        },
      });
      if (response.success) {
        toast.success(__('Deactivated', 'automarketer-ai'));
        await fetchConfig();
      } else {
        setErrorMessage(response.message);
        toast.error(response.message);
      }
    } catch (err) {
      setErrorMessage(__('Deactivate failed', 'automarketer-ai'));
      toast.error(__('Deactivate failed', 'automarketer-ai'));
    } finally {
      setIsLoading(false);
    }
  };

  const testConnection = async () => {
    setIsLoading(true);
    setErrorMessage('');
    try {
      const response = await wp.apiFetch({
        path: 'automarketer-ai/v1/ai-provider/test',
        method: 'POST',
        data: { provider: selectedProvider },
      });
      if (response.success) {
        toast.success(__('Connection successful', 'automarketer-ai'));
        setModels(response.models);
        setLastTest(response.timestamp);
      } else {
        setErrorMessage(response.message);
        toast.error(response.message);
      }
    } catch (err) {
      setErrorMessage(__('Test failed', 'automarketer-ai'));
      toast.error(__('Test failed', 'automarketer-ai'));
    } finally {
      setIsLoading(false);
    }
  };

  const resetForm = () => {
    reset();
    setIsDirty(false);
  };

  const handleProviderChange = (provider: string) => {
    setSelectedProvider(provider);
    setIsDirty(true);
  };

  const openHelpModal = (type: string) => {
    setShowHelpModal(type);
  };

  return (
    <div className="automarketer-ai-settings-tab" role="tabpanel" aria-labelledby="ai-tab">
      <h2>{__('AI Services', 'automarketer-ai')}</h2>
      <div className="side-tab">
        <h3>{__('API Services', 'automarketer-ai')}</h3>
        <div className="provider-chips">
          {availableProviders.map((prov) => (
            <button
              key={prov}
              className={`chip ${prov === selectedProvider ? 'active' : ''} ${isActivated ? 'grayed' : ''}`}
              onClick={() => !isActivated && handleProviderChange(prov)}
              aria-pressed={prov === selectedProvider}
              disabled={isActivated}
              style={{
                backgroundColor: prov === selectedProvider ? '#4CAF50' : (isActivated ? '#CCCCCC' : '#E0E0E0'),
              }} // Full green for active, gray for deactivated
            >
              {prov.toUpperCase()}
              <Tooltip text={__('Select this provider', 'automarketer-ai')}>
                <span className="help-icon" onClick={() => openHelpModal(prov)}>?</span>
              </Tooltip>
            </button>
          ))}
        </div>
      </div>
      <form onSubmit={handleSubmit(onSubmit)}>
        <TextControl
          label={__('API Key', 'automarketer-ai')}
          type={showKey ? 'text' : 'password'}
          {...register('apiKey', { required: __('API key required', 'automarketer-ai') })}
          aria-invalid={!!errors.apiKey}
          aria-describedby={errors.apiKey ? 'key-error' : undefined}
          onChange={() => setIsDirty(true)}
        />
        <Button onClick={() => setShowKey(!showKey)} aria-label={__('Toggle key visibility', 'automarketer-ai')}>
          {showKey ? __('Hide', 'automarketer-ai') : __('Show', 'automarketer-ai')}
        </Button>
        <Tooltip text={__('Enter your Grok API key from x.ai', 'automarketer-ai')}>
          <span className="help-icon" onClick={() => openHelpModal('key')}>?</span>
        </Tooltip>
        {errors.apiKey && <Notice status="error"><span id="key-error">{errors.apiKey.message}</span></Notice>}

        <Button isSecondary onClick={testConnection} disabled={isLoading}>
          {__('Test Connection', 'automarketer-ai')}
        </Button>
        {lastTest > 0 && <p>{__('Last tested: ', 'automarketer-ai')} {new Date(lastTest * 1000).toLocaleString()}</p>}
        <Tooltip text={__('Test API key and fetch models', 'automarketer-ai')}>
          <span className="help-icon" onClick={() => openHelpModal('test')}>?</span>
        </Tooltip>

        {models.length > 0 && (
          <select {...register('model', { required: __('Model required', 'automarketer-ai') })} onChange={() => setIsDirty(true)}>
            {models.map((mod) => (
              <option key={mod} value={mod}>{mod}</option>
            ))}
          </select>
        )}
        {errors.model && <Notice status="error"><span id="model-error">{errors.model.message}</span></Notice>}
        <Tooltip text={__('Select AI model after test', 'automarketer-ai')}>
          <span className="help-icon" onClick={() => openHelpModal('model')}>?</span>
        </Tooltip>

        {!isActivated ? (
          <Button isPrimary type="submit" disabled={isLoading || !isDirty}>
            {__('Activate', 'automarketer-ai')}
          </Button>
        ) : (
          <Button isDestructive onClick={deactivate} disabled={isLoading}>
            {__('Deactivate', 'automarketer-ai')}
          </Button>
        )}
        <Button isSecondary onClick={resetForm} disabled={!isDirty}>
          {__('Reset', 'automarketer-ai')}
        </Button>
        <Tooltip text={__('Save provider settings', 'automarketer-ai')}>
          <span className="help-icon" onClick={() => openHelpModal('save')}>?</span>
        </Tooltip>
      </form>

      {errorMessage && <Notice status="error">{errorMessage}</Notice>}

      <span id="settings-live-region" aria-live="polite" className="screen-reader-text"></span>

      {showHelpModal && (
        <Modal title={__('Help', 'automarketer-ai')} onRequestClose={() => setShowHelpModal('')}>
          <p>{getHelpText(showHelpModal)}</p>
          <ExternalLink href={getHelpLink(showHelpModal)}>{__('Full Guide', 'automarketer-ai')}</ExternalLink>
        </Modal>
      )}
    </div>
  );
};

function getHelpText(type: string): string {
  switch (type) {
    case 'grok':
      return __('Grok is the default AI provider. Enter your key from x.ai.');
    case 'key':
      return __('Your API key is encrypted and stored securely.');
    case 'test':
      return __('Tests connection and fetches available models.');
    case 'model':
      return __('Choose a model for AI responses.');
    case 'save':
      return __('Saves changes to database.');
    default:
      return __('General help.');
  }
}

function getHelpLink(type: string): string {
  switch (type) {
    case 'grok':
      return 'https://automarketer-ai.com/help/grok-setup';
    case 'key':
      return 'https://automarketer-ai.com/help/api-key-guide';
    case 'test':
      return 'https://automarketer-ai.com/help/test-connection';
    case 'model':
      return 'https://automarketer-ai.com/help/select-model';
    case 'save':
      return 'https://automarketer-ai.com/help/save-settings';
    default:
      return 'https://automarketer-ai.com/help/general';
  }
}

export default SettingsTab;