import { useModel } from '../hooks/useModel';
import { MoodleGPTConfig } from '../hooks/useConfig';
import { useState } from 'preact/hooks';

interface Props {
  config: MoodleGPTConfig;
  onChange: (key: keyof MoodleGPTConfig, value: MoodleGPTConfig[keyof MoodleGPTConfig]) => void;
  showMessage: (msg: string, isError?: boolean) => void;
  visible: boolean;
}

export function SettingsPanel({ config, onChange, showMessage, visible }: Props) {
  if (!visible) return null;
  const { models, fetchModels, validateModel } = useModel(
    config.apiKey,
    config.baseURL,
    config.projectId
  );
  const [testing, setTesting] = useState(false);

  const handleTest = async () => {
    if (!config.model) {
      showMessage('Please select a model first', true);
      return;
    }
    setTesting(true);
    showMessage('Checking GPT version...', false);
    const result = await validateModel(config.model, config.maxTokens);
    setTesting(false);
    if (result.success) {
      showMessage(result.message || 'Valid model');
    } else {
      showMessage(result.error || 'Invalid model', true);
    }
  };

  return (
    <div
      class="bg-panel-bg backdrop-blur-md border border-panel-border rounded-2xl p-4 shadow-[0_8px_32px_0_rgba(0,0,0,0.3)]"
      id="settings"
    >
      <div class="flex flex-col gap-2 mb-4">
        <label htmlFor="apiKey" class="text-sm font-medium text-text-secondary">
          Api Key<span class="text-error ml-1">*</span>
        </label>
        <input
          id="apiKey"
          type="text"
          placeholder="sk-..."
          class="w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border"
          value={config.apiKey || ''}
          onInput={e => onChange('apiKey', (e.target as HTMLInputElement).value)}
        />
      </div>
      <div class="flex flex-col gap-2">
        <label htmlFor="model" class="text-sm font-medium text-text-secondary">
          GPT Model<span class="text-error ml-1">*</span>
        </label>
        <div class="relative flex items-center">
          <input
            type="text"
            id="model"
            list="models"
            placeholder="gpt-4o"
            class="w-full pl-3 pr-9 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border"
            value={config.model || ''}
            onInput={e => onChange('model', (e.target as HTMLInputElement).value)}
            onFocus={fetchModels}
          />
          <datalist id="models">
            {models.map(m => (
              <option key={m} value={m}>
                {m}
              </option>
            ))}
          </datalist>
          <i
            class={`fa-solid ${testing ? 'fa-spinner fa-spin' : 'fa-play'} absolute right-3 text-primary text-sm transition-all hover:scale-110 hover:text-primary-hover cursor-pointer`}
            onClick={handleTest}
            title="Test"
          ></i>
        </div>
      </div>
    </div>
  );
}
