import React from 'react';
import { Spin } from 'antd';

// Hilfsfunktion für Dateigröße
export function formatFileSize(bytes) {
  if (typeof bytes !== 'number' || isNaN(bytes)) return '';
  if (bytes < 1024) return bytes + ' B';
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
  if (bytes < 1024 * 1024 * 1024) return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
  return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' GB';
}

// Hilfsfunktion für Video-Duration
export function formatDuration(seconds) {
  if (typeof seconds !== 'number' || isNaN(seconds)) return '';
  const mins = Math.floor(seconds / 60);
  const secs = Math.floor(seconds % 60);
  return `${mins}:${secs.toString().padStart(2, '0')}`;
}

// Datei-Vorschau-Komponente mit sofortiger Zoom-Skalierung und Loading-State
export default function FilePreview({ file, zoom = 1, darkMode = false }) {
  const [loaded, setLoaded] = React.useState(false);
  const width = file.width || 300;
  const height = file.height || 200;

  // Wrapper für saubere Skalierung
  const wrapperStyle = {
    display: 'inline-block',
    width: width * zoom,
    height: height * zoom,
    overflow: 'hidden',
    margin: 0,
    padding: 0,
    position: 'relative'
  };
  const innerStyle = {
    width,
    height,
    transform: `scale(${zoom})`,
    transformOrigin: 'top left',
    display: 'block'
  };

  const renderFileContent = () => {
    if (file.type === 'html') {
      return (
        <div style={wrapperStyle}>
          <div style={innerStyle}>
            {!loaded && (
              <div style={{ 
                position: 'absolute', 
                top: 0, 
                left: 0, 
                width: width, 
                height: height, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                backgroundColor: darkMode ? '#2c2c2c' : '#ffffff',
                border: `1px solid ${darkMode ? '#404040' : '#d9d9d9'}`,
                borderRadius: 4
              }}>
                <Spin size="large" />
              </div>
            )}
            <iframe
              src={file.url}
              title={file.name}
              width={width}
              height={height}
              style={{ border: 'none', opacity: loaded ? 1 : 0 }}
              onLoad={() => setLoaded(true)}
            />
          </div>
        </div>
      );
    }
    if (file.type === 'image') {
      return (
        <div style={wrapperStyle}>
          <div style={innerStyle}>
            {!loaded && (
              <div style={{ 
                position: 'absolute', 
                top: 0, 
                left: 0, 
                width: width, 
                height: height, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                backgroundColor: darkMode ? '#2c2c2c' : '#ffffff',
                border: `1px solid ${darkMode ? '#404040' : '#d9d9d9'}`,
                borderRadius: 6
              }}>
                <Spin size="large" />
              </div>
            )}
            <img
              src={file.url}
              alt={file.name}
              width={width}
              height={height}
              style={{ border: 'none', opacity: loaded ? 1 : 0 }}
              onLoad={() => setLoaded(true)}
              onError={() => setLoaded(true)}
            />
          </div>
        </div>
      );
    }
    if (file.type === 'video') {
      return (
        <div style={wrapperStyle}>
          <div style={innerStyle}>
            {!loaded && (
              <div style={{ 
                position: 'absolute', 
                top: 0, 
                left: 0, 
                width: width, 
                height: height, 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center', 
                backgroundColor: darkMode ? '#2c2c2c' : '#ffffff',
                border: `1px solid ${darkMode ? '#404040' : '#d9d9d9'}`,
                borderRadius: 6
              }}>
                <Spin size="large" />
              </div>
            )}
            <video
              src={file.url}
              width={width}
              height={height}
              controls
              autoPlay
              loop
              muted
              preload="metadata"
              style={{ border: 'none', opacity: loaded ? 1 : 0 }}
              onLoadedData={() => setLoaded(true)}
              onError={() => setLoaded(true)}
            />
          </div>
        </div>
      );
    }
    // Sonstige Datei: Link
    return (
      <a href={file.url} target="_blank" rel="noopener noreferrer">{file.name}</a>
    );
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', marginBottom: 16, marginTop: 16 }}>
      {renderFileContent()}
      {/* Badge für jede einzelne Datei */}
      {(file.width || file.height || file.size || file.duration) && (
        <div style={{
          marginTop: 0,
          background: darkMode ? 'rgba(31, 31, 31, 0.95)' : 'rgba(31, 31, 31, 0.95)',
          color: darkMode ? '#f9f9f9' : '#f9f9f9',
          borderBottomLeftRadius: 4,
          borderBottomRightRadius: 4,
          fontSize: 11,
          padding: '2px 6px',
          display: 'inline-block',
          lineHeight: 1.4,
          pointerEvents: 'none',
          zIndex: 10
        }}>
          {file.width && file.height ? `${file.width}×${file.height}px` : ''}
          {(file.width && file.height) && (file.size || file.duration) ? ' · ' : ''}
          {file.size ? formatFileSize(file.size) : ''}
          {file.size && file.duration ? ' · ' : ''}
          {file.type === 'video' && file.duration ? `${formatDuration(file.duration)} s` : ''}
        </div>
      )}
    </div>
  );
}
