import SwiftUI

struct ContentView: View {
    @StateObject private var viewModel = DownloadViewModel()

    var body: some View {
        ZStack {
            LinearGradient(
                colors: [
                    Color(red: 0.10, green: 0.12, blue: 0.20),
                    Color(red: 0.08, green: 0.22, blue: 0.36),
                    Color(red: 0.18, green: 0.14, blue: 0.35)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()

            VStack(spacing: 18) {
                headerCard
                controlsCard
            }
            .padding(20)
        }
        .alert("Download error", isPresented: $viewModel.showErrorAlert) {
            Button("OK", role: .cancel) {}
        } message: {
            Text(viewModel.errorMessage)
        }
    }

    private var headerCard: some View {
        GlassCard {
            HStack {
                VStack(alignment: .leading, spacing: 6) {
                    Text("YouToDownLoad")
                        .font(.system(size: 30, weight: .bold, design: .rounded))
                    Text("YouTube to MP3 Downloader")
                        .foregroundStyle(.secondary)
                }
                Spacer()
                statusBadge
            }
        }
    }

    private var controlsCard: some View {
        GlassCard {
            VStack(spacing: 14) {
                Group {
                    labeledField("YouTube URL", text: $viewModel.youtubeURL, placeholder: "https://www.youtube.com/watch?v=...")
                    HStack(spacing: 12) {
                        VStack(alignment: .leading, spacing: 6) {
                            Text("Output folder")
                                .font(.caption)
                                .foregroundStyle(.secondary)
                            HStack(spacing: 8) {
                                TextField("/Users/you/Downloads/YouToDownLoad", text: $viewModel.outputDirectory)
                                    .textFieldStyle(.plain)
                                    .padding(10)
                                    .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10))
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 10)
                                            .stroke(Color.white.opacity(0.25), lineWidth: 1)
                                    )
                                Button("Browse...") {
                                    viewModel.pickOutputDirectory()
                                }
                                .buttonStyle(SecondaryGlassButtonStyle())
                                .frame(maxWidth: 120)
                            }
                        }
                        .frame(maxWidth: .infinity)
                        labeledField("Quality", text: $viewModel.quality, placeholder: "0")
                            .frame(maxWidth: 140)
                        labeledField("Format", text: $viewModel.format, placeholder: "mp3")
                            .frame(maxWidth: 140)
                    }
                }

                HStack {
                    Toggle("Playlist", isOn: $viewModel.allowPlaylist)
                    Toggle("Embed metadata", isOn: $viewModel.embedMetadata)
                    Toggle("Write thumbnail", isOn: $viewModel.writeThumbnail)
                }
                .toggleStyle(.switch)

                HStack(spacing: 10) {
                    Button {
                        viewModel.download()
                    } label: {
                        Label("Download", systemImage: "arrow.down.circle.fill")
                            .frame(maxWidth: .infinity)
                    }
                    .buttonStyle(PrimaryGlassButtonStyle())
                    .disabled(viewModel.isRunning)

                    Button {
                        viewModel.stop()
                    } label: {
                        Label("Stop", systemImage: "stop.circle.fill")
                            .frame(maxWidth: .infinity)
                    }
                    .buttonStyle(SecondaryGlassButtonStyle())
                    .disabled(!viewModel.isRunning)
                }

                VStack(alignment: .leading, spacing: 8) {
                    HStack {
                        Text("Progress")
                            .font(.caption)
                            .foregroundStyle(.secondary)
                        Spacer()
                        Text(viewModel.progressText)
                            .font(.caption.monospacedDigit())
                            .foregroundStyle(.secondary)
                    }
                    ProgressView(value: viewModel.downloadProgress, total: 1.0)
                        .progressViewStyle(.linear)
                        .tint(.cyan)
                }
            }
        }
    }

    private var statusBadge: some View {
        Text(viewModel.statusText)
            .font(.system(size: 13, weight: .semibold, design: .rounded))
            .padding(.horizontal, 10)
            .padding(.vertical, 6)
            .background(.ultraThinMaterial, in: Capsule())
            .overlay(
                Capsule()
                    .stroke(Color.white.opacity(0.30), lineWidth: 1)
            )
    }

    private func labeledField(_ title: String, text: Binding<String>, placeholder: String) -> some View {
        VStack(alignment: .leading, spacing: 6) {
            Text(title)
                .font(.caption)
                .foregroundStyle(.secondary)
            TextField(placeholder, text: text)
                .textFieldStyle(.plain)
                .padding(10)
                .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 10))
                .overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(Color.white.opacity(0.25), lineWidth: 1)
                )
        }
        .frame(maxWidth: .infinity)
    }
}

private struct GlassCard<Content: View>: View {
    @ViewBuilder var content: Content

    var body: some View {
        content
            .padding(16)
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 24, style: .continuous))
            .overlay(
                RoundedRectangle(cornerRadius: 24, style: .continuous)
                    .stroke(
                        LinearGradient(
                            colors: [Color.white.opacity(0.36), Color.white.opacity(0.08)],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1
                    )
            )
            .shadow(color: .black.opacity(0.25), radius: 24, x: 0, y: 10)
    }
}

private struct PrimaryGlassButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(.vertical, 10)
            .background(
                LinearGradient(
                    colors: [Color.cyan.opacity(0.8), Color.blue.opacity(0.65)],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                ),
                in: RoundedRectangle(cornerRadius: 12, style: .continuous)
            )
            .overlay(
                RoundedRectangle(cornerRadius: 12, style: .continuous)
                    .stroke(Color.white.opacity(0.28), lineWidth: 1)
            )
            .scaleEffect(configuration.isPressed ? 0.99 : 1)
    }
}

private struct SecondaryGlassButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .padding(.vertical, 10)
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 12, style: .continuous))
            .overlay(
                RoundedRectangle(cornerRadius: 12, style: .continuous)
                    .stroke(Color.white.opacity(0.22), lineWidth: 1)
            )
            .scaleEffect(configuration.isPressed ? 0.99 : 1)
    }
}
