import { useState, useEffect, useCallback } from 'react';
import api from '../api/client';
import { SkillsSection } from './sections/SkillsSection';
import { ExperienceSection } from './sections/ExperienceSection';
import { LanguagesSection } from './sections/LanguagesSection';
import { ProjectsSection } from './sections/ProjectsSection';
import { CertificationsSection } from './sections/CertificationsSection';
import { AttachmentsSection } from './sections/AttachmentsSection';
import styles from './ExpertProfileTab.module.css';

interface ExpertExperience {
  id: string;
  area: string;
  years: number;
  level?: string | null;
}

interface ExpertLanguage {
  id: string;
  language: string;
  level: string;
}

interface ExpertProject {
  id: string;
  fromMonth: number;
  fromYear: number;
  toMonth?: number | null;
  toYear?: number | null;
  isCurrent: boolean;
  role: string;
  tasks?: string | null;
  company?: string | null;
  companySize?: string | null;
  industry?: string | null;
}

interface ExpertCertification {
  id: string;
  title: string;
  issuingBody: string;
  website?: string | null;
  issueYear: number;
}

interface AttachmentMeta {
  id: string;
  filename: string;
  mimetype: string;
  size: number;
  createdAt: string;
}

interface ExpertProfile {
  id: string;
  skills: string[];
  experiences: ExpertExperience[];
  languages: ExpertLanguage[];
  projects: ExpertProject[];
  certifications: ExpertCertification[];
  attachments: AttachmentMeta[];
}

export type { ExpertExperience, ExpertLanguage, ExpertProject, ExpertCertification, AttachmentMeta };

export function ExpertProfileTab() {
  const [profile, setProfile] = useState<ExpertProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [exporting, setExporting] = useState(false);

  const loadProfile = useCallback(async () => {
    try {
      const { data } = await api.get<ExpertProfile>('/expert-profile/me');
      setProfile(data);
      setError('');
    } catch {
      setError('Experten-Profil konnte nicht geladen werden');
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    loadProfile();
  }, [loadProfile]);

  const handleExport = async (format: 'pdf' | 'docx') => {
    setExporting(true);
    try {
      const response = await api.get(`/expert-profile/me/export/${format}`, {
        responseType: 'blob',
      });
      const blob = response.data as Blob;
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = format === 'pdf' ? 'Profil.pdf' : 'Profil.docx';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
    } catch {
      setError(`Export als ${format.toUpperCase()} fehlgeschlagen`);
    } finally {
      setExporting(false);
    }
  };

  if (loading) {
    return (
      <div className={styles.loading}>
        Experten-Profil wird geladen...
      </div>
    );
  }

  if (error && !profile) {
    return <div className={styles.errorBox}>{error}</div>;
  }

  if (!profile) return null;

  return (
    <div className={styles.expertContainer}>
      {/* Export-Buttons */}
      <div className={styles.exportBar}>
        <button
          type="button"
          className={styles.btnSecondary}
          onClick={() => handleExport('pdf')}
          disabled={exporting}
        >
          {exporting ? 'Exportiert...' : 'PDF Export'}
        </button>
        <button
          type="button"
          className={styles.btnSecondary}
          onClick={() => handleExport('docx')}
          disabled={exporting}
        >
          {exporting ? 'Exportiert...' : 'Word Export'}
        </button>
      </div>

      {/* Skills + Sprachen nebeneinander */}
      <div className={styles.twoColumnRow}>
        <SkillsSection skills={profile.skills} onUpdate={loadProfile} />
        <LanguagesSection languages={profile.languages} onUpdate={loadProfile} />
      </div>
      <ExperienceSection experiences={profile.experiences} onUpdate={loadProfile} />
      <ProjectsSection projects={profile.projects} onUpdate={loadProfile} />
      <CertificationsSection certifications={profile.certifications} onUpdate={loadProfile} />
      <AttachmentsSection attachments={profile.attachments} onUpdate={loadProfile} />
    </div>
  );
}
