import { type Component, createMemo } from "solid-js";
import { type Task, toggleTask, calculateUrgencyFromDate, setActiveTaskId, store, copyTask } from "@/store";
import { cn } from "@/lib/utils";
import { CheckCircle2, Circle, Clock, ArrowUpCircle, Copy, Users2 } from "lucide-solid";
import { Badge } from "@/components/ui/badge";
import { For } from "solid-js";
import { useTheme } from "./ThemeProvider";
import { getThemeAdjustedColor } from "@/lib/colors";

export const TaskCard: Component<{ task: Task }> = (props) => {
    const { resolvedTheme } = useTheme();
    const urgencyLevel = createMemo(() => calculateUrgencyFromDate(props.task.dueDate));

    const urgencyColor = () => {
        const u = urgencyLevel();
        if (u >= 8) return "text-red-500";
        if (u >= 6) return "text-orange-500";
        if (u >= 4) return "text-blue-500";
        return "text-muted-foreground";
    };

    const formattedDate = () => {
        const date = new Date(props.task.dueDate);
        return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    };

    return (
        <div
            class={cn(
                "group flex items-center p-3 sm:p-4 bg-card border border-border rounded-2xl transition-all duration-500 hover:duration-100 hover:shadow-xl hover:shadow-primary/5 hover:-translate-y-0.5 cursor-pointer w-full min-w-0 overflow-hidden",
                props.task.completed && "opacity-60"
            )}
            onClick={() => setActiveTaskId(props.task.id)}
        >
            <button
                onClick={(e) => { e.stopPropagation(); toggleTask(props.task.id); }}
                class="mr-3 sm:mr-4 text-muted-foreground hover:text-primary transition-colors shrink-0"
            >
                {props.task.completed ? (
                    <CheckCircle2 class="text-green-500" size={22} />
                ) : (
                    <Circle size={22} />
                )}
            </button>

            <div class="flex-1 min-w-0 flex flex-col">
                <h3 class={cn(
                    "text-sm sm:text-base font-semibold truncate transition-all",
                    props.task.completed && "line-through"
                )}>
                    {props.task.title}
                </h3>
                {props.task.content && (
                    <div class="text-[11px] sm:text-xs text-muted-foreground/60 line-clamp-1 mt-1 leading-tight whitespace-pre">
                        {(() => {
                            let html = props.task.content || "";
                            // Replace block tags with newlines first to preserve structure
                            html = html.replace(/<\/p>/gi, '\n')
                                .replace(/<\/div>/gi, '\n')
                                .replace(/<br\s*\/?>/gi, '\n')
                                .replace(/<\/li>/gi, '\n')
                                .replace(/<\/h[1-6]>/gi, '\n');

                            const tmp = document.createElement("DIV");
                            tmp.innerHTML = html;
                            const text = tmp.textContent || tmp.innerText || "";

                            // Replace newlines (and surrounding whitespace) with a wide gap
                            // Using 5 non-breaking spaces worth of visual space
                            return text.trim().replace(/\s*[\r\n]+\s*/g, '     ');
                        })()}
                    </div>
                )}
                <div class="flex flex-wrap items-center gap-x-3 gap-y-1.5 mt-1 min-w-0">
                    {/* Priority */}
                    <div class="flex items-center gap-1.5 shrink-0">
                        <ArrowUpCircle size={12} class="text-primary opacity-60" />
                        <span class="text-[10px] font-medium">P{props.task.priority}</span>
                    </div>

                    {/* Shared Indicator - shows for individual shares OR tag-based ShareRules */}
                    {(() => {
                        const hasIndividualShares = props.task.sharedWith && props.task.sharedWith.length > 0;
                        // Check if any tag-based ShareRules match this task's tags (exclude 'all' type)
                        const hasTagRuleShares = store.shareRules.some(rule =>
                            rule.type === 'tag' &&
                            rule.tagName &&
                            props.task.tags?.includes(rule.tagName)
                        );
                        const isShared = hasIndividualShares || hasTagRuleShares;

                        if (!isShared) return null;

                        const shareCount = (props.task.sharedWith?.length || 0);
                        const tooltip = hasIndividualShares
                            ? `Shared with ${shareCount} user${shareCount > 1 ? 's' : ''}`
                            : 'Shared via tag rule';

                        return (
                            <div class="flex items-center gap-1 shrink-0" title={tooltip}>
                                <Users2 size={11} class="text-muted-foreground/50" />
                            </div>
                        );
                    })()}

                    {/* Tags */}
                    {props.task.tags && props.task.tags.length > 0 && (
                        <div class="flex flex-wrap items-center gap-1 min-w-0">
                            <For each={props.task.tags}>
                                {(tag) => (
                                    <Badge
                                        variant="secondary"
                                        class="h-4 px-1.5 text-[9px] gap-1 bg-muted/50 border-border/50 shrink-0"
                                        style={{
                                            "background-color": (() => {
                                                const def = store.tagDefinitions.find(d => d.name === tag);
                                                const color = getThemeAdjustedColor(def?.color, def?.theme, resolvedTheme());
                                                return color ? `${color}15` : undefined;
                                            })(),
                                            "border-color": (() => {
                                                const def = store.tagDefinitions.find(d => d.name === tag);
                                                const color = getThemeAdjustedColor(def?.color, def?.theme, resolvedTheme());
                                                return color ? `${color}30` : undefined;
                                            })(),
                                            "color": (() => {
                                                const def = store.tagDefinitions.find(d => d.name === tag);
                                                return getThemeAdjustedColor(def?.color, def?.theme, resolvedTheme()) || "inherit";
                                            })()
                                        }}
                                    >
                                        <div
                                            class="w-1 h-1 rounded-full"
                                            style={{
                                                "background-color": (store.tagDefinitions.find(d => d.name === tag)?.value ?? 5) > 5 ? "#22c55e" : (store.tagDefinitions.find(d => d.name === tag)?.value ?? 5) < 5 ? "#ef4444" : "#94a3b8"
                                            }}
                                        />
                                        {tag}
                                    </Badge>
                                )}
                            </For>
                        </div>
                    )}

                    {/* Due Date + Urgency Slide-out */}
                    <div class="relative group/date flex items-center h-5 cursor-help shrink-0 min-w-0">
                        {/* Due Date - Static Layer on Top */}
                        <div class="flex items-center space-x-1 text-[9px] font-bold text-muted-foreground uppercase tracking-wider bg-card relative z-20 pr-1">
                            <Clock size={11} class="text-primary/60" />
                            <span class="truncate">{formattedDate()}</span>
                        </div>

                        {/* Urgency Number - Slides out from behind with fade */}
                        <div class={cn(
                            "absolute left-4 top-0 bottom-0 flex items-center transition-all duration-300 ease-out z-10 opacity-0 group-hover/date:opacity-100 group-hover/date:left-full whitespace-nowrap",
                            urgencyColor()
                        )}>
                            <span class="text-[9px] font-bold ml-2 transition-all duration-300 transform translate-x-[-8px] group-hover/date:translate-x-0 group-hover/date:blur-none blur-[2px]">
                                Urgency {urgencyLevel()}
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <div class="ml-2 sm:ml-4 opacity-100 sm:opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
                <button
                    class="p-1.5 hover:bg-muted rounded-full transition-colors text-muted-foreground hover:text-primary"
                    onClick={(e) => {
                        e.stopPropagation();
                        copyTask(props.task.id);
                    }}
                    title="Duplicate Task"
                >
                    <Copy size={16} />
                </button>
            </div>
        </div>
    );
};
