import MetalPetal
import SwiftUI
import UIKit

struct MTIPreviewView: View {
    let previewView: MTIImageView

    var body: some View {
        MTIImageViewRepresentable(previewView: previewView)
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.black)
    }
}

struct LensPreViewer: View {
    // MTIImage 기반으로 변경
    let beforeImage: MTIImage
    let afterImage: MTIImage

    let beforePreview: MTIImageView
    let afterPreview: MTIImageView

    @State private var showingBeforeImage: Bool = false
    @State private var sliderPosition: CGFloat = 0.5
    @State private var isSliderVisible: Bool = true
    @State private var isLongPressing: Bool = false
    @State private var dragOffset: CGFloat = 0
    @State private var isAnimating: Bool = false
    @State private var showLabels: Bool = true
    @State private var showBeforeOnLongPress: Bool = true // 롱 터치 시 Before 이미지 표시 여부

    // 상수 정의
    private let longPressDuration: Double = 0.15
    private let animationDuration: Double = 0.3
    private let buttonSize: CGFloat = 36
    private let sliderWidth: CGFloat = 0.8 // 세로 라인 두께 다시 얇게 조정
    private let handleSize: CGFloat = 36

    // 세련된 컬러 테마
    private let accentColor = Color(red: 0.0, green: 0.7, blue: 0.9)
    private let overlayColor = Color.black.opacity(0.6)
    private let labelTextColor = Color.white
    private let handleGradient = LinearGradient(
        gradient: Gradient(colors: [Color.black, Color.black.opacity(0.8)]),
        startPoint: .topLeading,
        endPoint: .bottomTrailing
    )

    // 세로 라인 그라데이션 (상단과 하단 모두 투명)
    private let lineGradient = LinearGradient(
        gradient: Gradient(stops: [
            .init(color: Color.white.opacity(0), location: 0), // 상단 완전 투명
            .init(color: Color.white.opacity(0.05), location: 0.1), // 상단 10% 지점 거의 투명
            .init(color: Color.white.opacity(0.3), location: 0.3), // 상단 30% 지점 약간 선명
            .init(color: Color.white.opacity(0.7), location: 0.5), // 중앙 부분 가장 선명
            .init(color: Color.white.opacity(0.3), location: 0.7), // 하단 70% 지점 약간 선명
            .init(color: Color.white.opacity(0.05), location: 0.9), // 하단 90% 지점 거의 투명
            .init(color: Color.white.opacity(0), location: 1), // 하단 완전 투명
        ]),
        startPoint: .top,
        endPoint: .bottom
    )

    var body: some View {
        GeometryReader { geometry in
            ZStack {
                // 배경 (After 이미지)
                MTIPreviewView(previewView: afterPreview)
                    .frame(maxWidth: .infinity, maxHeight: .infinity)

                // Before 이미지 (마스크 적용)
                if isSliderVisible {
                    MTIPreviewView(previewView: beforePreview)
                        .frame(maxWidth: .infinity, maxHeight: .infinity)
                        .mask(
                            Rectangle()
                                .frame(width: geometry.size.width * sliderPosition)
                                .position(x: (geometry.size.width * sliderPosition) / 2, y: geometry.size.height / 2)
                        )
                        .opacity(isLongPressing ? 0 : 1)
                        .animation(.easeInOut(duration: 0.1), value: isLongPressing)
                } else if isLongPressing {
                    // 롱프레스시 Before 또는 After 이미지 표시 (showBeforeOnLongPress 상태에 따라)
                    if showBeforeOnLongPress {
                        MTIPreviewView(previewView: beforePreview)
                            .frame(maxWidth: .infinity, maxHeight: .infinity)
                            .transition(.opacity)
                    }
                }

                // 슬라이더 컴포넌트
                if isSliderVisible {
                    ModernSliderDivider(
                        position: $sliderPosition,
                        geometry: geometry,
                        handleSize: handleSize,
                        sliderWidth: sliderWidth,
                        accentColor: accentColor,
                        handleGradient: handleGradient,
                        lineGradient: lineGradient,
                        isLongPressing: isLongPressing,
                        showLabels: showLabels
                    )

                    // 고정된 BEFORE/AFTER 라벨
                    HStack {
                        // BEFORE 라벨 (좌측 고정)
                        Text("BEFORE")
                            .font(Font.nn1050(size: 10))
                            .tracking(1)
                            .foregroundColor(.white)
                            .padding(.vertical, 4)
                            .padding(.horizontal, 8)
                            .background(
                                Capsule()
                                    .fill(Color.black.opacity(0.6))
                                    .overlay(
                                        Capsule()
                                            .stroke(Color.white.opacity(0.2), lineWidth: 1)
                                    )
                            )
                            .opacity(isLongPressing ? 0 : 1)
                            .animation(.easeInOut(duration: 0.1), value: isLongPressing)

                        Spacer()

                        // AFTER 라벨 (우측 고정)
                        Text("AFTER")
                            .font(Font.nn1050(size: 10))
                            .tracking(1)
                            .foregroundColor(.white)
                            .padding(.vertical, 4)
                            .padding(.horizontal, 8)
                            .background(
                                Capsule()
                                    .fill(Color.black.opacity(0.6))
                                    .overlay(
                                        Capsule()
                                            .stroke(Color.white.opacity(0.2), lineWidth: 1)
                                    )
                            )
                            .opacity(isLongPressing ? 0 : 1)
                            .animation(.easeInOut(duration: 0.1), value: isLongPressing)
                    }
                    .padding(.horizontal, 16)
                    .padding(.top, 16)
                    .frame(maxWidth: .infinity, alignment: .top)
                }

                // 단일 토글 버튼 (좌측 하단)
                SingleToggleButton(
                    isSliderVisible: $isSliderVisible,
                    sliderPosition: $sliderPosition,
                    toggleSliderVisibility: toggleSliderVisibility,
                    accentColor: accentColor,
                    buttonSize: buttonSize
                )

                // 정보 오버레이 (상단)
                EnhancedInfoOverlay(
                    isSliderVisible: isSliderVisible,
                    isLongPressing: isLongPressing,
                    showBeforeOnLongPress: showBeforeOnLongPress,
                    accentColor: accentColor
                )
            }
            .contentShape(Rectangle())
            .gesture(
                LongPressGesture(minimumDuration: longPressDuration)
                    .onChanged { _ in
                        withAnimation(.easeInOut(duration: 0.1)) {
                            self.isLongPressing = true
                        }
                    }
                    .onEnded { _ in
                        withAnimation(.easeInOut(duration: 0.1)) {
                            self.isLongPressing = false
                        }
                    }
            )
            .simultaneousGesture(
                TapGesture()
                    .onEnded { _ in
                        // 롱 프레스 중에 탭하면 Before/After 전환 (슬라이더 표시 여부와 상관없이)
                        if isLongPressing {
                            withAnimation(.easeInOut(duration: 0.2)) {
                                showBeforeOnLongPress.toggle()
                            }
                        }
                    }
            )
            .simultaneousGesture(
                DragGesture(minimumDistance: 2)
                    .onChanged { value in
                        if isSliderVisible {
                            // 전체 화면 영역에서 드래그 가능하도록 수정
                            let newPosition = value.location.x / geometry.size.width
                            withAnimation(.interactiveSpring(response: 0.25, dampingFraction: 0.7, blendDuration: 0.1)) {
                                sliderPosition = min(max(newPosition, 0), 1)
                            }
                        }
                    }
            )
            .onTapGesture(count: 2) {
                withAnimation(.easeInOut(duration: animationDuration)) {
                    toggleSliderVisibility()
                }
            }
            .onAppear {
                loadSliderVisibilityState()

                // 초기 애니메이션 효과
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    withAnimation(.easeInOut(duration: 0.8)) {
                        isAnimating = true
                    }
                }

                beforePreview.resizingMode = .aspectFill
                afterPreview.resizingMode = .aspectFill
            }
        }
        .cornerRadius(16)
    }

    private func toggleSliderVisibility() {
        if isSliderVisible {
            // 슬라이더 숨기기
            withAnimation(.easeInOut(duration: animationDuration)) {
                sliderPosition = 1.0 // 전체 After 이미지 표시
                isSliderVisible = false
            }
        } else {
            // 슬라이더 표시
            withAnimation(.easeInOut(duration: animationDuration)) {
                isSliderVisible = true
                sliderPosition = 0.5 // 중간 위치에서 시작
            }
        }

        // 상태 저장
        saveSliderVisibilityState()
    }

    private func resetSliderPosition() {
        // 햅틱 제거
        withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
            sliderPosition = 0.5
        }
    }

    private func saveSliderVisibilityState() {
        UserDefaults.standard.set(!isSliderVisible, forKey: "slideViewHidden")
    }

    private func loadSliderVisibilityState() {
        let isHidden = UserDefaults.standard.bool(forKey: "slideViewHidden")
        isSliderVisible = !isHidden

        if isHidden {
            sliderPosition = 1.0
        }
    }

    // 햅틱 함수는 유지하되 사용하지 않음
    private func hapticFeedback(_: UIImpactFeedbackGenerator.FeedbackStyle) {
        // 함수는 유지하되 내부 코드 제거
    }
}
