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

interface ExperienceSectionProps {
  experiences: ExpertExperience[];
  onUpdate: () => Promise<void>;
}

export function ExperienceSection({ experiences, onUpdate }: ExperienceSectionProps) {
  const [area, setArea] = useState('');
  const [years, setYears] = useState('');
  const [level, setLevel] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

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

    setLoading(true);
    setError('');
    try {
      await api.post('/expert-profile/me/experiences', {
        area: area.trim(),
        years: parseInt(years, 10),
        ...(level && { level }),
      });
      setArea('');
      setYears('');
      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/experiences/${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}>Erfahrung</h3>
        <form onSubmit={handleAdd} className={styles.headerForm}>
          <input
            type="text"
            value={area}
            onChange={(e) => setArea(e.target.value)}
            placeholder="z.B. IT Infrastruktur"
            maxLength={200}
            required
          />
          <input
            type="number"
            value={years}
            onChange={(e) => setYears(e.target.value)}
            placeholder="Jahre"
            min={0}
            max={60}
            style={{ width: '70px' }}
            required
          />
          <select value={level} onChange={(e) => setLevel(e.target.value)}>
            <option value="">Level</option>
            <option value="Experte">Experte</option>
            <option value="Fortgeschritten">Fortgeschritten</option>
            <option value="Grundkenntnisse">Grundkenntnisse</option>
          </select>
          <button type="submit" className={styles.btnPrimary} disabled={loading || !area.trim() || !years}>
            Hinzufügen
          </button>
        </form>
      </div>

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

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