/**
 * AttachmentPreview — рендер `Message.attachment` внутри bubble'а.
 *
 * Четыре формы:
 *   - image → Image с object-fit cover, aspect-ratio из width/height
 *   - video → то же + play-overlay в центре, duration внизу-справа
 *   - voice → row [play-icon] [waveform stub] [duration]
 *   - file  → row [file-icon] [name + size]
 *
 * Вложения размещаются ВНУТРИ того же bubble'а что и текст, чуть ниже
 * footer'а нет и ширина bubble'а снимает maxWidth-ограничение ради
 * изображений (отдельный media-first-bubble case).
 */
import React from 'react';
import { View, Text, Image } from 'react-native';
import { Ionicons } from '@expo/vector-icons';

import type { Attachment } from '@/lib/types';
import { VoicePlayer } from '@/components/chat/VoicePlayer';
import { VideoCirclePlayer } from '@/components/chat/VideoCirclePlayer';

export interface AttachmentPreviewProps {
  attachment: Attachment;
  /** Используется для тонирования footer-элементов. */
  own?: boolean;
}

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

function formatDuration(seconds: number): string {
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${String(s).padStart(2, '0')}`;
}

export function AttachmentPreview({ attachment, own }: AttachmentPreviewProps) {
  switch (attachment.kind) {
    case 'image':
      return <ImageAttachment att={attachment} />;
    case 'video':
      // circle=true — круглое видео-сообщение (Telegram-стиль).
      return attachment.circle
        ? <VideoCirclePlayer uri={attachment.uri} duration={attachment.duration} />
        : <VideoAttachment att={attachment} />;
    case 'voice':
      return <VoicePlayer uri={attachment.uri} duration={attachment.duration} own={own} />;
    case 'file':
      return <FileAttachment att={attachment} own={own} />;
  }
}

// ─── Image ──────────────────────────────────────────────────────────

function ImageAttachment({ att }: { att: Attachment }) {
  // Aspect-ratio из реальных width/height; fallback 4:3.
  const aspect = att.width && att.height ? att.width / att.height : 4 / 3;
  return (
    <Image
      source={{ uri: att.uri }}
      style={{
        width: '100%',
        aspectRatio: aspect,
        borderRadius: 12,
        marginBottom: 4,
        backgroundColor: '#0a0a0a',
      }}
      resizeMode="cover"
    />
  );
}

// ─── Video ──────────────────────────────────────────────────────────

function VideoAttachment({ att }: { att: Attachment }) {
  const aspect = att.width && att.height ? att.width / att.height : 16 / 9;
  return (
    <View style={{ position: 'relative', marginBottom: 4 }}>
      <Image
        source={{ uri: att.uri }}
        style={{
          width: '100%',
          aspectRatio: aspect,
          borderRadius: 12,
          backgroundColor: '#0a0a0a',
        }}
        resizeMode="cover"
      />
      {/* Play overlay по центру */}
      <View
        style={{
          position: 'absolute',
          top: '50%', left: '50%',
          transform: [{ translateX: -22 }, { translateY: -22 }],
          width: 44, height: 44, borderRadius: 22,
          backgroundColor: 'rgba(0,0,0,0.55)',
          alignItems: 'center', justifyContent: 'center',
        }}
      >
        <Ionicons name="play" size={22} color="#ffffff" style={{ marginLeft: 2 }} />
      </View>
      {att.duration !== undefined && (
        <View
          style={{
            position: 'absolute',
            right: 8, bottom: 8,
            backgroundColor: 'rgba(0,0,0,0.6)',
            paddingHorizontal: 6, paddingVertical: 2,
            borderRadius: 4,
          }}
        >
          <Text style={{ color: '#ffffff', fontSize: 11, fontWeight: '600' }}>
            {formatDuration(att.duration)}
          </Text>
        </View>
      )}
    </View>
  );
}

// ─── Voice ──────────────────────────────────────────────────────────
// Реальный плеер — см. components/chat/VoicePlayer.tsx (expo-av Sound).

// ─── File ───────────────────────────────────────────────────────────

function FileAttachment({ att, own }: { att: Attachment; own?: boolean }) {
  return (
    <View
      style={{
        flexDirection: 'row',
        alignItems: 'center',
        marginBottom: 4,
        gap: 10,
        paddingVertical: 4,
      }}
    >
      <View
        style={{
          width: 36, height: 36, borderRadius: 10,
          backgroundColor: own ? 'rgba(255,255,255,0.18)' : '#1a1a1a',
          alignItems: 'center', justifyContent: 'center',
        }}
      >
        <Ionicons
          name="document-text"
          size={18}
          color={own ? '#ffffff' : '#ffffff'}
        />
      </View>
      <View style={{ flex: 1, minWidth: 0 }}>
        <Text
          numberOfLines={1}
          style={{
            color: '#ffffff',
            fontSize: 14,
            fontWeight: '600',
          }}
        >
          {att.name ?? 'file'}
        </Text>
        <Text
          style={{
            color: own ? 'rgba(255,255,255,0.75)' : '#8b8b8b',
            fontSize: 11,
          }}
        >
          {att.size !== undefined ? formatSize(att.size) : ''}
          {att.size !== undefined && att.mime ? '  ·  ' : ''}
          {att.mime ?? ''}
        </Text>
      </View>
    </View>
  );
}
