//
//  AccountDeletionView.swift
//  lichunWebsocket
//
//  Created for BaoLife Phase 7 - GDPR Compliance
//  Account deletion functionality with 30-day grace period
//

import SwiftUI

struct AccountDeletionView: View {
    @EnvironmentObject var webSocketService: WebSocketService
    @Environment(\.presentationMode) var presentationMode

    @State private var confirmationText: String = ""
    @State private var showingFinalConfirmation = false
    @State private var deletionStatus: DeletionStatus = .idle
    @State private var errorMessage: String = ""
    @State private var agreedToTerms = false

    enum DeletionStatus {
        case idle
        case processing
        case scheduled
        case error
    }

    var body: some View {
        NavigationView {
            ScrollView(showsIndicators: false) {
                VStack(spacing: AppSpacing.md) {
                    // Scheduled-deletion banner: shown whenever the account is
                    // currently scheduled for deletion (within the 30-day grace
                    // period). Honors the promise in the grace-period copy by
                    // offering an explicit Cancel right where the user can see it.
                    if let scheduled = webSocketService.deletionScheduledAt {
                        ScheduledDeletionBanner(
                            scheduledAt: scheduled,
                            onCancel: cancelScheduledDeletion
                        )
                        .padding(.horizontal, AppSpacing.md)
                        .padding(.top, AppSpacing.md)
                    }

                    // Warning Icon
                    Image(systemName: "exclamationmark.triangle.fill")
                        .font(.system(size: 60))
                        .foregroundColor(AppColors.error)
                        .padding(.top, AppSpacing.lg)

                    // Title and Warning
                    VStack(spacing: AppSpacing.sm) {
                        Text("Delete Account")
                            .font(.appTitle)
                            .foregroundColor(AppColors.primaryText)

                        Text("This action will permanently delete your BaoLife account and all associated data.")
                            .font(.appBody)
                            .foregroundColor(AppColors.error.darker(by: 0.2))
                            .fontWeight(.semibold)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, AppSpacing.md)
                    }

                    // What Will Be Deleted Section
                    VStack(alignment: .leading, spacing: AppSpacing.md) {
                        Text("What Will Be Deleted")
                            .font(.appHeadline)
                            .foregroundColor(AppColors.primaryText)
                            .padding(.horizontal, AppSpacing.md)

                        VStack(spacing: AppSpacing.sm) {
                            DeletedDataRow(icon: "person.fill.xmark", title: "Your Account", description: "Username, email, profile")
                            DeletedDataRow(icon: "figure.walk", title: "All Characters", description: "Every character you've created")
                            DeletedDataRow(icon: "chart.bar.fill", title: "Game Progress", description: "Achievements, statistics, records")
                            DeletedDataRow(icon: "heart.fill", title: "Relationships", description: "All in-game relationships")
                            DeletedDataRow(icon: "bubble.left.fill", title: "Conversations", description: "All chat history")
                            DeletedDataRow(icon: "star.fill", title: "Virtual Items", description: "Diamonds, currency, purchased items")
                        }
                        .padding(.horizontal, AppSpacing.md)
                    }
                    .padding(.vertical, AppSpacing.xs)

                    // Grace Period Notice
                    BaseCard(
                        backgroundColor: AppColors.warning.opacity(0.1),
                        borderColor: AppColors.warning.opacity(0.3)
                    ) {
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            HStack(spacing: AppSpacing.xs) {
                                Image(systemName: "clock.fill")
                                    .foregroundColor(AppColors.warning.darker(by: 0.2))
                                Text("30-Day Grace Period")
                                    .font(.appHeadline)
                                    .foregroundColor(AppColors.primaryText)
                            }

                            Text("After you confirm deletion, your account will be deactivated immediately but not permanently deleted for 30 days. During this time:")
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)

                            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                                BulletPoint(text: "You can cancel anytime: tap Cancel Deletion below, or just sign back in")
                                BulletPoint(text: "Your data remains recoverable")
                                BulletPoint(text: "After 30 days, deletion becomes permanent")
                            }
                            .padding(.leading, AppSpacing.xs)
                        }
                    }
                    .padding(.horizontal, AppSpacing.md)

                    // What Will Be Kept
                    BaseCard(
                        backgroundColor: AppColors.info.opacity(0.1),
                        borderColor: AppColors.info.opacity(0.3)
                    ) {
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            HStack(spacing: AppSpacing.xs) {
                                Image(systemName: "info.circle.fill")
                                    .foregroundColor(AppColors.info.darker(by: 0.2))
                                Text("Legal Compliance")
                                    .font(.appHeadline)
                                    .foregroundColor(AppColors.primaryText)
                            }

                            Text("Some information may be retained for legal and compliance purposes:")
                                .font(.appBody)
                                .foregroundColor(AppColors.secondaryText)

                            VStack(alignment: .leading, spacing: AppSpacing.xs) {
                                BulletPoint(text: "Purchase records (required for tax compliance)")
                                BulletPoint(text: "Anonymized analytics data")
                                BulletPoint(text: "Records required by law")
                            }
                            .padding(.leading, AppSpacing.xs)
                        }
                    }
                    .padding(.horizontal, AppSpacing.md)

                    // Status Display
                    if deletionStatus != .idle {
                        BaseCard(
                            backgroundColor: AppColors.surfaceElevated
                        ) {
                            VStack(spacing: AppSpacing.md) {
                                switch deletionStatus {
                                case .processing:
                                    ProgressView()
                                        .scaleEffect(1.5)
                                    Text("Processing deletion request...")
                                        .font(.appBody)
                                        .foregroundColor(AppColors.secondaryText)

                                case .scheduled:
                                    Image(systemName: "checkmark.circle.fill")
                                        .font(.system(size: 50))
                                        .foregroundColor(AppColors.warning)
                                    Text("Deletion Scheduled")
                                        .font(.appHeadline)
                                        .foregroundColor(AppColors.warning.darker(by: 0.2))
                                    Text("Your account will be permanently deleted in 30 days. You can cancel anytime before then by tapping Cancel Deletion, or simply by signing back in.")
                                        .font(.appBody)
                                        .foregroundColor(AppColors.secondaryText)
                                        .multilineTextAlignment(.center)

                                    Button(action: cancelScheduledDeletion) {
                                        HStack(spacing: AppSpacing.xs) {
                                            Image(systemName: "arrow.uturn.backward")
                                            Text("Cancel Deletion")
                                                .fontWeight(.semibold)
                                        }
                                        .font(.appBodyBold)
                                        .foregroundColor(.white)
                                        .frame(maxWidth: .infinity)
                                        .padding()
                                        .background(AppColors.success.darker(by: 0.1))
                                        .cornerRadius(AppSpacing.cornerRadius)
                                    }

                                    Button(action: {
                                        // Logout and close app
                                        webSocketService.disconnect()
                                        presentationMode.wrappedValue.dismiss()
                                    }) {
                                        Text("Logout")
                                            .font(.appBodyBold)
                                            .foregroundColor(.white)
                                            .frame(maxWidth: .infinity)
                                            .padding()
                                            .background(AppColors.secondaryText)
                                            .cornerRadius(AppSpacing.cornerRadius)
                                    }

                                case .error:
                                    Image(systemName: "exclamationmark.triangle.fill")
                                        .font(.system(size: 50))
                                        .foregroundColor(AppColors.error)
                                    Text("Deletion Failed")
                                        .font(.appHeadline)
                                        .foregroundColor(AppColors.error.darker(by: 0.2))
                                    Text(errorMessage)
                                        .font(.appBody)
                                        .foregroundColor(AppColors.secondaryText)
                                        .multilineTextAlignment(.center)

                                case .idle:
                                    EmptyView()
                                }
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)
                    }

                    // Confirmation Section
                    if deletionStatus == .idle {
                        BaseCard(
                            backgroundColor: AppColors.surfaceElevated,
                            borderColor: AppColors.error.opacity(0.3)
                        ) {
                            VStack(alignment: .leading, spacing: AppSpacing.md) {
                                Text("Confirmation Required")
                                    .font(.appHeadline)
                                    .foregroundColor(AppColors.primaryText)

                                VStack(alignment: .leading, spacing: AppSpacing.sm) {
                                    Text("To confirm deletion, type DELETE in capital letters:")
                                        .font(.appBody)
                                        .foregroundColor(AppColors.secondaryText)

                                    TextField("Type DELETE", text: $confirmationText)
                                        .textFieldStyle(RoundedBorderTextFieldStyle())
                                        .autocapitalization(.allCharacters)
                                        .disableAutocorrection(true)

                                    Toggle(isOn: $agreedToTerms) {
                                        Text("I understand this action will delete my account and all data after 30 days")
                                            .font(.appBody)
                                            .foregroundColor(AppColors.secondaryText)
                                    }
                                    .tint(AppColors.error)
                                }
                            }
                        }
                        .padding(.horizontal, AppSpacing.md)

                        // Delete Button
                        Button(action: {
                            showingFinalConfirmation = true
                        }) {
                            HStack(spacing: AppSpacing.xs) {
                                Image(systemName: "trash.fill")
                                Text("Delete My Account")
                                    .fontWeight(.semibold)
                            }
                            .font(.appBodyBold)
                            .foregroundColor(.white)
                            .frame(maxWidth: .infinity)
                            .padding()
                            .background(isDeleteEnabled ? AppColors.error.darker(by: 0.1) : AppColors.disabledText)
                            .cornerRadius(AppSpacing.cornerRadius)
                        }
                        .disabled(!isDeleteEnabled)
                        .padding(.horizontal, AppSpacing.md)
                        .alert(isPresented: $showingFinalConfirmation) {
                            Alert(
                                title: Text("Final Confirmation"),
                                message: Text("Are you absolutely sure you want to delete your account? This cannot be undone after 30 days."),
                                primaryButton: .destructive(Text("Yes, Delete")) {
                                    deleteAccount()
                                },
                                secondaryButton: .cancel()
                            )
                        }
                    }

                    // Alternative Options
                    if deletionStatus == .idle {
                        VStack(alignment: .leading, spacing: AppSpacing.sm) {
                            Text("Consider These Alternatives")
                                .font(.appHeadline)
                                .foregroundColor(AppColors.primaryText)
                                .padding(.horizontal, AppSpacing.md)

                            VStack(spacing: AppSpacing.sm) {
                                AlternativeOptionRow(
                                    icon: "pause.circle.fill",
                                    title: "Take a Break",
                                    description: "Just log out. Your data will be safe when you return."
                                )
                                AlternativeOptionRow(
                                    icon: "square.and.arrow.down.fill",
                                    title: "Export Your Data",
                                    description: "Download a copy before deleting."
                                )
                                AlternativeOptionRow(
                                    icon: "envelope.fill",
                                    title: "Contact Support",
                                    description: "We can help with account issues."
                                )
                            }
                            .padding(.horizontal, AppSpacing.md)
                        }
                        .padding(.vertical, AppSpacing.xs)
                    }

                    Spacer(minLength: AppSpacing.xl)
                }
                .padding(.bottom, AppSpacing.xl)
            }
            .background(AppColors.background)
            .navigationBarTitle("Delete Account", displayMode: .inline)
            .navigationBarItems(
                leading: deletionStatus == .idle ? Button("Cancel") {
                    presentationMode.wrappedValue.dismiss()
                } : nil
            )
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("AccountDeleted"))) { notification in
                deletionStatus = .scheduled
                errorMessage = ""
                if let message = notification.userInfo?["message"] as? String {
                    ToastManager.shared.show(.success, message: message)
                }
            }
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("AccountDeletionFailed"))) { notification in
                deletionStatus = .error
                errorMessage = notification.userInfo?["error"] as? String ?? "Account deletion failed."
            }
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("AccountDeletionCancelled"))) { _ in
                // Cancel succeeded (explicit Cancel button or auto-cancel-on-login):
                // return the screen to its normal state. The success toast is shown
                // centrally by WebSocketService.
                deletionStatus = .idle
                errorMessage = ""
                confirmationText = ""
                agreedToTerms = false
            }
            .onAppear {
                // Reflect an already-scheduled deletion (e.g. reopening this screen
                // during the grace period) so the Cancel affordance is visible.
                if webSocketService.deletionScheduledAt != nil {
                    deletionStatus = .scheduled
                }
            }
        }
    }

    // MARK: - Computed Properties

    private var isDeleteEnabled: Bool {
        confirmationText == "DELETE" && agreedToTerms
    }

    // MARK: - Functions

    private func deleteAccount() {
        deletionStatus = .processing
        errorMessage = ""

        // Send deletion request via WebSocket
        webSocketService.sendMessage(message: WebSocketCommands.deleteAccount(confirmation: confirmationText))

        // Timeout after 30 seconds
        DispatchQueue.main.asyncAfter(deadline: .now() + 30.0) {
            if deletionStatus == .processing {
                deletionStatus = .error
                errorMessage = "Request timed out. Please check your connection and try again."
            }
        }
    }

    private func cancelScheduledDeletion() {
        // Send the explicit cancel command. The server clears the marker and
        // replies with `accountDeletionCancelled`, handled via the onReceive
        // above (which resets this screen) and WebSocketService (which clears
        // `deletionScheduledAt` and shows the success toast).
        webSocketService.cancelAccountDeletion()
    }
}

// MARK: - Scheduled Deletion Banner

/// Persistent notice shown while the account is scheduled for deletion, with an
/// inline Cancel action. Surfaced inside AccountDeletionView (which observes
/// WebSocketService), so it requires no edits to shared/global views.
struct ScheduledDeletionBanner: View {
    let scheduledAt: String
    let onCancel: () -> Void

    private var formattedDate: String {
        let iso = ISO8601DateFormatter()
        iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        let date = iso.date(from: scheduledAt)
            ?? ISO8601DateFormatter().date(from: scheduledAt)
        guard let date else { return scheduledAt }
        let out = DateFormatter()
        out.dateStyle = .long
        out.timeStyle = .none
        return out.string(from: date)
    }

    var body: some View {
        BaseCard(
            backgroundColor: AppColors.error.opacity(0.12),
            borderColor: AppColors.error.opacity(0.4)
        ) {
            VStack(alignment: .leading, spacing: AppSpacing.sm) {
                HStack(spacing: AppSpacing.xs) {
                    Image(systemName: "exclamationmark.octagon.fill")
                        .foregroundColor(AppColors.error)
                    Text("Account Scheduled for Deletion")
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                }

                Text("Your account is scheduled to be permanently deleted on \(formattedDate). Cancel anytime before then to keep your account.")
                    .font(.appBody)
                    .foregroundColor(AppColors.secondaryText)

                Button(action: onCancel) {
                    HStack(spacing: AppSpacing.xs) {
                        Image(systemName: "arrow.uturn.backward")
                        Text("Cancel Deletion")
                            .fontWeight(.semibold)
                    }
                    .font(.appBodyBold)
                    .foregroundColor(.white)
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(AppColors.success.darker(by: 0.1))
                    .cornerRadius(AppSpacing.cornerRadius)
                }
            }
        }
    }
}

// MARK: - Supporting Views

struct DeletedDataRow: View {
    let icon: String
    let title: String
    let description: String

    var body: some View {
        HStack(alignment: .top, spacing: AppSpacing.sm) {
            Image(systemName: icon)
                .font(.system(size: 20))
                .foregroundColor(AppColors.error)
                .frame(width: 30)

            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.appBodyBold)
                    .foregroundColor(AppColors.primaryText)
                Text(description)
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()
        }
        .padding(AppSpacing.md)
        .background(AppColors.error.opacity(0.08))
        .cornerRadius(AppSpacing.cornerRadius)
    }
}

struct BulletPoint: View {
    let text: String

    var body: some View {
        HStack(alignment: .top, spacing: AppSpacing.xs) {
            Text("•")
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
            Text(text)
                .font(.appBody)
                .foregroundColor(AppColors.secondaryText)
        }
    }
}

struct AlternativeOptionRow: View {
    let icon: String
    let title: String
    let description: String

    var body: some View {
        HStack(alignment: .top, spacing: AppSpacing.sm) {
            Image(systemName: icon)
                .font(.system(size: 20))
                .foregroundColor(AppColors.success)
                .frame(width: 30)

            VStack(alignment: .leading, spacing: 4) {
                Text(title)
                    .font(.appBodyBold)
                    .foregroundColor(AppColors.primaryText)
                Text(description)
                    .font(.appCaption)
                    .foregroundColor(AppColors.secondaryText)
            }

            Spacer()
        }
        .padding(AppSpacing.md)
        .background(AppColors.success.opacity(0.08))
        .cornerRadius(AppSpacing.cornerRadius)
    }
}

// MARK: - Preview
// Preview removed - requires backend connection
