import { useState } from 'preact/hooks';
import { Header } from './Header';
import { SettingsPanel } from './SettingsPanel';
import { AdvancedSettingsPanel } from './AdvancedSettingsPanel';
import { OptionsGrid } from './OptionsGrid';
import { OperatingMode } from './OperatingMode';
import { useConfig, MoodleGPTConfig } from '../hooks/useConfig';

export function App() {
  const { config, loading, saveConfig, setConfig } = useConfig();
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [message, setMessage] = useState<{ text: string; isError: boolean } | null>(null);

  if (loading) return null;

  const handleConfigChange = (
    key: keyof MoodleGPTConfig,
    value: MoodleGPTConfig[keyof MoodleGPTConfig]
  ) => {
    setConfig(prev => ({ ...prev, [key]: value }));
  };

  const showMessage = (msg: string, isError = false) => {
    setMessage({ text: msg, isError });
    setTimeout(() => setMessage(null), 5000);
  };

  const handleSave = async () => {
    if (!config.apiKey || !config.model) {
      showMessage('Please complete all the form', true);
      return;
    }
    if (config.code && config.code.length > 0 && config.code.length < 2) {
      showMessage('The code should at least contain 2 characters', true);
      return;
    }
    await saveConfig(config);
    showMessage('Configuration saved');
  };

  return (
    <main class="p-6 flex flex-col gap-5 bg-gradient-to-br from-gradient-start to-gradient-end text-text-primary min-h-screen font-sans antialiased overflow-x-hidden">
      <Header />

      <SettingsPanel
        config={config}
        onChange={handleConfigChange}
        showMessage={showMessage}
        visible={!showAdvanced}
      />

      <AdvancedSettingsPanel config={config} onChange={handleConfigChange} visible={showAdvanced} />

      <a
        href="#"
        class="block text-center text-sm text-text-secondary no-underline transition-colors hover:text-text-primary"
        onClick={e => {
          e.preventDefault();
          setShowAdvanced(!showAdvanced);
        }}
      >
        {showAdvanced ? 'Go back to settings' : 'Show Advanced Settings'}
      </a>

      <OperatingMode
        mode={config.mode || 'autocomplete'}
        onChange={m => handleConfigChange('mode', m)}
      />

      <div class="flex items-center gap-2 text-sm font-semibold text-text-primary my-2">
        <i class="fa-solid fa-sliders text-primary"></i>
        <span>Options</span>
      </div>

      <OptionsGrid config={config} onChange={handleConfigChange} />

      {message && (
        <p
          class={`text-center text-sm font-medium m-0 min-h-[18px] ${message.isError ? 'text-error' : 'text-success'}`}
        >
          {message.text}
        </p>
      )}

      <button
        class="w-full p-3 bg-gradient-to-br from-primary to-primary-hover text-white border-none rounded-xl text-base font-semibold cursor-pointer transition-all hover:-translate-y-0.5 hover:shadow-[0_4px_12px_rgba(99,102,241,0.4)] active:translate-y-0 mt-2"
        onClick={handleSave}
      >
        Save Preferences
      </button>

      <div class="flex justify-center gap-6 mt-2">
        <a
          class="text-sm font-medium no-underline transition-colors text-amber-400 hover:text-amber-300"
          href="https://www.buymeacoffee.com/yoannchbpro"
          target="_blank"
          rel="noopener noreferrer"
        >
          Support
        </a>
        <a
          class="text-sm font-medium no-underline transition-colors text-text-secondary hover:text-text-primary"
          href="https://github.com/yoannchb-pro/MoodleGPT"
          target="_blank"
          rel="noopener noreferrer"
        >
          Docs
        </a>
      </div>
    </main>
  );
}
