//
//  HabitRow.swift
//  lichunWebsocket
//
//  Component for displaying habit with quit/stop quit actions
//

import SwiftUI

struct HabitRow: View {
    var habit: Habit
    @ObservedObject var webSocketService: WebSocketService

    var body: some View {
        VStack(alignment: .leading, spacing: AppSpacing.md) {
            HStack(alignment: .top, spacing: AppSpacing.md) {
                // Habit icon with status indicator
                ZStack(alignment: .topTrailing) {
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: habitGradientColors,
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 50, height: 50)
                        .overlay(
                            Image(systemName: habitIcon)
                                .font(.system(size: 22, weight: .semibold))
                                .foregroundColor(.white)
                        )
                        .shadow(
                            color: habitGradientColors[0].opacity(0.3),
                            radius: 8,
                            x: 0,
                            y: 4
                        )

                    // Status badge
                    if habit.status == "quitting" {
                        Circle()
                            .fill(AppColors.success)
                            .frame(width: 16, height: 16)
                            .overlay(
                                Image(systemName: "checkmark")
                                    .font(.system(size: 8, weight: .bold))
                                    .foregroundColor(.white)
                            )
                            .offset(x: 4, y: -4)
                    }
                }

                // Habit info
                VStack(alignment: .leading, spacing: AppSpacing.xs) {
                    Text(habit.name.replacingOccurrences(of: "_", with: " ").capitalized)
                        .font(.appHeadline)
                        .foregroundColor(AppColors.primaryText)
                        .lineLimit(2)
                        .fixedSize(horizontal: false, vertical: true)

                    Text(habit.description)
                        .font(.appBody)
                        .foregroundColor(AppColors.secondaryText)
                        .lineLimit(2)
                        .fixedSize(horizontal: false, vertical: true)

                    // Status label
                    HStack(spacing: 6) {
                        Image(systemName: statusIcon)
                            .font(.system(size: 10, weight: .semibold))
                        Text(statusText)
                            .font(.appCaptionBold)
                    }
                    .foregroundColor(statusColor)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 4)
                    .background(statusColor.opacity(0.15))
                    .cornerRadius(AppSpacing.pillCornerRadius)
                }
                .frame(maxWidth: .infinity, alignment: .leading)

                Spacer(minLength: AppSpacing.sm)

                // Action button
                if habit.status == "active" && habit.habitType == "negative" {
                    quitHabitButton(action: {
                        hapticFeedback(style: .medium)
                        webSocketService.sendMessage(message: WebSocketCommands.quitHabit(habit.name))
                    }, label: "Break", icon: "flame.fill", isQuitting: false)
                } else if habit.status == "quitting" && habit.habitType == "negative" {
                    quitHabitButton(action: {
                        hapticFeedback(style: .light)
                        webSocketService.sendMessage(message: WebSocketCommands.stopQuitHabit(habit.name))
                    }, label: "Stop", icon: "xmark.circle.fill", isQuitting: true)
                }
            }

            // Progress bar for quitting habits
            if habit.status == "quitting" {
                VStack(alignment: .leading, spacing: AppSpacing.xs) {
                    HStack {
                        HStack(spacing: 6) {
                            Image(systemName: "calendar.circle.fill")
                                .font(.system(size: 12))
                                .foregroundColor(AppColors.success)
                            Text("Breaking free")
                                .font(.appCaptionBold)
                                .foregroundColor(AppColors.primaryText)
                        }
                        Spacer()
                        Text("\(habit.quitProgress) / 30 days")
                            .font(.appCaption)
                            .foregroundColor(AppColors.secondaryText)
                    }

                    GeometryReader { geometry in
                        ZStack(alignment: .leading) {
                            // Background
                            RoundedRectangle(cornerRadius: 8)
                                .fill(AppColors.background)
                                .frame(height: 12)

                            // Progress with animated gradient
                            RoundedRectangle(cornerRadius: 8)
                                .fill(
                                    LinearGradient(
                                        colors: [AppColors.success, AppColors.energy],
                                        startPoint: .leading,
                                        endPoint: .trailing
                                    )
                                )
                                .frame(
                                    width: geometry.size.width * (Double(habit.quitProgress) / 30.0),
                                    height: 12
                                )
                                .animation(.spring(response: 0.6, dampingFraction: 0.7), value: habit.quitProgress)

                            // Milestone markers
                            HStack(spacing: 0) {
                                ForEach([0, 7, 14, 21, 28], id: \.self) { day in
                                    Spacer()
                                    if day > 0 {
                                        Circle()
                                            .fill(habit.quitProgress >= day ? AppColors.success : AppColors.secondaryText.opacity(0.3))
                                            .frame(width: 6, height: 6)
                                        Spacer()
                                    }
                                }
                            }
                            .padding(.horizontal, 2)
                        }
                    }
                    .frame(height: 12)

                    // Encouragement text
                    Text(encouragementText)
                        .font(.appCaption)
                        .foregroundColor(AppColors.success)
                        .padding(.top, 4)
                }
                .padding(.top, AppSpacing.xs)
            }
        }
        .padding(AppSpacing.md)
        .background(
            LinearGradient(
                colors: [
                    AppColors.surfaceElevated,
                    AppColors.surfaceElevated.opacity(0.95)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
        .cornerRadius(AppSpacing.largeCornerRadius)
        .overlay(
            RoundedRectangle(cornerRadius: AppSpacing.largeCornerRadius)
                .strokeBorder(
                    AppColors.primaryText.opacity(0.05),
                    lineWidth: 1
                )
        )
        .shadow(
            color: Color.black.opacity(0.08),
            radius: AppSpacing.Shadow.radiusSoft,
            x: 0,
            y: AppSpacing.Shadow.offsetY
        )
    }

    private func quitHabitButton(action: @escaping () -> Void, label: String, icon: String, isQuitting: Bool) -> some View {
        Button(action: action) {
            VStack(spacing: 4) {
                Image(systemName: icon)
                    .font(.system(size: 16, weight: .semibold))
                Text(label)
                    .font(.appCaptionBold)
            }
            .foregroundColor(isQuitting ? AppColors.error : .white)
            .padding(.horizontal, 12)
            .padding(.vertical, 8)
            .background(
                isQuitting ?
                    LinearGradient(
                        colors: [AppColors.error.opacity(0.15)],
                        startPoint: .top,
                        endPoint: .bottom
                    ) :
                    LinearGradient(
                        colors: [AppColors.health, AppColors.health.darker(by: 0.1)],
                        startPoint: .top,
                        endPoint: .bottom
                    )
            )
            .cornerRadius(AppSpacing.cornerRadius)
            .shadow(
                color: isQuitting ? Color.clear : AppColors.health.opacity(0.3),
                radius: 6,
                x: 0,
                y: 3
            )
        }
        .buttonStyle(SquishButtonStyle())
    }

    // MARK: - Computed Properties

    private var habitIcon: String {
        if habit.habitType == "negative" {
            return "exclamationmark.triangle.fill"
        } else {
            return "star.fill"
        }
    }

    private var habitGradientColors: [Color] {
        if habit.status == "quitting" {
            return [AppColors.success, AppColors.energy]
        } else if habit.habitType == "negative" {
            return [AppColors.error, AppColors.error.opacity(0.7)]
        } else {
            return [AppColors.primary, AppColors.accent]
        }
    }

    private var statusIcon: String {
        if habit.status == "quitting" {
            return "arrow.up.circle.fill"
        } else {
            return "circle.fill"
        }
    }

    private var statusText: String {
        if habit.status == "quitting" {
            return "Breaking Habit"
        } else {
            return "Active"
        }
    }

    private var statusColor: Color {
        if habit.status == "quitting" {
            return AppColors.success
        } else {
            return AppColors.error
        }
    }

    private var encouragementText: String {
        let progress = habit.quitProgress
        if progress < 7 {
            return "Great start! Keep going!"
        } else if progress < 14 {
            return "You're doing amazing! One week down!"
        } else if progress < 21 {
            return "Halfway there! You've got this!"
        } else if progress < 28 {
            return "Almost there! Stay strong!"
        } else {
            return "Final stretch! You're incredible!"
        }
    }
}

// MARK: - Preview
// Preview removed - requires proper model initialization
