import SwiftUI

struct TagDetailView: View {
    let tag: Tag
    @EnvironmentObject var linkViewModel: LinkViewModel
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) private var viewContext
    @State private var showingEditTag = false
    @State private var showingDeleteAlert = false
    @State private var deleteErrorMessage = ""
    @State private var showingDeleteError = false
    @State private var showingDropdownMenu = false

    var canDeleteTag: Bool {
        tag.linkCount == 0
    }

    var body: some View {
        ZStack {
            ScrollView {
                VStack(alignment: .leading, spacing: 16) {
                    titleAndActionsSection
                    headerSection
                    statisticsSection
                    linksSection
                }
                .padding()
            }
            .navigationBarHidden(true)

            // Dropdown menu overlay
            if showingDropdownMenu {
                Color.black.opacity(0.001)
                    .onTapGesture {
                        showingDropdownMenu = false
                    }
                    .ignoresSafeArea()

                VStack {
                        HStack {
                            Spacer()
                            dropdownMenu
                                .padding(.top, 100)
                                .padding(.trailing, 16)
                        }
                        Spacer()
                    }
                }
            }
        .sheet(isPresented: $showingEditTag) {
            TagEditView(tag: tag)
                .environment(\.managedObjectContext, viewContext)
        }
        .alert("delete_tag", isPresented: $showingDeleteAlert) {
            Button("cancel", role: .cancel) { }
            Button("delete", role: .destructive) {
                deleteTag()
            }
        } message: {
            Text("delete_tag_confirmation")
        }
        .alert("error", isPresented: $showingDeleteError) {
            Button("ok") { }
        } message: {
            Text(deleteErrorMessage)
        }
    }

    private var titleAndActionsSection: some View {
        HStack {
            Button(action: {
                presentationMode.wrappedValue.dismiss()
            }) {
                HStack(spacing: 4) {
                    Image(systemName: "chevron.left")
                        .font(.system(size: 16, weight: .medium))
                    Text("Link Details")
                        .font(.system(size: 16))
                }
                .foregroundColor(.blue)
            }

            Spacer()

            Text("tag_details")
                .font(.system(size: 16))
                .fontWeight(.bold)

            Spacer()

            Button(action: {
                showingDropdownMenu.toggle()
            }) {
                Image(systemName: "ellipsis")
                    .font(.system(size: 18, weight: .medium))
                    .foregroundColor(.blue)
                    .frame(width: 30, height: 30)
            }
        }
        .padding(.horizontal, 16)
        .padding(.top, 8)
    }

    private var dropdownMenu: some View {
        VStack(alignment: .leading, spacing: 0) {
            Button(action: {
                showingDropdownMenu = false
                showingEditTag = true
            }) {
                HStack {
                    Image(systemName: "pencil")
                        .foregroundColor(.blue)
                        .frame(width: 20)
                    Text("edit_tag")
                        .foregroundColor(.primary)
                    Spacer()
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)
            }

            Divider()

            Button(action: {
                showingDropdownMenu = false
                if canDeleteTag {
                    showingDeleteAlert = true
                }
            }) {
                HStack {
                    Image(systemName: "trash")
                        .foregroundColor(canDeleteTag ? .red : .gray)
                    Text("delete_tag")
                        .foregroundColor(canDeleteTag ? .red : .gray)
                    Spacer()
                }
                .padding(.horizontal, 16)
                .padding(.vertical, 12)
            }
            .disabled(!canDeleteTag)
        }
        .background(Color(.systemBackground))
        .cornerRadius(10)
        .shadow(color: Color.black.opacity(0.1), radius: 10, x: 0, y: 5)
        .frame(width: 160)
    }

    private var headerSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                Text(tag.name)
                    .font(.title2)
                    .fontWeight(.semibold)

                Spacer()

                Text("tag")
                    .font(.caption)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(6)
            }

            if let description = tag.tagDescription, !description.isEmpty {
                Text(description)
                    .font(.body)
                    .foregroundColor(.secondary)
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }

    private var statisticsSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("statistics")
                .font(.headline)

            HStack(spacing: 16) {
                SimpleStatCard(
                    title: "associated_links",
                    value: "\(tag.linkCount)",
                    icon: "link"
                )

                SimpleStatCard(
                    title: "created",
                    value: tag.createdAt.formatted(.dateTime.year().month().day()),
                    icon: "calendar"
                )
            }
        }
    }

    private var linksSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Text("links")
                    .font(.headline)

                Spacer()

                Text("\(tag.sortedLinks.count)")
                    .font(.caption)
                    .foregroundColor(.secondary)
            }

            if tag.sortedLinks.isEmpty {
                VStack(spacing: 12) {
                    Image(systemName: "link.badge.plus")
                        .font(.system(size: 40))
                        .foregroundColor(.gray)

                    Text("no_links_with_tag")
                        .font(.body)
                        .foregroundColor(.secondary)
                        .multilineTextAlignment(.center)
                }
                .frame(maxWidth: .infinity)
                .padding(.vertical, 40)
                .background(Color(.systemGray6))
                .cornerRadius(12)
            } else {
                LazyVStack(spacing: 12) {
                    ForEach(tag.sortedLinks, id: \.id) { link in
                        NavigationLink(destination: LinkDetailView(link: link)) {
                            TagLinkRowView(link: link)
                        }
                        .buttonStyle(PlainButtonStyle())
                    }
                }
            }
        }
    }

    private func deleteTag() {
        guard canDeleteTag else {
            deleteErrorMessage = NSLocalizedString("cannot_delete_tag_with_links", comment: "Cannot delete tag with associated links")
            showingDeleteError = true
            return
        }

        viewContext.delete(tag)

        do {
            try viewContext.save()
            linkViewModel.fetchLinks() // Refresh the links list
            presentationMode.wrappedValue.dismiss()
        } catch {
            deleteErrorMessage = error.localizedDescription
            showingDeleteError = true
        }
    }
}

// Helper view for displaying links in the tag detail
struct TagLinkRowView: View {
    let link: Link

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            HStack {
                // Link type indicator
                Image(systemName: linkTypeIcon)
                    .foregroundColor(linkTypeColor)
                    .frame(width: 20)

                VStack(alignment: .leading, spacing: 4) {
                    Text(link.alias)
                        .font(.headline)
                        .foregroundColor(.primary)

                    if let description = link.linkDescription, !description.isEmpty {
                        Text(description)
                            .font(.caption)
                            .foregroundColor(.secondary)
                            .lineLimit(2)
                    } else if let url = link.originalURL {
                        Text(url)
                            .font(.caption)
                            .foregroundColor(.blue)
                            .lineLimit(1)
                    }
                }

                Spacer()

                VStack(alignment: .trailing, spacing: 2) {
                    Text("\(link.clickCount)")
                        .font(.title3)
                        .fontWeight(.semibold)
                        .foregroundColor(.blue)

                    Text("clicks")
                        .font(.caption2)
                        .foregroundColor(.secondary)
                }
            }

            // Tags (if any)
            if !link.sortedTags.isEmpty {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(spacing: 4) {
                        ForEach(link.sortedTags, id: \.id) { tag in
                            Text(tag.name)
                                .font(.caption2)
                                .padding(.horizontal, 6)
                                .padding(.vertical, 2)
                                .background(Color.blue.opacity(0.2))
                                .foregroundColor(.blue)
                                .cornerRadius(4)
                        }
                    }
                }
            }
        }
        .padding()
        .background(Color(.systemGray6))
        .cornerRadius(12)
    }

    private var linkTypeIcon: String {
        switch link.linkTypeEnum {
        case .link:
            return "link"
        case .custom:
            return "doc.text"
        case .template:
            return "doc.badge.plus"
        }
    }

    private var linkTypeColor: Color {
        switch link.linkTypeEnum {
        case .link:
            return .blue
        case .custom:
            return .green
        case .template:
            return .orange
        }
    }
}

// Reuse SimpleStatCard component for consistent styling
struct SimpleStatCard: View {
    let title: String
    let value: String
    let icon: String

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack {
                Image(systemName: icon)
                    .foregroundColor(.blue)
                Text(title)
                    .font(.caption)
                    .foregroundColor(.secondary)
            }

            Text(value)
                .font(.title2)
                .fontWeight(.semibold)
        }
        .padding()
        .frame(maxWidth: .infinity, alignment: .leading)
        .background(Color(.systemGray6))
        .cornerRadius(8)
    }
}

#Preview {
    let context = PersistenceController.preview.container.viewContext
    let tag = Tag(context: context)
    tag.name = "Sample Tag"
    tag.tagDescription = "This is a sample tag description for testing the tag detail view."
    tag.createdAt = Date()

    return TagDetailView(tag: tag)
        .environment(\.managedObjectContext, context)
        .environmentObject(LinkViewModel())
}
