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

// ─── Inline markdown renderer ─────────────────────────────────────────────────

/** Convert **bold**, *italic*, __underline__ markers to React elements */
function renderInline(text: string): ReactNode {
  // Pattern: **bold** first (must precede *italic* to avoid false matches)
  const pattern = /(\*\*([^*\n]+)\*\*)|(\*([^*\n]+)\*)|(__([^_\n]+)__)/g;
  const parts: ReactNode[] = [];
  let lastIndex = 0;
  let match: RegExpExecArray | null;
  let key = 0;

  while ((match = pattern.exec(text)) !== null) {
    if (match.index > lastIndex) parts.push(text.substring(lastIndex, match.index));
    if (match[1]) parts.push(<strong key={key++}>{match[2]}</strong>);
    else if (match[3]) parts.push(<em key={key++}>{match[4]}</em>);
    else if (match[5]) parts.push(<u key={key++}>{match[6]}</u>);
    lastIndex = pattern.lastIndex;
  }
  if (lastIndex < text.length) parts.push(text.substring(lastIndex));
  return <>{parts}</>;
}

/** Render the full tasks string: bullets, numbered lists, indentation, inline formatting */
function RichText({ text }: { text: string }) {
  const lines = text.split('\n');
  return (
    <div className={styles.richText}>
      {lines.map((line, i) => {
        const bm = line.match(/^( *)(• )(.*)$/);
        const nm = line.match(/^( *)(\d+)\. (.*)$/);

        if (bm) {
          return (
            <div key={i} className={styles.richTextLine} style={{ paddingLeft: `${bm[1].length * 0.875}rem` }}>
              <span className={styles.richTextBullet}>•</span>
              <span>{renderInline(bm[3])}</span>
            </div>
          );
        }
        if (nm) {
          return (
            <div key={i} className={styles.richTextLine} style={{ paddingLeft: `${nm[1].length * 0.875}rem` }}>
              <span className={styles.richTextNum}>{nm[2]}.</span>
              <span>{renderInline(nm[3])}</span>
            </div>
          );
        }
        if (!line.trim()) {
          return <div key={i} className={styles.richTextBlank} />;
        }
        const im = line.match(/^( *)(.*)/);
        return (
          <div key={i} style={{ paddingLeft: `${(im?.[1]?.length ?? 0) * 0.875}rem` }}>
            {renderInline(im?.[2] ?? line)}
          </div>
        );
      })}
    </div>
  );
}

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} ${project.tasks ? styles.entryItemExpanded : ''}`}
            >
              <div className={styles.entryItemRow}>
                <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>
              {project.tasks && (
                <div className={styles.entryTasks}>
                  <RichText text={project.tasks} />
                </div>
              )}
            </div>
          ))}
        </div>
      ) : (
        <p className={styles.emptyState}>Noch keine Projekte hinzugefügt</p>
      )}

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