import { useState } from 'react';
import type { ExpertCertification } from '../ExpertProfileTab';
import { CertificationModal } from './CertificationModal';
import styles from '../ExpertProfileTab.module.css';
import api from '../../api/client';

interface CertificationsSectionProps {
  certifications: ExpertCertification[];
  onUpdate: () => Promise<void>;
}

export function CertificationsSection({ certifications, onUpdate }: CertificationsSectionProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const [editCert, setEditCert] = useState<ExpertCertification | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleEdit = (cert: ExpertCertification) => {
    setEditCert(cert);
    setModalOpen(true);
  };

  const handleAdd = () => {
    setEditCert(null);
    setModalOpen(true);
  };

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

  const handleModalClose = () => {
    setModalOpen(false);
    setEditCert(null);
  };

  const handleModalSave = async () => {
    handleModalClose();
    await onUpdate();
  };

  return (
    <div className={styles.section}>
      <div className={styles.sectionHeader}>
        <h3 className={styles.sectionTitle}>Zertifizierungen</h3>
        <button type="button" className={styles.btnPrimary} onClick={handleAdd}>
          + Zertifizierung hinzufügen
        </button>
      </div>

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

      {certifications.length > 0 ? (
        <div className={styles.entryList}>
          {certifications.map((cert) => (
            <div key={cert.id} className={styles.entryItem}>
              <div className={styles.entryInfo}>
                <span className={styles.entryPrimary}>{cert.title}</span>
                <span className={styles.entrySecondary}>{cert.issuingBody}</span>
                <span className={styles.entryBadge}>{cert.issueYear}</span>
              </div>
              <div className={styles.entryActions}>
                <button
                  type="button"
                  className={styles.btnIcon}
                  onClick={() => handleEdit(cert)}
                  disabled={loading}
                  title="Bearbeiten"
                >
                  ✏️
                </button>
                <button
                  type="button"
                  className={`${styles.btnIcon} ${styles.btnIconDanger}`}
                  onClick={() => handleDelete(cert.id)}
                  disabled={loading}
                  title="Löschen"
                >
                  🗑
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <p className={styles.emptyState}>Noch keine Zertifizierungen hinzugefügt</p>
      )}

      <CertificationModal
        isOpen={modalOpen}
        onClose={handleModalClose}
        onSave={handleModalSave}
        certification={editCert}
      />
    </div>
  );
}
