import SwiftUI
import ComposeApp

struct TaskCard: View {
    let task: TaskResponse
    let onEdit: () -> Void
    let onCancel: (() -> Void)?
    let onUncancel: (() -> Void)?
    let onMarkInProgress: (() -> Void)?
    let onComplete: (() -> Void)?
    let onArchive: (() -> Void)?
    let onUnarchive: (() -> Void)?

    @State private var isCompletionsExpanded = false
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        VStack(alignment: .leading, spacing: 16) {
            // Header
            HStack(alignment: .top, spacing: 12) {
                VStack(alignment: .leading, spacing: 8) {
                    Text(task.title)
                        .font(.system(size: 18, weight: .bold, design: .rounded))
                        .foregroundColor(Color.appTextPrimary)
                        .lineLimit(2)

                    if task.inProgress {
                        StatusBadge(status: "in_progress")
                    }
                }

                Spacer()

                if let priorityName = task.priorityName, !priorityName.isEmpty {
                    PriorityBadge(priority: priorityName)
                }
            }

            // Description
            if !task.description_.isEmpty {
                Text(task.description_)
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(Color.appTextSecondary)
                    .lineLimit(3)
            }

            // Metadata Pills
            HStack(spacing: 10) {
                if let frequency = task.frequencyDisplayName, !frequency.isEmpty {
                    TaskMetadataPill(
                        icon: "repeat",
                        text: frequency
                    )
                }

                Spacer()

                if let effectiveDate = task.effectiveDueDate {
                    TaskMetadataPill(
                        icon: "calendar",
                        text: effectiveDate.toFormattedDate(),
                        color: effectiveDate.isOverdue() ? Color.appError : Color.appTextSecondary
                    )
                }
            }

            // Completions
            if task.completions.count > 0 {
                OrganicDivider()
                    .padding(.vertical, 4)

                VStack(alignment: .leading, spacing: 12) {
                    HStack(spacing: 10) {
                        ZStack {
                            Circle()
                                .fill(Color.appAccent.opacity(0.12))
                                .frame(width: 28, height: 28)
                            Image(systemName: "checkmark.circle.fill")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(Color.appAccent)
                        }
                        Text("\(L10n.Tasks.completions.capitalized) (\(task.completions.count))")
                            .font(.system(size: 13, weight: .semibold, design: .rounded))
                            .foregroundColor(Color.appTextPrimary)
                        Spacer()
                        Image(systemName: isCompletionsExpanded ? "chevron.up" : "chevron.down")
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                    }
                    .contentShape(Rectangle())
                    .onTapGesture {
                        withAnimation(.spring(response: 0.3, dampingFraction: 0.7)) {
                            isCompletionsExpanded.toggle()
                        }
                    }
                    .accessibilityLabel("Completions (\(task.completions.count))")
                    .accessibilityHint("Double tap to \(isCompletionsExpanded ? "collapse" : "expand") completions")

                    if isCompletionsExpanded {
                        ForEach(task.completions, id: \.id) { completion in
                            CompletionCardView(completion: completion)
                        }
                    }
                }
            }

            // Primary Actions
            if task.showCompletedButton {
                VStack(spacing: 10) {
                    if let onMarkInProgress = onMarkInProgress, !task.inProgress {
                        Button(action: onMarkInProgress) {
                            HStack(spacing: 8) {
                                Image(systemName: "play.circle.fill")
                                    .font(.system(size: 16, weight: .semibold))
                                Text(L10n.Tasks.inProgress)
                                    .font(.system(size: 15, weight: .semibold, design: .rounded))
                            }
                            .frame(maxWidth: .infinity)
                            .frame(height: 48)
                            .foregroundColor(Color.appAccent)
                            .background(
                                RoundedRectangle(cornerRadius: 16, style: .continuous)
                                    .fill(Color.appAccent.opacity(0.12))
                            )
                        }
                    }

                    if task.showCompletedButton, let onComplete = onComplete {
                        Button(action: onComplete) {
                            HStack(spacing: 8) {
                                Image(systemName: "checkmark.circle.fill")
                                    .font(.system(size: 16, weight: .semibold))
                                Text(L10n.Tasks.complete)
                                    .font(.system(size: 15, weight: .semibold, design: .rounded))
                            }
                            .frame(maxWidth: .infinity)
                            .frame(height: 48)
                            .foregroundColor(Color.appTextOnPrimary)
                            .background(
                                RoundedRectangle(cornerRadius: 16, style: .continuous)
                                    .fill(
                                        LinearGradient(
                                            colors: [Color.appPrimary, Color.appPrimary.opacity(0.9)],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        )
                                    )
                            )
                        }
                    }
                }
            }

            // Secondary Actions
            VStack(spacing: 10) {
                HStack(spacing: 10) {
                    TaskSecondaryButton(
                        icon: "pencil",
                        text: L10n.Tasks.edit,
                        color: Color.appPrimary,
                        action: onEdit
                    )

                    if let onCancel = onCancel {
                        TaskSecondaryButton(
                            icon: "xmark.circle",
                            text: L10n.Tasks.cancel,
                            color: Color.appError,
                            isDestructive: true,
                            action: onCancel
                        )
                    } else if let onUncancel = onUncancel {
                        TaskSecondaryButton(
                            icon: "arrow.uturn.backward",
                            text: L10n.Tasks.restore,
                            color: Color.appPrimary,
                            isFilled: true,
                            action: onUncancel
                        )
                    }
                }

                if task.archived {
                    if let onUnarchive = onUnarchive {
                        TaskSecondaryButton(
                            icon: "tray.and.arrow.up",
                            text: L10n.Tasks.unarchive,
                            color: Color.appPrimary,
                            action: onUnarchive
                        )
                    }
                } else {
                    if let onArchive = onArchive {
                        TaskSecondaryButton(
                            icon: "archivebox",
                            text: L10n.Tasks.archive,
                            color: Color.appTextSecondary,
                            action: onArchive
                        )
                    }
                }
            }
        }
        .padding(OrganicSpacing.cozy)
        .background(TaskCardBackground())
        .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
        .naturalShadow(.medium)
    }
}

// MARK: - Task Metadata Pill

private struct TaskMetadataPill: View {
    let icon: String
    let text: String
    var color: Color = Color.appTextSecondary

    var body: some View {
        HStack(spacing: 6) {
            Image(systemName: icon)
                .font(.system(size: 11, weight: .semibold))
                .foregroundColor(color.opacity(0.8))
            Text(text)
                .font(.system(size: 12, weight: .medium, design: .rounded))
                .foregroundColor(color)
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 6)
        .background(
            Capsule()
                .fill(Color.appBackgroundPrimary.opacity(0.6))
                .overlay(
                    Capsule()
                        .stroke(color.opacity(0.15), lineWidth: 1)
                )
        )
    }
}

// MARK: - Task Secondary Button

private struct TaskSecondaryButton: View {
    let icon: String
    let text: String
    var color: Color = Color.appPrimary
    var isDestructive: Bool = false
    var isFilled: Bool = false
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack(spacing: 6) {
                Image(systemName: icon)
                    .font(.system(size: 13, weight: .semibold))
                Text(text)
                    .font(.system(size: 13, weight: .semibold, design: .rounded))
            }
            .frame(maxWidth: .infinity)
            .frame(height: 40)
            .foregroundColor(isFilled ? Color.appTextOnPrimary : color)
            .background(
                RoundedRectangle(cornerRadius: 14, style: .continuous)
                    .fill(
                        isFilled
                            ? color
                            : (isDestructive ? color.opacity(0.1) : Color.appBackgroundPrimary.opacity(0.5))
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 14, style: .continuous)
                            .stroke(color.opacity(isFilled ? 0 : 0.2), lineWidth: 1)
                    )
            )
        }
    }
}

// MARK: - Task Card Background

private struct TaskCardBackground: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            Color.appBackgroundSecondary

            // Subtle organic blob
            GeometryReader { geo in
                OrganicBlobShape(variation: 1)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(colorScheme == .dark ? 0.06 : 0.04),
                                Color.appPrimary.opacity(0.01)
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.4
                        )
                    )
                    .frame(width: geo.size.width * 0.5, height: geo.size.height * 0.6)
                    .offset(x: geo.size.width * 0.55, y: -geo.size.height * 0.1)
                    .blur(radius: 15)
            }

            // Grain texture
            GrainTexture(opacity: 0.012)
        }
    }
}

#Preview {
    VStack(spacing: 16) {
        TaskCard(
            task: TaskResponse(
                id: 1,
                residenceId: 1,
                createdById: 1,
                createdBy: nil,
                assignedToId: nil,
                assignedTo: nil,
                title: "Clean Gutters",
                description: "Remove all debris from gutters",
                categoryId: 1,
                category: TaskCategory(id: 1, name: "maintenance", description: "", icon: "", color: "", displayOrder: 0),
                priorityId: 2,
                priority: TaskPriority(id: 2, name: "medium", level: 2, color: "", displayOrder: 0),
                inProgress: false,
                frequencyId: 1,
                frequency: TaskFrequency(id: 1, name: "monthly", days: 30, displayOrder: 0),
                customIntervalDays: nil,
                dueDate: "2024-12-15",
                nextDueDate: nil,
                estimatedCost: 150.00,
                actualCost: nil,
                contractorId: nil,
                isCancelled: false,
                isArchived: false,
                parentTaskId: nil,
                templateId: nil,
                completionCount: 0,
                kanbanColumn: nil,
                completions: [],
                createdAt: "2024-01-01T00:00:00Z",
                updatedAt: "2024-01-01T00:00:00Z"
            ),
            onEdit: {},
            onCancel: {},
            onUncancel: nil,
            onMarkInProgress: {},
            onComplete: {},
            onArchive: {},
            onUnarchive: {}
        )
    }
    .padding()
    .background(Color.appBackgroundPrimary)
}
