import SwiftUI

struct VODDetailView: View {
    let vodItem: VODItem
    let allVersions: [VODItem]  // All available versions of this movie
    @EnvironmentObject var appState: AppState
    @State private var isShowingPlayer: Bool = false
    @State private var resumePosition: TimeInterval? = nil
    @State private var selectedVersion: VODItem

    init(vodItem: VODItem, allVersions: [VODItem]? = nil) {
        self.vodItem = vodItem
        self.allVersions = allVersions ?? [vodItem]
        self._selectedVersion = State(initialValue: vodItem)
    }

    private var watchHistoryEntry: WatchHistoryEntry? {
        appState.getWatchHistoryEntry(forId: selectedVersion.id)
    }

    private var hasMultipleVersions: Bool {
        allVersions.count > 1
    }

    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()

            HStack(spacing: 80) {
                if let iconURL = vodItem.iconURLObject {
                    AsyncImage(url: iconURL) { phase in
                        switch phase {
                        case .empty:
                            posterPlaceholder
                        case .success(let image):
                            image
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                                .frame(width: 600, height: 900)
                                .clipShape(RoundedRectangle(cornerRadius: 20))
                                .shadow(radius: 20)
                        case .failure:
                            posterPlaceholder
                        @unknown default:
                            posterPlaceholder
                        }
                    }
                } else {
                    posterPlaceholder
                }

                VStack(alignment: .leading, spacing: 40) {
                    VStack(alignment: .leading, spacing: 20) {
                        Text(vodItem.name)
                            .font(.system(size: 60, weight: .bold))
                            .foregroundColor(.white)

                        if let category = vodItem.categoryID {
                            HStack {
                                Image(systemName: "folder.fill")
                                Text(category)
                            }
                            .font(.title2)
                            .foregroundColor(.gray)
                        }

                        if let description = vodItem.description {
                            Text(description)
                                .font(.title3)
                                .foregroundColor(.white.opacity(0.8))
                                .lineLimit(5)
                        }

                        HStack(spacing: 30) {
                            if let duration = vodItem.duration {
                                Label(duration, systemImage: "clock")
                                    .font(.title3)
                                    .foregroundColor(.gray)
                            }

                            if let rating = vodItem.rating {
                                Label(rating, systemImage: "star.fill")
                                    .font(.title3)
                                    .foregroundColor(.gray)
                            }
                        }
                    }

                    // Version selector (when multiple versions available)
                    if hasMultipleVersions {
                        VStack(alignment: .leading, spacing: 15) {
                            Text("Available Versions")
                                .font(.title2)
                                .fontWeight(.semibold)
                                .foregroundColor(.white)

                            HStack(spacing: 15) {
                                ForEach(allVersions, id: \.id) { version in
                                    Button(action: {
                                        selectedVersion = version
                                    }) {
                                        VStack(spacing: 8) {
                                            Text(version.qualityLabel)
                                                .font(.title3)
                                                .fontWeight(.bold)

                                            if version.name != vodItem.name {
                                                Text(version.name)
                                                    .font(.caption)
                                                    .lineLimit(1)
                                            }
                                        }
                                        .foregroundColor(selectedVersion.id == version.id ? .white : .gray)
                                        .frame(width: 150, height: 80)
                                        .background(
                                            selectedVersion.id == version.id
                                                ? Color.blue
                                                : Color.white.opacity(0.1)
                                        )
                                        .cornerRadius(10)
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 10)
                                                .stroke(
                                                    selectedVersion.id == version.id ? Color.blue : Color.clear,
                                                    lineWidth: 3
                                                )
                                        )
                                    }
                                    .buttonStyle(.plain)
                                }
                            }
                        }
                    }

                    HStack(spacing: 20) {
                        // Resume button (if watch history exists)
                        if let entry = watchHistoryEntry {
                            Button(action: {
                                resumePosition = entry.progress
                                isShowingPlayer = true
                            }) {
                                HStack {
                                    Image(systemName: "play.fill")
                                        .font(.title)
                                    Text("Resume at \(entry.formattedProgress)")
                                        .font(.title)
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(width: 400, height: 100)
                                .background(Color.blue)
                                .cornerRadius(15)
                            }
                            .buttonStyle(.plain)

                            Button(action: {
                                resumePosition = nil
                                isShowingPlayer = true
                            }) {
                                HStack {
                                    Image(systemName: "arrow.counterclockwise")
                                        .font(.title)
                                    Text("Start Over")
                                        .font(.title)
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(width: 300, height: 100)
                                .background(Color.gray.opacity(0.5))
                                .cornerRadius(15)
                            }
                            .buttonStyle(.plain)
                        } else {
                            // Play button (no history)
                            Button(action: {
                                resumePosition = nil
                                isShowingPlayer = true
                            }) {
                                HStack {
                                    Image(systemName: "play.fill")
                                        .font(.title)
                                    Text("Play")
                                        .font(.title)
                                        .fontWeight(.semibold)
                                }
                                .foregroundColor(.white)
                                .frame(width: 300, height: 100)
                                .background(Color.blue)
                                .cornerRadius(15)
                            }
                            .buttonStyle(.plain)
                        }
                    }

                    Spacer()
                }
                .frame(maxWidth: 800, alignment: .leading)
            }
            .padding(80)
        }
        .toolbar(.hidden, for: .navigationBar)
        .fullScreenCover(isPresented: $isShowingPlayer) {
            VLCVideoPlayerView(
                vodItem: selectedVersion,
                startPosition: resumePosition,
                onProgressUpdate: { progress, duration in
                    let entry = WatchHistoryEntry(
                        from: selectedVersion,
                        duration: duration,
                        progress: progress
                    )
                    Task {
                        await appState.updateWatchHistory(entry)
                    }
                }
            )
            .ignoresSafeArea()
        }
    }

    private var posterPlaceholder: some View {
        ZStack {
            Color.gray.opacity(0.3)
            Image(systemName: "film")
                .font(.system(size: 120))
                .foregroundColor(.white.opacity(0.5))
        }
        .frame(width: 600, height: 900)
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .shadow(radius: 20)
    }
}
