import SwiftUI

// MARK: - AttachmentPreviewStrip

/// Horizontal strip above the compositor showing selected attachments before send.
///
/// Desktop parity: `DialogInput.tsx` renders `DialogAttachment` components in a
/// flex row above the input field when `attachments.length > 0`.
///
/// Each item shows a thumbnail (images) or file card (files) with a red X remove button.
struct AttachmentPreviewStrip: View {

    @Binding var pendingAttachments: [PendingAttachment]

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {
                ForEach(pendingAttachments) { attachment in
                    attachmentPreview(attachment)
                }
            }
            .padding(.horizontal, 16)
            .padding(.vertical, 6)
        }
    }

    @ViewBuilder
    private func attachmentPreview(_ attachment: PendingAttachment) -> some View {
        ZStack(alignment: .topTrailing) {
            switch attachment.type {
            case .image:
                imagePreview(attachment)
            case .file:
                filePreview(attachment)
            default:
                EmptyView()
            }

            // Remove button (Figma: red circle with X)
            Button {
                withAnimation(.easeInOut(duration: 0.2)) {
                    pendingAttachments.removeAll { $0.id == attachment.id }
                }
            } label: {
                Image(systemName: "xmark")
                    .font(.system(size: 9, weight: .bold))
                    .foregroundStyle(.white)
                    .frame(width: 18, height: 18)
                    .background(Color.red, in: Circle())
            }
            .offset(x: 4, y: -4)
        }
    }

    @ViewBuilder
    private func imagePreview(_ attachment: PendingAttachment) -> some View {
        if let thumbnail = attachment.thumbnail {
            Image(uiImage: thumbnail)
                .resizable()
                .scaledToFill()
                .frame(width: 70, height: 70)
                .clipShape(RoundedRectangle(cornerRadius: 8))
        } else {
            RoundedRectangle(cornerRadius: 8)
                .fill(Color.white.opacity(0.1))
                .frame(width: 70, height: 70)
                .overlay {
                    Image(systemName: "photo")
                        .foregroundStyle(.white.opacity(0.4))
                }
        }
    }

    @ViewBuilder
    private func filePreview(_ attachment: PendingAttachment) -> some View {
        VStack(spacing: 4) {
            Image(systemName: fileIcon(for: attachment.fileName ?? "file"))
                .font(.system(size: 22))
                .foregroundStyle(Color(hex: 0x008BFF))

            Text(attachment.fileName ?? "file")
                .font(.system(size: 9))
                .foregroundStyle(.white.opacity(0.8))
                .lineLimit(2)
                .multilineTextAlignment(.center)

            Text(formatFileSize(attachment.fileSize ?? 0))
                .font(.system(size: 8))
                .foregroundStyle(.white.opacity(0.4))
        }
        .frame(width: 70, height: 70)
        .background(Color.white.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))
    }

    // MARK: - Helpers

    /// Returns an appropriate SF Symbol name for the file extension.
    private func fileIcon(for fileName: String) -> String {
        let ext = (fileName as NSString).pathExtension.lowercased()
        switch ext {
        case "pdf": return "doc.fill"
        case "zip", "rar", "7z": return "doc.zipper"
        case "jpg", "jpeg", "png", "gif", "webp": return "photo.fill"
        case "mp4", "mov", "avi": return "film.fill"
        case "mp3", "wav", "aac": return "waveform"
        case "doc", "docx": return "doc.text.fill"
        case "xls", "xlsx": return "tablecells.fill"
        case "txt": return "doc.plaintext.fill"
        default: return "doc.fill"
        }
    }

    /// Formats byte count to human-readable string.
    private func formatFileSize(_ bytes: Int) -> String {
        if bytes < 1024 {
            return "\(bytes) B"
        } else if bytes < 1024 * 1024 {
            return String(format: "%.1f KB", Double(bytes) / 1024)
        } else {
            return String(format: "%.1f MB", Double(bytes) / (1024 * 1024))
        }
    }
}
