import SwiftUI
import LocalAuthentication

// MARK: - Lock Screen

struct AppLockView: View {
    @Environment(\.nahbarTheme) var theme
    @EnvironmentObject var lockManager: AppLockManager

    @State private var entered = ""
    @State private var showError = false
    @State private var errorOffset: CGFloat = 0

    private let pinLength = 6

    var body: some View {
        ZStack {
            theme.backgroundPrimary.ignoresSafeArea()

            VStack(spacing: 0) {
                Spacer()

                // Title
                VStack(spacing: 6) {
                    Text("nahbar")
                        .font(.system(size: 32, weight: .light, design: theme.displayDesign))
                        .foregroundStyle(theme.contentPrimary)
                    Text("Code eingeben")
                        .font(.system(size: 15))
                        .foregroundStyle(theme.contentSecondary)
                }

                Spacer().frame(height: 44)

                // PIN dots
                HStack(spacing: 20) {
                    ForEach(0..<pinLength, id: \.self) { i in
                        Circle()
                            .fill(i < entered.count ? theme.accent : Color.clear)
                            .frame(width: 14, height: 14)
                            .overlay(
                                Circle().stroke(
                                    i < entered.count ? theme.accent : theme.contentTertiary,
                                    lineWidth: 1.5
                                )
                            )
                    }
                }
                .offset(x: errorOffset)

                Spacer().frame(height: 14)

                // Error message — fixed height to avoid layout shift
                Text(showError ? "Falscher Code" : " ")
                    .font(.system(size: 13))
                    .foregroundStyle(.red.opacity(0.8))
                    .animation(.easeInOut(duration: 0.2), value: showError)

                Spacer()

                // Number pad
                PINPadView { key in handleKey(key) }
                    .padding(.horizontal, 44)

                Spacer().frame(height: 24)

                // Biometric button
                if lockManager.biometricType != .none {
                    Button { tryBiometric() } label: {
                        Image(systemName: lockManager.biometricType == .faceID ? "faceid" : "touchid")
                            .font(.system(size: 34, weight: .light))
                            .foregroundStyle(theme.accent)
                    }
                    .padding(.bottom, 44)
                } else {
                    Spacer().frame(height: 44)
                }
            }
        }
        .onAppear { tryBiometric() }
    }

    private func handleKey(_ key: PINKey) {
        switch key {
        case .digit(let d):
            guard entered.count < pinLength else { return }
            entered.append(d)
            if entered.count == pinLength { verify() }
        case .delete:
            if !entered.isEmpty { entered.removeLast() }
        }
    }

    private func verify() {
        if lockManager.verifyPIN(entered) {
            lockManager.unlock()
        } else {
            entered = ""
            animateShake()
            showError = true
            DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
                withAnimation { showError = false }
            }
        }
    }

    private func tryBiometric() {
        lockManager.authenticateWithBiometrics { success in
            if success { lockManager.unlock() }
        }
    }

    private func animateShake() {
        let pattern: [(CGFloat, Double)] = [(10,0), (-10,0.07), (6,0.14), (-4,0.21), (0,0.28)]
        for (offset, delay) in pattern {
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
                withAnimation(.easeInOut(duration: 0.07)) { errorOffset = offset }
            }
        }
    }
}

// MARK: - PIN Key Model

enum PINKey {
    case digit(Character)
    case delete
}

// MARK: - PIN Pad

struct PINPadView: View {
    @Environment(\.nahbarTheme) var theme
    let onKey: (PINKey) -> Void

    private let rows: [[String]] = [
        ["1", "2", "3"],
        ["4", "5", "6"],
        ["7", "8", "9"],
        ["",  "0", "⌫"]
    ]

    var body: some View {
        VStack(spacing: 14) {
            ForEach(rows, id: \.self) { row in
                HStack(spacing: 18) {
                    ForEach(row, id: \.self) { key in
                        pinButton(for: key)
                    }
                }
            }
        }
    }

    @ViewBuilder
    private func pinButton(for key: String) -> some View {
        if key.isEmpty {
            Color.clear.frame(width: 80, height: 80).allowsHitTesting(false)
        } else if key == "⌫" {
            Button { onKey(.delete) } label: {
                Image(systemName: "delete.left")
                    .font(.system(size: 20, weight: .light))
                    .foregroundStyle(theme.contentPrimary)
                    .frame(width: 80, height: 80)
            }
        } else {
            Button { onKey(.digit(key.first!)) } label: {
                Text(key)
                    .font(.system(size: 26, weight: .light, design: theme.displayDesign))
                    .foregroundStyle(theme.contentPrimary)
                    .frame(width: 80, height: 80)
                    .background(theme.surfaceCard)
                    .clipShape(Circle())
                    .overlay(Circle().stroke(theme.borderSubtle, lineWidth: 1))
            }
        }
    }
}
