import { useState, useRef, type ChangeEvent } from 'react';
import api from '../../api/client';
import type { AttachmentMeta } from '../ExpertProfileTab';
import styles from '../ExpertProfileTab.module.css';

interface AttachmentsSectionProps {
  attachments: AttachmentMeta[];
  onUpdate: () => Promise<void>;
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function formatDate(dateStr: string): string {
  return new Date(dateStr).toLocaleDateString('de-DE', {
    day: '2-digit', month: '2-digit', year: 'numeric',
  });
}

const ACCEPTED_TYPES = '.pdf,.jpg,.jpeg,.png,.docx,.doc';
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB

export function AttachmentsSection({ attachments, onUpdate }: AttachmentsSectionProps) {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  const handleFileSelect = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (file.size > MAX_FILE_SIZE) {
      setError('Datei darf maximal 10MB groß sein');
      return;
    }

    setLoading(true);
    setError('');
    setSuccess('');

    try {
      const base64 = await new Promise<string>((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = reject;
        reader.readAsDataURL(file);
      });

      await api.post('/expert-profile/me/attachments', {
        filename: file.name,
        mimetype: file.type || 'application/octet-stream',
        size: file.size,
        data: base64,
      });

      setSuccess(`"${file.name}" erfolgreich hochgeladen`);
      await onUpdate();
    } catch {
      setError('Fehler beim Hochladen');
    } finally {
      setLoading(false);
      if (fileInputRef.current) fileInputRef.current.value = '';
    }
  };

  const handleDownload = async (id: string, filename: string) => {
    try {
      const { data } = await api.get<{ data: string; mimetype: string }>(
        `/expert-profile/me/attachments/${id}`,
      );

      const link = document.createElement('a');
      link.href = data.data;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch {
      setError('Fehler beim Herunterladen');
    }
  };

  const handleDelete = async (id: string) => {
    setLoading(true);
    setError('');
    setSuccess('');
    try {
      await api.delete(`/expert-profile/me/attachments/${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}>Profilanlagen</h3>
        <button
          type="button"
          className={styles.btnPrimary}
          onClick={() => fileInputRef.current?.click()}
          disabled={loading}
        >
          {loading ? 'Laden...' : '+ Datei hochladen'}
        </button>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept={ACCEPTED_TYPES}
        onChange={handleFileSelect}
        className={styles.hiddenInput}
      />

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

      {attachments.length > 0 ? (
        <div className={styles.entryList}>
          {attachments.map((att) => (
            <div key={att.id} className={styles.attachmentItem}>
              <div className={styles.attachmentInfo}>
                <span className={styles.attachmentName}>{att.filename}</span>
                <span className={styles.attachmentMeta}>
                  {formatFileSize(att.size)} · {formatDate(att.createdAt)}
                </span>
              </div>
              <div className={styles.entryActions}>
                <button
                  type="button"
                  className={styles.btnIcon}
                  onClick={() => handleDownload(att.id, att.filename)}
                  title="Herunterladen"
                >
                  ⬇
                </button>
                <button
                  type="button"
                  className={`${styles.btnIcon} ${styles.btnIconDanger}`}
                  onClick={() => handleDelete(att.id)}
                  disabled={loading}
                  title="Löschen"
                >
                  🗑
                </button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <p className={styles.emptyState}>
          Noch keine Anlagen hochgeladen. Unterstützte Formate: PDF, JPEG, PNG, DOCX (max. 10MB)
        </p>
      )}
    </div>
  );
}
