import { useState, type FormEvent } from 'react';
import api from '../../api/client';
import type { ExpertLanguage } from '../ExpertProfileTab';
import styles from '../ExpertProfileTab.module.css';

interface LanguagesSectionProps {
  languages: ExpertLanguage[];
  onUpdate: () => Promise<void>;
}

const LANGUAGE_LEVELS = ['Muttersprache', 'Verhandlungssicher', 'Fließend', 'Gut'];

export function LanguagesSection({ languages, onUpdate }: LanguagesSectionProps) {
  const [language, setLanguage] = useState('');
  const [level, setLevel] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleAdd = async (e: FormEvent) => {
    e.preventDefault();
    if (!language.trim() || !level) return;

    setLoading(true);
    setError('');
    try {
      await api.post('/expert-profile/me/languages', {
        language: language.trim(),
        level,
      });
      setLanguage('');
      setLevel('');
      await onUpdate();
    } catch {
      setError('Fehler beim Hinzufügen');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    setLoading(true);
    setError('');
    try {
      await api.delete(`/expert-profile/me/languages/${id}`);
      await onUpdate();
    } catch {
      setError('Fehler beim Löschen');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>Sprachen</h3>
        <form onSubmit={handleAdd} className={styles.headerForm}>
          <input
            type="text"
            value={language}
            onChange={(e) => setLanguage(e.target.value)}
            placeholder="z.B. Deutsch"
            maxLength={100}
            required
          />
          <select value={level} onChange={(e) => setLevel(e.target.value)} required>
            <option value="">Niveau</option>
            {LANGUAGE_LEVELS.map((l) => (
              <option key={l} value={l}>{l}</option>
            ))}
          </select>
          <button type="submit" className={styles.btnPrimary} disabled={loading || !language.trim() || !level}>
            Hinzufügen
          </button>
        </form>
      </div>

      {error && <div className={styles.error}>{error}</div>}

      {languages.length > 0 ? (
        <div className={styles.entryList}>
          {languages.map((lang) => (
            <div key={lang.id} className={styles.entryItem}>
              <div className={styles.entryInfo}>
                <span className={styles.entryPrimary}>{lang.language}</span>
                <span className={styles.entryBadge}>{lang.level}</span>
              </div>
              <div className={styles.entryActions}>
                <button
                  type="button"
                  className={`${styles.btnIcon} ${styles.btnIconDanger}`}
                  onClick={() => handleDelete(lang.id)}
                  disabled={loading}
                  title="Löschen"
                >
                  🗑
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <p className={styles.emptyState}>Noch keine Sprachen hinzugefügt</p>
      )}
    </div>
  );
}
