//
//  ErrorRecoveryView.swift
//  lichunWebsocket
//
//  Error recovery UI components
//

import SwiftUI

struct ErrorRecoveryView: View {
    let error: WebSocketService.WebSocketError
    let onRetry: (() -> Void)?
    let onDismiss: () -> Void

    var body: some View {
        VStack(spacing: AppSpacing.lg) {
            // Error icon with soft glow
            ZStack {
                Circle()
                    .fill(
                        RadialGradient(
                            colors: [
                                errorColor.opacity(0.2),
                                errorColor.opacity(0.1),
                                .clear
                            ],
                            center: .center,
                            startRadius: 20,
                            endRadius: 60
                        )
                    )
                    .frame(width: 120, height: 120)

                Image(systemName: error.icon)
                    .font(.system(size: 60, weight: .medium))
                    .foregroundColor(errorColor)
                    .shadow(color: errorColor.opacity(0.3), radius: 8, x: 0, y: 4)
            }

            // Title
            Text("Oops!")
                .font(.system(size: 32, weight: .bold, design: .rounded))
                .foregroundColor(AppColors.primaryText)

            // Message
            Text(error.userMessage)
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
                .multilineTextAlignment(.center)
                .padding(.horizontal, AppSpacing.md)
                .lineSpacing(4)

            // Actions
            HStack(spacing: AppSpacing.md) {
                // Dismiss button
                Button {
                    onDismiss()
                } label: {
                    Text("Dismiss")
                        .font(.system(size: 16, weight: .semibold, design: .rounded))
                        .foregroundColor(AppColors.secondaryText)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, AppSpacing.md)
                        .background(
                            RoundedRectangle(cornerRadius: 16)
                                .fill(AppColors.surfaceElevated)
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 16)
                                .stroke(AppColors.secondaryText.opacity(0.3), lineWidth: 1)
                        )
                }

                // Retry button (if retryable)
                if error.isRetryable, let retry = onRetry {
                    Button {
                        retry()
                    } label: {
                        Text("Try Again")
                            .font(.system(size: 16, weight: .semibold, design: .rounded))
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding(.vertical, AppSpacing.md)
                            .background(
                                LinearGradient(
                                    colors: [AppColors.primary, AppColors.accent],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .cornerRadius(16)
                            .shadow(color: AppColors.primary.opacity(0.3), radius: 8, x: 0, y: 4)
                    }
                }
            }
            .padding(.horizontal, AppSpacing.md)
        }
        .padding(AppSpacing.xl)
        .background(
            ZStack {
                RoundedRectangle(cornerRadius: 24)
                    .fill(AppColors.background)

                // Warm gradient overlay
                RoundedRectangle(cornerRadius: 24)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.5),
                                Color(hex: 0xFFF8F3).opacity(0.3)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
            }
        )
        .overlay(
            RoundedRectangle(cornerRadius: 24)
                .stroke(
                    LinearGradient(
                        colors: [Color.white.opacity(0.5), Color.clear],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 1
                )
        )
        .shadow(color: .black.opacity(0.1), radius: 20, x: 0, y: 10)
        .shadow(color: errorColor.opacity(0.15), radius: 15, x: 0, y: 8)
    }

    private var errorColor: Color {
        switch error {
        case .connectionLost:
            return AppColors.warning
        case .serverError, .timeout:
            return AppColors.error
        case .insufficientResources:
            return AppColors.warning
        case .invalidOperation:
            return AppColors.error
        }
    }
}

// MARK: - Error Banner (for less intrusive errors)
struct ErrorBanner: View {
    let error: WebSocketService.WebSocketError
    let onDismiss: () -> Void

    var body: some View {
        HStack(spacing: AppSpacing.sm) {
            ZStack {
                Circle()
                    .fill(Color.white.opacity(0.2))
                    .frame(width: 28, height: 28)

                Image(systemName: error.icon)
                    .foregroundColor(.white)
                    .font(.system(size: 14, weight: .semibold))
            }

            Text(error.userMessage)
                .font(.system(size: 14, weight: .medium, design: .rounded))
                .foregroundColor(.white)
                .lineLimit(2)

            Spacer()

            Button(action: onDismiss) {
                Image(systemName: "xmark.circle.fill")
                    .foregroundColor(.white.opacity(0.8))
                    .font(.system(size: 20))
            }
        }
        .padding(AppSpacing.md)
        .background(
            ZStack {
                RoundedRectangle(cornerRadius: 16)
                    .fill(bannerColor)

                // Subtle gradient overlay
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [.white.opacity(0.1), .clear],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
            }
        )
        .shadow(color: bannerColor.opacity(0.3), radius: 10, x: 0, y: 4)
        .shadow(color: .black.opacity(0.1), radius: 6, x: 0, y: 2)
        .transition(.move(edge: .top).combined(with: .opacity).combined(with: .scale(scale: 0.95, anchor: .center)))
    }

    private var bannerColor: Color {
        switch error {
        case .connectionLost:
            return AppColors.warning
        case .serverError, .timeout:
            return AppColors.error
        case .insufficientResources:
            return AppColors.info
        case .invalidOperation:
            return AppColors.error
        }
    }
}

// MARK: - Preview
#if DEBUG
struct ErrorRecoveryView_Previews: PreviewProvider {
    static var previews: some View {
        ZStack {
            AppColors.background
                .ignoresSafeArea()

            VStack(spacing: AppSpacing.xl) {
                Text("Error Recovery Components")
                    .font(.appLargeTitle)
                    .foregroundColor(AppColors.primaryText)

                // Connection lost error
                ErrorRecoveryView(
                    error: .connectionLost,
                    onRetry: { print("Retry") },
                    onDismiss: { print("Dismiss") }
                )
                .padding(AppSpacing.md)

                // Insufficient resources error
                ErrorRecoveryView(
                    error: .insufficientResources(resource: "energy", required: 50, available: 20),
                    onRetry: nil,
                    onDismiss: { print("Dismiss") }
                )
                .padding(AppSpacing.md)

                // Error banner
                ErrorBanner(
                    error: .serverError(message: "Something went wrong"),
                    onDismiss: { print("Dismiss banner") }
                )
                .padding(.horizontal, AppSpacing.md)

                // Connection banner
                ErrorBanner(
                    error: .connectionLost,
                    onDismiss: { print("Dismiss banner") }
                )
                .padding(.horizontal, AppSpacing.md)
            }
            .padding()
        }
    }
}
#endif
