//
//  TooltipView.swift
//  lichunWebsocket
//
//  Visual components for displaying contextual tooltips
//

import SwiftUI

// MARK: - TooltipView

/// Displays a contextual tooltip with title, message, and arrow pointer
struct TooltipView: View {
    let tooltip: TooltipData
    let onDismiss: () -> Void

    var body: some View {
        ZStack(alignment: tooltipAlignment) {
            // Tooltip card content with warm, friendly design
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                // Header with title and dismiss button
                HStack {
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: "lightbulb.fill")
                            .font(.system(size: 14))
                            .foregroundStyle(
                                LinearGradient(
                                    gradient: Gradient(colors: [
                                        Color(hex: 0xFFB88C),
                                        Color(hex: 0xFF8C94)
                                    ]),
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                )
                            )

                        Text(tooltip.title)
                            .font(.appBodyBold)
                            .foregroundColor(AppColors.primaryText)
                    }

                    Spacer()

                    Button(action: onDismiss) {
                        Image(systemName: "xmark.circle.fill")
                            .font(.system(size: 20))
                            .foregroundColor(AppColors.secondaryText.opacity(0.5))
                    }
                }

                // Message with better readability
                Text(tooltip.message)
                    .font(.appBody)
                    .foregroundColor(AppColors.primaryText.opacity(0.85))
                    .fixedSize(horizontal: false, vertical: true)
                    .lineSpacing(2)

                // Got it button with warm gradient
                Button(action: onDismiss) {
                    Text("Got it!")
                        .font(.appBodyBold)
                        .foregroundColor(.white)
                        .frame(maxWidth: .infinity)
                        .frame(height: AppSpacing.buttonHeight - 4)
                        .background(
                            LinearGradient(
                                gradient: Gradient(colors: [
                                    Color(hex: 0xFFB88C),
                                    Color(hex: 0xFF8C94)
                                ]),
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .cornerRadius(AppSpacing.cornerRadius)
                        .shadow(color: Color(hex: 0xFF8C94).opacity(0.3), radius: 8, y: 4)
                }
                .padding(.top, AppSpacing.xs)
            }
            .padding(AppSpacing.md)
            .frame(maxWidth: 280)
            .background(
                RoundedRectangle(cornerRadius: 16)
                    .fill(AppColors.surfaceElevated)
                    .shadow(color: Color(hex: 0xFF8C94).opacity(0.2), radius: 20, x: 0, y: 8)
            )

            // Arrow pointing to target, matching the tooltip card surface
            TooltipArrow(position: tooltip.position)
                .fill(AppColors.surfaceElevated)
                .frame(width: 16, height: 8)
                .offset(arrowOffset)
                .shadow(color: Color(hex: 0xFF8C94).opacity(0.15), radius: 8)
        }
    }

    // MARK: - Computed Properties

    /// Alignment for the tooltip content and arrow
    private var tooltipAlignment: Alignment {
        switch tooltip.position {
        case .top:
            return .bottom
        case .bottom:
            return .top
        case .leading:
            return .trailing
        case .trailing:
            return .leading
        }
    }

    /// Offset for the arrow to position it correctly
    private var arrowOffset: CGSize {
        switch tooltip.position {
        case .top:
            return CGSize(width: 0, height: 8)
        case .bottom:
            return CGSize(width: 0, height: -8)
        case .leading:
            return CGSize(width: 8, height: 0)
        case .trailing:
            return CGSize(width: -8, height: 0)
        }
    }
}

// MARK: - TooltipArrow

/// Triangle arrow shape that points to the target UI element
struct TooltipArrow: Shape {
    let position: TooltipPosition

    func path(in rect: CGRect) -> Path {
        var path = Path()

        switch position {
        case .top:
            // Arrow pointing up
            path.move(to: CGPoint(x: rect.midX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
            path.closeSubpath()

        case .bottom:
            // Arrow pointing down
            path.move(to: CGPoint(x: rect.midX, y: rect.maxY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
            path.closeSubpath()

        case .leading:
            // Arrow pointing left
            path.move(to: CGPoint(x: rect.minX, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
            path.closeSubpath()

        case .trailing:
            // Arrow pointing right
            path.move(to: CGPoint(x: rect.maxX, y: rect.midY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.minY))
            path.addLine(to: CGPoint(x: rect.minX, y: rect.maxY))
            path.closeSubpath()
        }

        return path
    }
}

// MARK: - TooltipModifier

/// View modifier that adds tooltip functionality to any view
struct TooltipModifier: ViewModifier {
    @ObservedObject var manager: TooltipManager

    let id: String
    let title: String
    let message: String
    let position: TooltipPosition
    let trigger: TooltipTrigger

    @State private var hasTriggered = false

    func body(content: Content) -> some View {
        content
            .onAppear {
                guard trigger == .onAppear, !hasTriggered else { return }
                hasTriggered = true

                // Delay to allow view to settle
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    manager.showTooltipIfNeeded(id, title: title, message: message, position: position)
                }
            }
            .onTapGesture {
                guard trigger == .onTap, !hasTriggered else { return }
                hasTriggered = true
                manager.showTooltipIfNeeded(id, title: title, message: message, position: position)
            }
    }
}

// MARK: - View Extension

extension View {
    /// Adds a contextual tooltip to the view
    /// - Parameters:
    ///   - manager: The tooltip manager instance
    ///   - id: Unique identifier for the tooltip
    ///   - title: Bold title text
    ///   - message: Descriptive message text
    ///   - position: Where to position the tooltip (default: .top)
    ///   - trigger: When to show the tooltip (default: .onAppear)
    /// - Returns: Modified view with tooltip capability
    func tooltip(
        manager: TooltipManager,
        id: String,
        title: String,
        message: String,
        position: TooltipPosition = .top,
        trigger: TooltipTrigger = .onAppear
    ) -> some View {
        modifier(TooltipModifier(
            manager: manager,
            id: id,
            title: title,
            message: message,
            position: position,
            trigger: trigger
        ))
    }
}

// MARK: - Preview Provider

struct TooltipView_Previews: PreviewProvider {
    static var previews: some View {
        ZStack {
            // Background
            AppColors.background
                .ignoresSafeArea()

            VStack(spacing: 40) {
                // Top position tooltip
                VStack {
                    Text("Target Element")
                        .padding()
                        .background(Color.gray.opacity(0.3))
                        .cornerRadius(8)

                    TooltipView(
                        tooltip: TooltipData(
                            id: "preview_top",
                            title: "Welcome!",
                            message: "This is a tooltip that points to the element above it.",
                            position: .bottom
                        ),
                        onDismiss: {}
                    )
                }

                Spacer()

                // Bottom position tooltip
                VStack {
                    TooltipView(
                        tooltip: TooltipData(
                            id: "preview_bottom",
                            title: "Energy System",
                            message: "Actions cost energy. When you run out, you can refill with diamonds or wait for natural regeneration.",
                            position: .top
                        ),
                        onDismiss: {}
                    )

                    Text("Energy Badge")
                        .padding()
                        .background(Color.gray.opacity(0.3))
                        .cornerRadius(8)
                }
            }
            .padding()
        }
    }
}

// MARK: - Interactive Preview

struct TooltipInteractive_Previews: PreviewProvider {
    static var previews: some View {
        TooltipInteractivePreview()
    }
}

struct TooltipInteractivePreview: View {
    @StateObject private var tooltipManager = TooltipManager()

    var body: some View {
        ZStack {
            AppColors.background
                .ignoresSafeArea()

            VStack(spacing: 40) {
                Text("Tap the button below")
                    .font(.appHeadline)
                    .foregroundColor(AppColors.primaryText)

                Button(action: {
                    tooltipManager.showTooltipIfNeeded(
                        "interactive_demo",
                        title: "First Time Here?",
                        message: "This is an interactive demo of the tooltip system. Tap 'Got it' to dismiss!",
                        position: .bottom
                    )
                }) {
                    Text("Show Tooltip")
                        .font(.appBodyBold)
                        .foregroundColor(.white)
                        .frame(width: 200, height: AppSpacing.buttonHeight)
                        .background(AppColors.primary)
                        .cornerRadius(AppSpacing.cornerRadius)
                }

                if let tooltip = tooltipManager.activeTooltip {
                    TooltipView(tooltip: tooltip) {
                        tooltipManager.dismissTooltip()
                    }
                    .transition(.scale.combined(with: .opacity))
                }
            }
            .padding()
        }
    }
}
