import SwiftUI
import ComposeApp

// MARK: - Honeycomb Summary View

/// Displays a honeycomb grid of task completions over the last 12 months.
/// Each hexagon represents a completed task, colored by the kanban column
/// the task was in when completed. Empty slots show faint gray hexagons.
struct HoneycombSummaryView: View {
    let summary: CompletionSummary
    let residenceName: String

    private let hexSpacing: CGFloat = 2
    private let colorAlpha: CGFloat = 0.3

    private let rowCount = 12

    var body: some View {
        VStack(spacing: OrganicSpacing.comfortable) {
            // Header with big number
            headerSection

            // Honeycomb grid
            honeycombGrid
                .padding(.horizontal, 4)

            // Month labels
            monthLabels
                .padding(.horizontal, 4)
        }
        .padding(OrganicSpacing.comfortable)
        .background(
            OrganicCardBackground(showBlob: true, blobVariation: 2)
        )
        .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
        .shadow(color: Color.black.opacity(0.06), radius: 8, x: 0, y: 2)
    }

    // MARK: - Header

    private var headerSection: some View {
        VStack(spacing: 8) {
            Text("\(summary.totalAllTime)")
                .font(.system(size: 56, weight: .thin, design: .rounded))
                .foregroundColor(Color.appTextPrimary)

            Text("completions at \(residenceName)")
                .font(.subheadline)
                .foregroundColor(Color.appTextSecondary)
                .multilineTextAlignment(.center)

            if summary.totalLast12Months != summary.totalAllTime {
                Text("\(summary.totalLast12Months) in the last 12 months")
                    .font(.caption)
                    .foregroundColor(Color.appTextSecondary.opacity(0.7))
            }
        }
    }

    // MARK: - Grid

    private var honeycombGrid: some View {
        VStack(spacing: hexSpacing) {
            // Grid rows (top = row 12, bottom = row 1)
            ForEach((0..<rowCount).reversed(), id: \.self) { row in
                HStack(spacing: hexSpacing) {
                    ForEach(Array(summary.months.enumerated()), id: \.offset) { _, month in
                        let hexColors = buildHexColors(for: month)

                        if row < hexColors.count {
                            HexagonShape()
                                .fill(hexColors[row].opacity(colorAlpha))
                                .overlay(
                                    HexagonShape()
                                        .stroke(hexColors[row].opacity(0.7), lineWidth: 1.5)
                                )
                                .aspectRatio(1, contentMode: .fit)
                        } else {
                            HexagonShape()
                                .fill(Color.appTextSecondary.opacity(0.08))
                                .aspectRatio(1, contentMode: .fit)
                        }
                    }
                }
            }

            // Overflow indicators
            HStack(spacing: hexSpacing) {
                ForEach(Array(summary.months.enumerated()), id: \.offset) { _, month in
                    if month.overflow > 0 {
                        Text("+\(month.overflow)")
                            .font(.system(size: 8, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                            .frame(maxWidth: .infinity)
                    } else {
                        Color.clear
                            .frame(maxWidth: .infinity)
                            .frame(height: 10)
                    }
                }
            }
        }
    }

    // MARK: - Month Labels

    private var monthLabels: some View {
        HStack(spacing: hexSpacing) {
            ForEach(Array(summary.months.enumerated()), id: \.offset) { _, month in
                Text(monthAbbreviation(from: month.month))
                    .font(.system(size: 8, weight: .medium))
                    .foregroundColor(Color.appTextSecondary.opacity(0.6))
                    .frame(maxWidth: .infinity)
            }
        }
    }

    // MARK: - Helpers

    /// Build an array of colors for the filled hexes in a month column.
    /// Order: completed (green) first at bottom, then overdue (red), due_soon (orange),
    /// in_progress (purple), upcoming (blue).
    private func buildHexColors(for month: MonthlyCompletionSummary) -> [Color] {
        let fillOrder = [
            "completed_tasks",
            "overdue_tasks",
            "due_soon_tasks",
            "in_progress_tasks",
            "upcoming_tasks"
        ]

        var colors: [Color] = []
        let columnMap = Dictionary(
            month.completions.map { ($0.column, $0) },
            uniquingKeysWith: { first, _ in first }
        )

        for column in fillOrder {
            if let entry = columnMap[column] {
                let color = Color(hex: entry.color) ?? Color.green
                for _ in 0..<min(Int(entry.count), rowCount - colors.count) {
                    colors.append(color)
                }
            }
            if colors.count >= rowCount { break }
        }

        return colors
    }

    private func monthAbbreviation(from monthString: String) -> String {
        // "2025-04" → "Apr"
        let parts = monthString.split(separator: "-")
        guard parts.count == 2, let monthNum = Int(parts[1]) else { return "" }
        let formatter = DateFormatter()
        formatter.dateFormat = "MMM"
        var components = DateComponents()
        components.month = monthNum
        if let date = Calendar.current.date(from: components) {
            return formatter.string(from: date)
        }
        return ""
    }
}

// MARK: - Hexagon Shape

/// A regular hexagon shape (flat-top orientation).
struct HexagonShape: Shape {
    func path(in rect: CGRect) -> Path {
        let w = rect.width
        let h = rect.height
        let cx = rect.midX
        let cy = rect.midY
        // Use the smaller dimension to keep it regular
        let r = min(w, h) / 2

        var path = Path()
        for i in 0..<6 {
            let angle = CGFloat(i) * .pi / 3 - .pi / 6 // flat-top: start at -30°
            let x = cx + r * cos(angle)
            let y = cy + r * sin(angle)
            if i == 0 {
                path.move(to: CGPoint(x: x, y: y))
            } else {
                path.addLine(to: CGPoint(x: x, y: y))
            }
        }
        path.closeSubpath()
        return path
    }
}
