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

interface ProjectsSectionProps {
  projects: ExpertProject[];
  onUpdate: () => Promise<void>;
}

const MONTH_NAMES = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];

function formatPeriod(p: ExpertProject): string {
  const from = `${MONTH_NAMES[p.fromMonth - 1]} ${p.fromYear}`;
  if (p.isCurrent) return `${from} – heute`;
  if (p.toMonth && p.toYear) return `${from} – ${MONTH_NAMES[p.toMonth - 1]} ${p.toYear}`;
  return from;
}

export function ProjectsSection({ projects, onUpdate }: ProjectsSectionProps) {
  const [modalOpen, setModalOpen] = useState(false);
  const [editProject, setEditProject] = useState<ExpertProject | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleEdit = (project: ExpertProject) => {
    setEditProject(project);
    setModalOpen(true);
  };

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

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

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

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

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

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

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

      <ProjectModal
        isOpen={modalOpen}
        onClose={handleModalClose}
        onSave={handleModalSave}
        project={editProject}
      />
    </div>
  );
}
